-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathModelDialog.tsx
More file actions
879 lines (816 loc) · 28.5 KB
/
Copy pathModelDialog.tsx
File metadata and controls
879 lines (816 loc) · 28.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type React from 'react';
import process from 'node:process';
import { useCallback, useContext, useMemo, useState } from 'react';
import { Box, Text } from 'ink';
import {
AuthType,
ModelSlashCommandEvent,
logModelSlashCommand,
MAINLINE_CODER_MODEL,
isImageCapable,
parseVisionModelSetting,
resolveModelId,
type AvailableModel as CoreAvailableModel,
type ContentGeneratorConfig,
type InputModalities,
} from '@qwen-code/qwen-code-core';
import { useKeypress } from '../hooks/useKeypress.js';
import { theme } from '../semantic-colors.js';
import { DescriptiveRadioButtonSelect } from './shared/DescriptiveRadioButtonSelect.js';
import { ConfigContext } from '../contexts/ConfigContext.js';
import { UIStateContext, type UIState } from '../contexts/UIStateContext.js';
import { useSettings } from '../contexts/SettingsContext.js';
import { getPersistScopeForModelSelection } from '../../config/modelProvidersScope.js';
import { t } from '../../i18n/index.js';
import {
formatUnsupportedVoiceModelMessage,
isSelectableVoiceModel,
} from '../voice/voice-model.js';
function formatModalities(modalities?: InputModalities): string {
if (!modalities) return t('text-only');
const parts: string[] = [];
if (modalities.image) parts.push(t('image'));
if (modalities.pdf) parts.push(t('pdf'));
if (modalities.audio) parts.push(t('audio'));
if (modalities.video) parts.push(t('video'));
if (parts.length === 0) return t('text-only');
return `${t('text')} · ${parts.join(' · ')}`;
}
/**
* Build a unique selection key for a model entry in the model dialog.
* When baseUrl is present, it's appended after a \0 separator to ensure
* entries with the same model id but different baseUrls get distinct keys.
*/
function buildModelSelectionKey(
authType: string,
modelId: string,
baseUrl?: string,
): string {
const base = `${authType}::${modelId}`;
return baseUrl ? `${base}\0${baseUrl}` : base;
}
/**
* Parse a model selection key back into its components.
*/
function parseModelSelectionKey(key: string): {
authType: string;
modelId: string;
baseUrl?: string;
} {
const sep = '::';
const idx = key.indexOf(sep);
if (idx < 0) return { authType: '', modelId: key };
const authType = key.slice(0, idx);
const rest = key.slice(idx + sep.length);
const nullIdx = rest.indexOf('\0');
if (nullIdx >= 0) {
return {
authType,
modelId: rest.slice(0, nullIdx),
baseUrl: rest.slice(nullIdx + 1),
};
}
return { authType, modelId: rest };
}
/**
* Encode a dialog selection key into the `authType:modelId` form persisted for
* the fast/vision auxiliary models (baseUrl discarded), so duplicate model ids
* across providers stay unambiguous. Handles the three selection-key shapes:
* `authType::modelId[\0baseUrl]`, `$runtime|authType|modelId`, and a bare id.
*/
export function encodeAuxModelSelector(selected: string): string {
if (selected.includes('::')) {
const parsed = parseModelSelectionKey(selected);
return `${parsed.authType}:${parsed.modelId}`;
}
if (selected.startsWith('$runtime|')) {
const parts = selected.split('|');
return parts[1] && parts[2] ? `${parts[1]}:${parts[2]}` : selected;
}
return selected;
}
function encodeVisionModelSelector(selected: string): string {
if (!selected.includes('::')) {
return encodeAuxModelSelector(selected);
}
const parsed = parseModelSelectionKey(selected);
const selector = `${parsed.authType}:${parsed.modelId}`;
return parsed.baseUrl ? `${selector}\0${parsed.baseUrl}` : selector;
}
interface ModelDialogProps {
onClose: () => void;
isFastModelMode?: boolean;
isVoiceModelMode?: boolean;
isVisionModelMode?: boolean;
isCompactionModelMode?: boolean;
}
function maskApiKey(apiKey: string | undefined): string {
if (!apiKey) return `(${t('not set')})`;
const trimmed = apiKey.trim();
if (trimmed.length === 0) return `(${t('not set')})`;
if (trimmed.length <= 6) return '***';
const head = trimmed.slice(0, 3);
const tail = trimmed.slice(-4);
return `${head}…${tail}`;
}
function persistModelSelection(
settings: ReturnType<typeof useSettings>,
modelId: string,
baseUrl?: string,
): void {
const scope = getPersistScopeForModelSelection(settings);
settings.setValue(scope, 'model.name', modelId);
// Persist the paired baseUrl so the correct provider is restored on next
// launch when multiple providers share the same model id. When the selection
// has no baseUrl, write an empty-string tombstone (not undefined): undefined
// is dropped from JSON, so it would not override a stale model.baseUrl left
// in a lower-priority scope, whereas '' is a present value that does.
settings.setValue(scope, 'model.baseUrl', baseUrl ?? '');
}
function persistAuthTypeSelection(
settings: ReturnType<typeof useSettings>,
authType: AuthType,
): void {
const scope = getPersistScopeForModelSelection(settings);
settings.setValue(scope, 'security.auth.selectedType', authType);
}
function hydrateApiKeyEnvFromSettings(
settings: ReturnType<typeof useSettings>,
envKey: string | undefined,
): void {
if (!envKey || process.env[envKey]) {
return;
}
const settingsEnvValue = (
settings?.merged?.env as Record<string, unknown> | undefined
)?.[envKey];
if (
typeof settingsEnvValue === 'string' &&
settingsEnvValue.trim().length > 0
) {
process.env[envKey] = settingsEnvValue;
}
}
interface HandleModelSwitchSuccessParams {
settings: ReturnType<typeof useSettings>;
uiState: UIState | null;
after: ContentGeneratorConfig | undefined;
effectiveAuthType: AuthType | undefined;
effectiveModelId: string;
effectiveBaseUrl: string | undefined;
isRuntime: boolean;
}
function handleModelSwitchSuccess({
settings,
uiState,
after,
effectiveAuthType,
effectiveModelId,
effectiveBaseUrl,
isRuntime,
}: HandleModelSwitchSuccessParams): void {
persistModelSelection(settings, effectiveModelId, effectiveBaseUrl);
if (effectiveAuthType) {
persistAuthTypeSelection(settings, effectiveAuthType);
}
const baseUrl = after?.baseUrl ?? t('(default)');
const maskedKey = maskApiKey(after?.apiKey);
uiState?.historyManager.addItem(
{
type: 'info',
text:
`authType: ${effectiveAuthType ?? `(${t('none')})`}` +
`\n` +
`Using ${isRuntime ? 'runtime ' : ''}model: ${effectiveModelId}` +
`\n` +
`Base URL: ${baseUrl}` +
`\n` +
`API key: ${maskedKey}`,
},
Date.now(),
);
}
function formatContextWindow(size?: number): string {
if (!size) return `(${t('unknown')})`;
return `${size.toLocaleString('en-US')} tokens`;
}
function DetailRow({
label,
value,
}: {
label: string;
value: React.ReactNode;
}): React.JSX.Element {
return (
<Box>
<Box minWidth={16} flexShrink={0}>
<Text color={theme.text.secondary}>{label}:</Text>
</Box>
<Box flexGrow={1} flexDirection="row" flexWrap="wrap">
<Text>{value}</Text>
</Box>
</Box>
);
}
export function ModelDialog({
onClose,
isFastModelMode,
isVoiceModelMode,
isVisionModelMode,
isCompactionModelMode,
}: ModelDialogProps): React.JSX.Element {
const config = useContext(ConfigContext);
const uiState = useContext(UIStateContext);
const settings = useSettings();
// Local error state for displaying errors within the dialog
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [highlightedValue, setHighlightedValue] = useState<string | null>(null);
const authType = config?.getAuthType();
const availableModelEntries = useMemo(() => {
const allModels = config ? config.getAllConfiguredModels() : [];
// Separate runtime models from registry models
const runtimeModels = allModels.filter((m) => m.isRuntimeModel);
const registryModels = allModels.filter(
(m) =>
!m.isRuntimeModel &&
(m.authType !== AuthType.QWEN_OAUTH ||
authType === AuthType.QWEN_OAUTH) &&
(isFastModelMode || !m.fastOnly) &&
(isVoiceModelMode || !m.voiceOnly) &&
(isVisionModelMode || !m.visionOnly) &&
(isCompactionModelMode || !m.visionOnly),
);
// Group registry models by authType
const modelsByAuthTypeMap = new Map<AuthType, CoreAvailableModel[]>();
for (const model of registryModels) {
const authType = model.authType;
if (!modelsByAuthTypeMap.has(authType)) {
modelsByAuthTypeMap.set(authType, []);
}
modelsByAuthTypeMap.get(authType)!.push(model);
}
// Fixed order: qwen-oauth first, then others in a stable order
const authTypeOrder: AuthType[] = [
AuthType.QWEN_OAUTH,
AuthType.USE_OPENAI,
AuthType.USE_ANTHROPIC,
AuthType.USE_GEMINI,
AuthType.USE_VERTEX_AI,
];
// Filter to only include authTypes that have registry models and maintain order
const availableAuthTypes = new Set(modelsByAuthTypeMap.keys());
const orderedAuthTypes = authTypeOrder.filter((t) =>
availableAuthTypes.has(t),
);
// Build ordered list: runtime models first, then registry models grouped by authType
const result: Array<{
authType: AuthType;
model: CoreAvailableModel;
isRuntime?: boolean;
snapshotId?: string;
}> = [];
// Add all runtime models first
for (const runtimeModel of runtimeModels) {
result.push({
authType: runtimeModel.authType,
model: runtimeModel,
isRuntime: true,
snapshotId: runtimeModel.runtimeSnapshotId,
});
}
// Add registry models grouped by authType
for (const t of orderedAuthTypes) {
for (const model of modelsByAuthTypeMap.get(t) ?? []) {
result.push({ authType: t, model, isRuntime: false });
}
}
return result;
}, [
authType,
config,
isFastModelMode,
isVoiceModelMode,
isVisionModelMode,
isCompactionModelMode,
]);
const MODEL_OPTIONS = useMemo(
() =>
availableModelEntries.map(
({ authType: t2, model, isRuntime, snapshotId }) => {
const value =
isRuntime && snapshotId
? snapshotId
: buildModelSelectionKey(t2, model.id, model.baseUrl);
const isQwenOAuth = t2 === AuthType.QWEN_OAUTH;
const title = (
<Text>
<Text
bold
color={
isQwenOAuth
? theme.status.warning
: isRuntime
? theme.status.warning
: theme.text.accent
}
>
[{t2}]
</Text>
<Text>{` ${model.label}`}</Text>
{model.id !== model.label && (
<Text color={theme.text.secondary} italic>
{' '}
({model.id})
</Text>
)}
{isRuntime && (
<Text color={theme.status.warning}> (Runtime)</Text>
)}
{isQwenOAuth && !isRuntime && (
<Text color={theme.status.warning}> ({t('Discontinued')})</Text>
)}
</Text>
);
// Include runtime / discontinued indicator in description
let description = model.description || '';
if (isRuntime) {
description = description
? `${description} (Runtime)`
: 'Runtime model';
}
if (isQwenOAuth && !isRuntime) {
description = t('Discontinued — switch to Coding Plan or API Key');
}
return {
value,
title,
description,
key: value,
};
},
),
[availableModelEntries],
);
// In fast model mode, default to the currently configured fast model
const fastModelSetting = settings?.merged?.fastModel as string | undefined;
const voiceModelSetting = settings?.merged?.voiceModel as string | undefined;
const visionModelSetting = settings?.merged?.visionModel as
string | undefined;
const parsedVisionModelValue = parseVisionModelSetting(visionModelSetting);
const parsedFastModelSetting = useMemo(() => {
if (!isFastModelMode) return undefined;
try {
return resolveModelId(fastModelSetting);
} catch {
return undefined;
}
}, [fastModelSetting, isFastModelMode]);
const parsedVisionModelSetting = useMemo(() => {
if (!isVisionModelMode) return undefined;
try {
return resolveModelId(parsedVisionModelValue?.selector);
} catch {
return undefined;
}
}, [parsedVisionModelValue?.selector, isVisionModelMode]);
const preferredModelId =
isFastModelMode && parsedFastModelSetting
? parsedFastModelSetting.modelId
: isVisionModelMode && parsedVisionModelSetting
? parsedVisionModelSetting.modelId
: config?.getModel() || MAINLINE_CODER_MODEL;
// Check if current model is a runtime model
// Runtime snapshot ID is already in $runtime|${authType}|${modelId} format
const activeRuntimeSnapshot =
isFastModelMode ||
isVoiceModelMode ||
isVisionModelMode ||
isCompactionModelMode
? undefined // fast/voice/vision/compaction models are never runtime model selections
: config?.getActiveRuntimeModelSnapshot?.();
const currentBaseUrl = config
?.getModelsConfig()
.getGenerationConfig()?.baseUrl;
// When `/model --fast <bare-id>` validated the model across all providers,
// the setting persists as a bare model ID (no authType prefix) so that
// runtime cross-auth lookups still work. Highlight the row that owns it
// regardless of which provider that turns out to be — otherwise the
// dialog would default to the current auth's first row and Enter would
// silently overwrite the user's fast-model setting.
const preferredFastModelEntry =
isFastModelMode && parsedFastModelSetting
? parsedFastModelSetting.authType
? availableModelEntries.find(
({ authType: t2, model }) =>
t2 === parsedFastModelSetting.authType &&
model.id === parsedFastModelSetting.modelId,
)
: availableModelEntries.find(
({ model }) => model.id === parsedFastModelSetting.modelId,
)
: undefined;
const preferredVoiceModelEntry =
isVoiceModelMode && voiceModelSetting
? availableModelEntries.find(
({ model }) => model.id === voiceModelSetting,
)
: undefined;
// Like fast mode, the vision setting may persist as a bare id (cross-provider)
// or an authType:modelId selector — highlight whichever row owns it.
const matchesVisionModelBaseUrl = (model: CoreAvailableModel): boolean =>
!parsedVisionModelValue?.baseUrl ||
model.baseUrl === parsedVisionModelValue.baseUrl;
const preferredVisionModelEntry =
isVisionModelMode && parsedVisionModelSetting
? parsedVisionModelSetting.authType
? availableModelEntries.find(
({ authType: t2, model }) =>
t2 === parsedVisionModelSetting.authType &&
model.id === parsedVisionModelSetting.modelId &&
matchesVisionModelBaseUrl(model),
)
: availableModelEntries.find(
({ model }) =>
model.id === parsedVisionModelSetting.modelId &&
matchesVisionModelBaseUrl(model),
)
: undefined;
const preferredKey = activeRuntimeSnapshot
? activeRuntimeSnapshot.id
: preferredVoiceModelEntry
? buildModelSelectionKey(
preferredVoiceModelEntry.authType,
preferredVoiceModelEntry.model.id,
preferredVoiceModelEntry.model.baseUrl,
)
: preferredVisionModelEntry
? buildModelSelectionKey(
preferredVisionModelEntry.authType,
preferredVisionModelEntry.model.id,
preferredVisionModelEntry.model.baseUrl,
)
: preferredFastModelEntry
? buildModelSelectionKey(
preferredFastModelEntry.authType,
preferredFastModelEntry.model.id,
preferredFastModelEntry.model.baseUrl,
)
: authType
? buildModelSelectionKey(authType, preferredModelId, currentBaseUrl)
: '';
useKeypress(
(key) => {
if (
key.name === 'escape' ||
(key.name === 'left' &&
(isFastModelMode || isVoiceModelMode || isVisionModelMode))
) {
onClose();
}
},
{ isActive: true },
);
const initialIndex = useMemo(() => {
const index = MODEL_OPTIONS.findIndex(
(option) => option.value === preferredKey,
);
return index === -1 ? 0 : index;
}, [MODEL_OPTIONS, preferredKey]);
const handleHighlight = useCallback((value: string) => {
setHighlightedValue(value);
}, []);
const highlightedEntry = useMemo(() => {
const key = highlightedValue ?? preferredKey;
return availableModelEntries.find(
({ authType: t2, model, isRuntime, snapshotId }) => {
const v =
isRuntime && snapshotId
? snapshotId
: buildModelSelectionKey(t2, model.id, model.baseUrl);
return v === key;
},
);
}, [highlightedValue, preferredKey, availableModelEntries]);
const handleSelect = useCallback(
async (selected: string) => {
setErrorMessage(null);
const selectedEntry = availableModelEntries.find(
({ authType: t2, model, isRuntime, snapshotId }) => {
const value =
isRuntime && snapshotId
? snapshotId
: buildModelSelectionKey(t2, model.id, model.baseUrl);
return value === selected;
},
);
if (isVoiceModelMode) {
if (!selectedEntry) {
setErrorMessage(t('Selected voice model is unavailable.'));
return;
}
const voiceModel = selectedEntry.model.id;
if (!isSelectableVoiceModel(selectedEntry.model)) {
setErrorMessage(formatUnsupportedVoiceModelMessage(voiceModel));
return;
}
const matchingEntries = availableModelEntries.filter(
({ model }) => model.id === voiceModel,
);
if (matchingEntries.length > 1) {
setErrorMessage(
t(
"Voice model '{{model}}' is configured more than once. Remove duplicate model ids before selecting it for voice transcription.",
{ model: voiceModel },
),
);
return;
}
const scope = getPersistScopeForModelSelection(settings);
settings.setValue(scope, 'voiceModel', voiceModel);
uiState?.historyManager.addItem(
{
type: 'success',
text: `${t('Voice Model')}: ${voiceModel}`,
},
Date.now(),
);
onClose();
return;
}
hydrateApiKeyEnvFromSettings(settings, selectedEntry?.model.envKey);
// Fast model mode: save authType:modelId so duplicate model ids across
// providers remain unambiguous. baseUrl is intentionally discarded.
if (isFastModelMode) {
const fastModel = encodeAuxModelSelector(selected);
const scope = getPersistScopeForModelSelection(settings);
settings.setValue(scope, 'fastModel', fastModel);
// Sync the runtime Config so forked agents pick up the change immediately.
config?.setFastModel(fastModel);
uiState?.historyManager.addItem(
{
type: 'success',
text: `${t('Fast Model')}: ${fastModel}`,
},
Date.now(),
);
onClose();
return;
}
// Vision model mode: keep the selected row's baseUrl when present so
// same-provider OpenAI-compatible endpoints with the same id stay distinct.
if (isVisionModelMode) {
const visionModel = encodeVisionModelSelector(selected);
const visionModelDisplay =
parseVisionModelSetting(visionModel)?.selector ?? visionModel;
// Pinning the primary itself is ignored by the bridge at runtime, so
// reject it here instead of persisting a dead pin and reporting success.
if (
selectedEntry &&
config?.isCurrentPrimaryModel(selectedEntry.model)
) {
setErrorMessage(
t(
"'{{model}}' is the current primary model and cannot be used as the vision bridge.",
{ model: visionModelDisplay },
),
);
return;
}
const scope = getPersistScopeForModelSelection(settings);
settings.setValue(scope, 'visionModel', visionModel);
// Sync runtime Config so the vision bridge picks it up without a restart.
config?.setVisionModel(visionModel);
// Honor the pin even if the model isn't image-capable, but warn — the
// bridge will send images to it.
const visionWarning =
selectedEntry && !isImageCapable(selectedEntry.model)
? `\n${t("⚠ '{{model}}' is not a known image-capable model; the vision bridge may fail on images.", { model: visionModelDisplay })}`
: '';
uiState?.historyManager.addItem(
{
type: 'success',
text: `${t('Vision Model')}: ${visionModelDisplay}${visionWarning}`,
},
Date.now(),
);
onClose();
return;
}
// Block selection of discontinued qwen-oauth models
// (only block non-runtime OAuth; runtime OAuth models from existing
// cached tokens are still allowed to work until the server rejects them)
const isQwenOAuthSelection =
selected.startsWith(`${AuthType.QWEN_OAUTH}::`) ||
(selected.startsWith('$runtime|') &&
selected.split('|')[1] === AuthType.QWEN_OAUTH);
const isRuntimeOAuthSelection = selected.startsWith(
`$runtime|${AuthType.QWEN_OAUTH}|`,
);
if (isQwenOAuthSelection && !isRuntimeOAuthSelection) {
setErrorMessage(
t(
'Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.',
),
);
return;
}
let after: ContentGeneratorConfig | undefined;
let effectiveAuthType: AuthType | undefined;
let effectiveModelId = selected;
let isRuntime = false;
if (!config) {
onClose();
return;
}
try {
// Determine if this is a runtime model selection
// Runtime model format: $runtime|${authType}|${modelId}
isRuntime = selected.startsWith('$runtime|');
let selectedAuthType: AuthType;
let modelId: string;
let selectedBaseUrl: string | undefined;
if (isRuntime) {
// For runtime models, extract authType from the snapshot ID
// Format: $runtime|${authType}|${modelId}
const parts = selected.split('|');
if (parts.length >= 2 && parts[0] === '$runtime') {
selectedAuthType = parts[1] as AuthType;
} else {
selectedAuthType = authType as AuthType;
}
modelId = selected; // Pass the full snapshot ID to switchModel
} else {
const parsed = parseModelSelectionKey(selected);
selectedAuthType = (parsed.authType || authType) as AuthType;
modelId = parsed.modelId;
selectedBaseUrl = parsed.baseUrl;
}
await config.switchModel(selectedAuthType, modelId, {
...(selectedAuthType !== authType &&
selectedAuthType === AuthType.QWEN_OAUTH
? { requireCachedCredentials: true }
: {}),
baseUrl: selectedBaseUrl,
});
if (!isRuntime) {
const event = new ModelSlashCommandEvent(modelId);
logModelSlashCommand(config, event);
}
after = config.getContentGeneratorConfig?.() as
ContentGeneratorConfig | undefined;
effectiveAuthType = after?.authType ?? selectedAuthType ?? authType;
effectiveModelId = after?.model ?? modelId;
} catch (e) {
const baseErrorMessage = e instanceof Error ? e.message : String(e);
// Use parsed modelId for display to avoid showing raw selection key
// (which contains invisible \0 separator between modelId and baseUrl)
const displayModelId = isRuntime
? effectiveModelId
: parseModelSelectionKey(selected).modelId;
const errorPrefix = isRuntime
? 'Failed to switch to runtime model.'
: `Failed to switch model to '${displayModelId}'.`;
setErrorMessage(`${errorPrefix}\n\n${baseErrorMessage}`);
return;
}
handleModelSwitchSuccess({
settings,
uiState,
after,
effectiveAuthType,
effectiveModelId,
// Persist the selected provider's baseUrl so the right provider is
// restored next launch when several share the same id. Pair it with the
// same resolved config that effectiveModelId comes from (`after`) so the
// persisted (model.name, model.baseUrl) stays consistent even if
// switchModel transforms the id; fall back to the picker entry's
// baseUrl. Runtime models are keyed by snapshot id, so no disambiguator.
effectiveBaseUrl: isRuntime
? undefined
: (after?.baseUrl ?? selectedEntry?.model.baseUrl),
isRuntime,
});
onClose();
},
[
authType,
config,
onClose,
settings,
uiState,
setErrorMessage,
isFastModelMode,
isVoiceModelMode,
isVisionModelMode,
availableModelEntries,
],
);
const hasModels = MODEL_OPTIONS.length > 0;
return (
<Box
borderStyle="round"
borderColor={theme.border.default}
flexDirection="column"
padding={1}
width="100%"
>
<Text bold>
{isVoiceModelMode
? t('Select Voice Model')
: isVisionModelMode
? t('Select Vision Model')
: isFastModelMode
? t('Select Fast Model')
: t('Select Model')}
</Text>
{!hasModels ? (
<Box marginTop={1} flexDirection="column">
<Text color={theme.status.warning}>
{t(
'No models available for the current authentication type ({{authType}}).',
{
authType: authType ? String(authType) : t('(none)'),
},
)}
</Text>
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t(
'Please configure models in settings.modelProviders or use environment variables.',
)}
</Text>
</Box>
</Box>
) : (
<Box marginTop={1}>
<DescriptiveRadioButtonSelect
items={MODEL_OPTIONS}
onSelect={handleSelect}
onHighlight={handleHighlight}
initialIndex={initialIndex}
showNumbers={true}
/>
</Box>
)}
{highlightedEntry && (
<Box marginTop={1} flexDirection="column">
<Box
borderStyle="single"
borderTop
borderBottom={false}
borderLeft={false}
borderRight={false}
borderColor={theme.border.default}
/>
{highlightedEntry.authType === AuthType.QWEN_OAUTH &&
!highlightedEntry.isRuntime && (
<Box marginTop={1}>
<Text color={theme.status.warning}>
⚠ {t('Discontinued — switch to Coding Plan or API Key')}
</Text>
</Box>
)}
<DetailRow
label={t('Modality')}
value={formatModalities(highlightedEntry.model.modalities)}
/>
<DetailRow
label={t('Context Window')}
value={formatContextWindow(
highlightedEntry.model.contextWindowSize,
)}
/>
{highlightedEntry.authType !== AuthType.QWEN_OAUTH && (
<>
<DetailRow
label="Base URL"
value={highlightedEntry.model.baseUrl ?? t('(default)')}
/>
<DetailRow
label="API Key"
value={highlightedEntry.model.envKey ?? t('(not set)')}
/>
</>
)}
</Box>
)}
{errorMessage && (
<Box marginTop={1} flexDirection="column" paddingX={1}>
<Text color={theme.status.error} wrap="wrap">
✕ {errorMessage}
</Text>
</Box>
)}
<Box marginTop={1} flexDirection="column">
<Text color={theme.text.secondary}>
{t('Enter to select, ↑↓ to navigate, Esc to close')}
</Text>
</Box>
</Box>
);
}