The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): the model picker keeps its caching without "use memo" (#20815)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 17, 2026 at 00:32 UTC
44ecfd65b6b1ed4d9163f886e7118fe4258454de
1 file changed
+450
-476
apps/web/src/components/chat/ModelPickerContent.tsx
+450
-476
@@ -4,13 +4,23 @@ import {
4
type EnvironmentId,
5
type ProviderDriverKind,
6
type ResolvedKeybindingsConfig,
7
+ MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
8
} from "@t3tools/contracts";
9
import { resolveSelectableModel } from "@t3tools/shared/model";
10
import { useAtomValue } from "@effect/atom-react";
11
import { formatProviderUpdateRequiredNotice } from "@t3tools/client-runtime/providerUpdateRequiredModels";
12
import { useNavigate } from "@tanstack/react-router";
13
import { LegendList, type LegendListRef } from "@legendapp/list/react";
13
-import { memo, useState, useEffect, useEffectEvent, useLayoutEffect, useRef } from "react";
14
+import {
15
+ memo,
16
+ useState,
17
+ useEffect,
18
+ useEffectEvent,
19
+ useLayoutEffect,
20
+ useRef,
21
+ type ReactNode,
22
+ type RefObject,
23
+} from "react";
24
import { ChevronRightIcon } from "lucide-react";
25
import { ModelListRow } from "./ModelListRow";
26
import { ModelPickerSidebar } from "./ModelPickerSidebar";
@@ -156,26 +166,355 @@ function ModelListSeparator() {
166
return <div className="h-0.5" />;
167
}
168
159
-// Every list below keys the virtualized list, the combobox or the shortcut listener, so
160
-// they are derived together and only rebuilt when an input changes.
161
-function useModelPickerLists(
162
- favorites: ReturnType<typeof useEnvironmentModelPreferences>["favorites"],
163
- instanceEntries: ReadonlyArray<ProviderInstanceEntry>,
164
- modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>,
165
- activeInstanceId: ProviderInstanceId,
166
- activeModelSlug: string,
167
- activeInstanceHasSelectableUnavailableModel: boolean,
168
- lockedProvider: ProviderDriverKind | null,
169
- lockedContinuationGroupKey: string | null | undefined,
170
- hasProviderSetup: boolean,
171
- searchQuery: string,
172
- selectedInstanceId: ProviderInstanceId | "favorites",
173
- expandedLegacyInstances: ReadonlySet<ProviderInstanceId>,
174
- getModelDisabledReason:
175
- | ((instanceId: ProviderInstanceId, model: string) => string | null)
176
- | undefined,
177
-) {
178
- "use memo";
169
+function modelJumpLabelsByKey(
170
+ modelKeys: ReadonlyArray<string>,
171
+ keybindings: ResolvedKeybindingsConfig,
172
+ terminalOpen: boolean,
173
+): ReadonlyMap<string, string> {
174
+ const shortcutLabelOptions = {
175
+ platform: navigator.platform,
176
+ context: { terminalFocus: false, terminalOpen, modelPickerOpen: true },
177
+ };
178
+ const mapping = new Map<string, string>();
179
+ for (const [index, modelKey] of modelKeys.entries()) {
180
+ const command = modelPickerJumpCommandForIndex(index);
181
+ const label = command && shortcutLabelForCommand(keybindings, command, shortcutLabelOptions);
182
+ if (label) {
183
+ mapping.set(modelKey, label);
184
+ }
185
+ }
186
+ return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
187
+}
188
+
189
+function ModelPickerProviderNotices({
190
+ setupEntries,
191
+ updateRequiredNotices,
192
+ onRequestClose,
193
+ onOpenProviderSetup,
194
+}: {
195
+ setupEntries: ReadonlyArray<ProviderInstanceEntry>;
196
+ updateRequiredNotices: ReadonlyArray<{ instanceId: ProviderInstanceId; notice: string }>;
197
+ onRequestClose: (() => void) | undefined;
198
+ onOpenProviderSetup: ((instanceId: ProviderInstanceId) => void) | undefined;
199
+}) {
200
+ const navigate = useNavigate();
201
+ return (
202
+ <>
203
+ {setupEntries.length > 0 ? (
204
+ <div className="max-h-44 shrink-0 overflow-y-auto border-t border-border/70 p-2">
205
+ {setupEntries.map((entry) => (
206
+ <div key={entry.instanceId} className="px-1 py-1.5 text-xs leading-snug">
207
+ <p className="line-clamp-3 text-muted-foreground">
208
+ {getProviderStatusMessage(entry.snapshot)}
209
+ </p>
210
+ <InlineButton
211
+ className="mt-1"
212
+ onClick={() => {
213
+ onRequestClose?.();
214
+ onOpenProviderSetup?.(entry.instanceId);
215
+ }}
216
+ >
217
+ {setupEntries.length > 1 ? `Set up ${entry.displayName}` : "Open provider setup"}
218
+ </InlineButton>
219
+ </div>
220
+ ))}
221
+ </div>
222
+ ) : (
223
+ <ComboboxEmpty className="empty:h-0">No models found</ComboboxEmpty>
224
+ )}
225
+ {updateRequiredNotices.map(({ instanceId, notice }) => (
226
+ <p
227
+ key={instanceId}
228
+ className="shrink-0 border-t border-border/70 px-3 py-2 text-xs leading-snug text-muted-foreground"
229
+ >
230
+ {notice}{" "}
231
+ <InlineButton
232
+ onClick={() => {
233
+ onRequestClose?.();
234
+ void navigate({ to: "/settings/providers" });
235
+ }}
236
+ >
237
+ Provider settings
238
+ </InlineButton>
239
+ </p>
240
+ ))}
241
+ </>
242
+ );
243
+}
244
+
245
+// Owns the list's measured height and scroll fades, which change on every scroll and
246
+// resize without touching the picker's model lists.
247
+function ModelPickerList({
248
+ listRef,
249
+ itemKeys,
250
+ extraData,
251
+ renderItem,
252
+}: {
253
+ listRef: RefObject<LegendListRef | null>;
254
+ itemKeys: ReadonlyArray<string>;
255
+ extraData: unknown;
256
+ renderItem: (props: { item: string; index: number }) => ReactNode;
257
+}) {
258
+ const [showTopScrollFade, setShowTopScrollFade] = useState(false);
259
+ const [showBottomScrollFade, setShowBottomScrollFade] = useState(false);
260
+ const [contentSize, setContentSize] = useState(
261
+ () => itemKeys.length * MODEL_LIST_ESTIMATED_ITEM_SIZE,
262
+ );
263
+ useLayoutEffect(() => listRef.current?.getState().listen("totalSize", setContentSize), [listRef]);
264
+ const updateScrollFades = () => {
265
+ const scrollElement = listRef.current?.getScrollableNode();
266
+ if (!(scrollElement instanceof HTMLElement)) {
267
+ return;
268
+ }
269
+ const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
270
+ setShowTopScrollFade(scrollElement.scrollTop > 1);
271
+ setShowBottomScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
272
+ };
273
+
274
+ // Keyed by content: a new disabled-reason closure rebuilds an identical key array.
275
+ const itemListKey = JSON.stringify(itemKeys);
276
+ // A new list starts from the top until the measurement below lands.
277
+ const [fadesResetFor, setFadesResetFor] = useState(itemListKey);
278
+ if (fadesResetFor !== itemListKey) {
279
+ setFadesResetFor(itemListKey);
280
+ setShowTopScrollFade(false);
281
+ setShowBottomScrollFade(itemKeys.length > 5);
282
+ }
283
+ const measureScrollFades = useEffectEvent(updateScrollFades);
284
+ useLayoutEffect(() => {
285
+ let nestedFrame = 0;
286
+ const frame = window.requestAnimationFrame(() => {
287
+ measureScrollFades();
288
+ nestedFrame = window.requestAnimationFrame(() => measureScrollFades());
289
+ });
290
+ return () => {
291
+ window.cancelAnimationFrame(frame);
292
+ window.cancelAnimationFrame(nestedFrame);
293
+ };
294
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new list re-measures its scroll fades once it has laid out.
295
+ }, [itemListKey]);
296
+
297
+ return (
298
+ <div
299
+ className="relative min-h-0 overflow-hidden pr-px"
300
+ style={{
301
+ height: itemKeys.length === 0 ? 0 : `calc(${contentSize}px + var(--spacing) * 5)`,
302
+ }}
303
+ >
304
+ <ComboboxListVirtualized>
305
+ <LegendList<string>
306
+ ref={listRef}
307
+ data={itemKeys}
308
+ extraData={extraData}
309
+ keyExtractor={(modelKey) => modelKey}
310
+ renderItem={renderItem}
311
+ estimatedItemSize={MODEL_LIST_ESTIMATED_ITEM_SIZE}
312
+ drawDistance={480}
313
+ recycleItems
314
+ contentContainerClassName="pl-2 pr-px"
315
+ ItemSeparatorComponent={ModelListSeparator}
316
+ onLayout={updateScrollFades}
317
+ onScroll={updateScrollFades}
318
+ className={cn(
319
+ "scrollbar-gutter-stable h-full overflow-x-hidden overscroll-y-contain py-1.5 [&::-webkit-scrollbar-track]:my-2",
320
+ getVirtualizedScrollFadeClassName({
321
+ top: showTopScrollFade,
322
+ bottom: showBottomScrollFade,
323
+ }),
324
+ )}
325
+ />
326
+ </ComboboxListVirtualized>
327
+ </div>
328
+ );
329
+}
330
+
331
+// Capture phase, so model and provider shortcuts win over the composer underneath.
332
+function WindowKeyDownListener({ onKeyDown }: { onKeyDown: (event: KeyboardEvent) => void }) {
333
+ const handleKeyDown = useEffectEvent(onKeyDown);
334
+ useEffect(() => {
335
+ const listener = (event: KeyboardEvent) => handleKeyDown(event);
336
+ window.addEventListener("keydown", listener, true);
337
+ return () => {
338
+ window.removeEventListener("keydown", listener, true);
339
+ };
340
+ }, []);
341
+ return null;
342
+}
343
+
344
+export const ModelPickerContent = memo(function ModelPickerContent(props: {
345
+ environmentId: EnvironmentId | null;
346
+ activeInstanceId: ProviderInstanceId;
347
+ model: string;
348
+ selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>;
349
+ onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void;
350
+ lockedProvider: ProviderDriverKind | null;
351
+ lockedContinuationGroupKey?: string | null;
352
+ instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
353
+ keybindings?: ResolvedKeybindingsConfig;
354
+ modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
355
+ terminalOpen: boolean;
356
+ onRequestClose?: () => void;
357
+ onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void;
358
+ getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
359
+ onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
360
+}) {
361
+ const {
362
+ keybindings: providedKeybindings,
363
+ modelOptionsByInstance,
364
+ instanceEntries,
365
+ getModelDisabledReason,
366
+ onInstanceModelChange,
367
+ onToggleModel,
368
+ onRequestClose,
369
+ onOpenProviderSetup,
370
+ } = props;
371
+ const [searchQuery, setSearchQuery] = useState("");
372
+ const searchInputRef = useRef<HTMLInputElement>(null);
373
+ const modelListRef = useRef<LegendListRef | null>(null);
374
+ const pickerContentRef = useRef<HTMLDivElement>(null);
375
+ const highlightedModelKeyRef = useRef<string | null>(null);
376
+ const { favorites } = useEnvironmentModelPreferences(props.environmentId);
377
+ const activeEntry = props.instanceEntries.find(
378
+ (entry) => entry.instanceId === props.activeInstanceId,
379
+ );
380
+ const activeModel = resolveModelPickerSelectedModel({
381
+ driverKind: activeEntry?.driverKind,
382
+ model: props.model,
383
+ options: modelOptionsByInstance.get(props.activeInstanceId) ?? [],
384
+ });
385
+ const activeModelSlug =
386
+ activeModel?.slug ?? (props.model === ANTIGRAVITY_DEFAULT_MODEL ? "" : props.model);
387
+ const activeModelKey = activeModelSlug
388
+ ? modelPickerModelKey(props.activeInstanceId, activeModelSlug)
389
+ : null;
390
+ const selectedModelKeys = props.selectedModels?.map((selection) => {
391
+ const entry = instanceEntries.find((entry) => entry.instanceId === selection.instanceId);
392
+ const model = resolveModelPickerSelectedModel({
393
+ driverKind: entry?.driverKind,
394
+ model: selection.model,
395
+ options: modelOptionsByInstance.get(selection.instanceId) ?? [],
396
+ });
397
+ return modelPickerModelKey(selection.instanceId, model?.slug ?? selection.model);
398
+ });
399
+ const selectedModelKeySet = new Set(
400
+ selectedModelKeys ?? (activeModelKey ? [activeModelKey] : []),
401
+ );
402
+ const activeInstanceHasSelectableUnavailableModel =
403
+ activeEntry !== undefined &&
404
+ (modelOptionsByInstance.get(props.activeInstanceId) ?? []).some((option) =>
405
+ shouldIncludeModelPickerOption({
406
+ entry: activeEntry,
407
+ option,
408
+ activeInstanceId: props.activeInstanceId,
409
+ activeModel: activeModelSlug,
410
+ }),
411
+ ) &&
412
+ !isProviderInstancePickerReady(activeEntry);
413
+ const activeInstanceNeedsSetup =
414
+ onOpenProviderSetup !== undefined &&
415
+ activeEntry !== undefined &&
416
+ shouldOfferModelPickerSetup(
417
+ activeEntry,
418
+ modelOptionsByInstance.get(props.activeInstanceId) ?? [],
419
+ );
420
+ const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(
421
+ () => {
422
+ if (
423
+ props.lockedProvider !== null ||
424
+ activeInstanceHasSelectableUnavailableModel ||
425
+ activeInstanceNeedsSetup
426
+ ) {
427
+ return props.activeInstanceId;
428
+ }
429
+ return favorites.length > 0 ? "favorites" : props.activeInstanceId;
430
+ },
431
+ );
432
+ const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
433
+ () =>
434
+ new Set<ProviderInstanceId>(
435
+ modelOptionsByInstance
436
+ .get(props.activeInstanceId)
437
+ ?.some((model) => model.slug === activeModelSlug && model.isLegacy)
438
+ ? [props.activeInstanceId]
439
+ : [],
440
+ ),
441
+ );
442
+ const serverKeybindings = useAtomValue(primaryServerKeybindingsAtom);
443
+ const keybindings = providedKeybindings ?? serverKeybindings;
444
+ const [searchHeight, setSearchHeight] = useState(0);
445
+ const toggleFavorite = useToggleEnvironmentModelFavorite(props.environmentId);
446
+
447
+ const focusSearchInput = () => {
448
+ searchInputRef.current?.focus({ preventScroll: true });
449
+ };
450
+
451
+ const handleSelectInstance = (instanceId: ProviderInstanceId | "favorites") => {
452
+ setSelectedInstanceId(instanceId);
453
+ window.requestAnimationFrame(() => {
454
+ focusSearchInput();
455
+ });
456
+ };
457
+
458
+ useLayoutEffect(() => {
459
+ focusSearchInput();
460
+ const frame = window.requestAnimationFrame(() => {
461
+ focusSearchInput();
462
+ });
463
+ const timeout = window.setTimeout(() => {
464
+ focusSearchInput();
465
+ }, 0);
466
+ return () => {
467
+ window.cancelAnimationFrame(frame);
468
+ window.clearTimeout(timeout);
469
+ };
470
+ }, [focusSearchInput]);
471
+
472
+ const toggleLegacySection = (instanceId: ProviderInstanceId) => {
473
+ setExpandedLegacyInstances((expanded) => {
474
+ const next = new Set(expanded);
475
+ if (next.has(instanceId)) {
476
+ next.delete(instanceId);
477
+ } else {
478
+ next.add(instanceId);
479
+ }
480
+ return next;
481
+ });
482
+ };
483
+
484
+ const handleModelSelect = (
485
+ modelSlug: string,
486
+ instanceId: ProviderInstanceId,
487
+ additive = false,
488
+ ) => {
489
+ if (getModelDisabledReason?.(instanceId, modelSlug)) {
490
+ return;
491
+ }
492
+ const options = modelOptionsByInstance.get(instanceId);
493
+ if (!options) {
494
+ return;
495
+ }
496
+ const entry = instanceEntries.find((candidate) => candidate.instanceId === instanceId);
497
+ if (!entry) {
498
+ return;
499
+ }
500
+ const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);
501
+ if (resolvedModel) {
502
+ if (additive && onToggleModel) {
503
+ onToggleModel(instanceId, resolvedModel);
504
+ } else {
505
+ onInstanceModelChange(instanceId, resolvedModel);
506
+ }
507
+ }
508
+ };
509
+
510
+ const modelJumpShortcutContext = {
511
+ terminalFocus: false,
512
+ terminalOpen: props.terminalOpen,
513
+ modelPickerOpen: true,
514
+ } as const;
515
+ const lockedProvider = props.lockedProvider;
516
+ const lockedContinuationGroupKey = props.lockedContinuationGroupKey;
517
+ const canOpenProviderSetup = onOpenProviderSetup !== undefined;
518
const favoritesSet = (() => {
519
return new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model)));
520
})();
@@ -193,9 +532,9 @@ function useModelPickerLists(
532
const selectableUnavailableInstanceIds = (() => {
533
const instanceIds = new Set<ProviderInstanceId>();
534
if (activeInstanceHasSelectableUnavailableModel) {
196
- instanceIds.add(activeInstanceId);
535
+ instanceIds.add(props.activeInstanceId);
536
}
198
- if (hasProviderSetup) {
537
+ if (canOpenProviderSetup) {
538
for (const entry of instanceEntries) {
539
if (
540
shouldOfferModelPickerSetup(entry, modelOptionsByInstance.get(entry.instanceId) ?? [])
@@ -219,7 +558,7 @@ function useModelPickerLists(
558
!shouldIncludeModelPickerOption({
559
entry,
560
option: model,
222
- activeInstanceId: activeInstanceId,
561
+ activeInstanceId: props.activeInstanceId,
562
activeModel: activeModelSlug,
563
})
564
) {
@@ -347,7 +686,7 @@ function useModelPickerLists(
686
const selectedEntry =
687
selectedInstanceId === "favorites" ? undefined : entryByInstanceId.get(selectedInstanceId);
688
const providerSetupEntries =
350
- !isSearching && hasProviderSetup
689
+ !isSearching && canOpenProviderSetup
690
? instanceEntries.filter(
691
(entry) =>
692
matchesLockedProvider(entry) &&
@@ -361,37 +700,19 @@ function useModelPickerLists(
700
)
701
: [];
702
364
- const updateRequiredNotices = (
365
- isSearching
366
- ? instanceEntries.filter(matchesLockedProvider)
367
- : selectedEntry
368
- ? [selectedEntry]
369
- : []
370
- ).flatMap((entry) => {
371
- const notice = formatProviderUpdateRequiredNotice(entry.snapshot, searchQuery);
703
+ const updateRequiredNotices = instanceEntries.flatMap((entry) => {
704
+ const shown = isSearching
705
+ ? matchesLockedProvider(entry)
706
+ : entry.instanceId === selectedEntry?.instanceId;
707
+ const notice = shown ? formatProviderUpdateRequiredNotice(entry.snapshot, searchQuery) : null;
708
return notice ? [{ instanceId: entry.instanceId, notice }] : [];
709
});
710
375
- const modelJumpCommandByKey = (() => {
376
- const mapping = new Map<
377
- string,
378
- NonNullable<ReturnType<typeof modelPickerJumpCommandForIndex>>
379
- >();
380
- let selectableModelIndex = 0;
381
- for (const model of visibleModels) {
382
- if (getModelDisabledReason?.(model.instanceId, model.slug)) {
383
- continue;
384
- }
385
- const jumpCommand = modelPickerJumpCommandForIndex(selectableModelIndex);
386
- if (!jumpCommand) {
387
- return mapping;
388
- }
389
- mapping.set(modelPickerModelKey(model.instanceId, model.slug), jumpCommand);
390
- selectableModelIndex += 1;
391
- }
392
- return mapping;
393
- })();
394
- const modelJumpModelKeys = [...modelJumpCommandByKey.keys()];
711
+ // The first selectable models get the numbered jump shortcuts, in list order.
712
+ const modelJumpModelKeys = visibleModels
713
+ .filter((model) => !getModelDisabledReason?.(model.instanceId, model.slug))
714
+ .slice(0, MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.length)
715
+ .map((model) => modelPickerModelKey(model.instanceId, model.slug));
716
const allItemKeys = ((): string[] => [
717
...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
718
...new Set(
@@ -416,272 +737,12 @@ function useModelPickerLists(
737
(model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const,
738
),
739
))();
419
- return {
420
- favoritesSet,
421
- entryByInstanceId,
422
- matchesLockedProvider,
423
- selectableUnavailableInstanceIds,
424
- flatModels,
425
- isLocked,
426
- isSearching,
427
- lockedDisabledInstanceIds,
428
- sidebarInstanceEntries,
429
- showSidebar,
430
- instanceOrder,
431
- filteredModels,
432
- legacySection,
433
- visibleModels,
434
- selectedEntry,
435
- providerSetupEntries,
436
- updateRequiredNotices,
437
- modelJumpCommandByKey,
438
- modelJumpModelKeys,
439
- allItemKeys,
440
- filteredItemKeys,
441
- filteredModelByKey,
442
- };
443
-}
444
-
445
-export const ModelPickerContent = memo(function ModelPickerContent(props: {
446
- environmentId: EnvironmentId | null;
447
- activeInstanceId: ProviderInstanceId;
448
- model: string;
449
- selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>;
450
- onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void;
451
- lockedProvider: ProviderDriverKind | null;
452
- lockedContinuationGroupKey?: string | null;
453
- instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
454
- keybindings?: ResolvedKeybindingsConfig;
455
- modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
456
- terminalOpen: boolean;
457
- onRequestClose?: () => void;
458
- onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void;
459
- getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
460
- onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
461
-}) {
462
- const {
463
- keybindings: providedKeybindings,
464
- modelOptionsByInstance,
465
- instanceEntries,
466
- getModelDisabledReason,
467
- onInstanceModelChange,
468
- onToggleModel,
469
- } = props;
470
- const [searchQuery, setSearchQuery] = useState("");
471
- const [showTopScrollFade, setShowTopScrollFade] = useState(false);
472
- const [showBottomScrollFade, setShowBottomScrollFade] = useState(false);
473
- const searchInputRef = useRef<HTMLInputElement>(null);
474
- const modelListRef = useRef<LegendListRef | null>(null);
475
- const pickerContentRef = useRef<HTMLDivElement>(null);
476
- const highlightedModelKeyRef = useRef<string | null>(null);
477
- const { favorites } = useEnvironmentModelPreferences(props.environmentId);
478
- const activeEntry = props.instanceEntries.find(
479
- (entry) => entry.instanceId === props.activeInstanceId,
480
- );
481
- const activeModel = resolveModelPickerSelectedModel({
482
- driverKind: activeEntry?.driverKind,
483
- model: props.model,
484
- options: modelOptionsByInstance.get(props.activeInstanceId) ?? [],
485
- });
486
- const activeModelSlug =
487
- activeModel?.slug ?? (props.model === ANTIGRAVITY_DEFAULT_MODEL ? "" : props.model);
488
- const activeModelKey = activeModelSlug
489
- ? modelPickerModelKey(props.activeInstanceId, activeModelSlug)
490
- : null;
491
- const selectedModelKeys = props.selectedModels?.map((selection) => {
492
- const entry = instanceEntries.find((entry) => entry.instanceId === selection.instanceId);
493
- const model = resolveModelPickerSelectedModel({
494
- driverKind: entry?.driverKind,
495
- model: selection.model,
496
- options: modelOptionsByInstance.get(selection.instanceId) ?? [],
497
- });
498
- return modelPickerModelKey(selection.instanceId, model?.slug ?? selection.model);
499
- });
500
- const selectedModelKeySet = new Set(
501
- selectedModelKeys ?? (activeModelKey ? [activeModelKey] : []),
502
- );
503
- const activeInstanceHasSelectableUnavailableModel =
504
- activeEntry !== undefined &&
505
- (modelOptionsByInstance.get(props.activeInstanceId) ?? []).some((option) =>
506
- shouldIncludeModelPickerOption({
507
- entry: activeEntry,
508
- option,
509
- activeInstanceId: props.activeInstanceId,
510
- activeModel: activeModelSlug,
511
- }),
512
- ) &&
513
- !isProviderInstancePickerReady(activeEntry);
514
- const activeInstanceNeedsSetup =
515
- props.onOpenProviderSetup !== undefined &&
516
- activeEntry !== undefined &&
517
- shouldOfferModelPickerSetup(
518
- activeEntry,
519
- modelOptionsByInstance.get(props.activeInstanceId) ?? [],
520
- );
521
- const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(
522
- () => {
523
- if (
524
- props.lockedProvider !== null ||
525
- activeInstanceHasSelectableUnavailableModel ||
526
- activeInstanceNeedsSetup
527
- ) {
528
- return props.activeInstanceId;
529
- }
530
- return favorites.length > 0 ? "favorites" : props.activeInstanceId;
531
- },
532
- );
533
- const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
534
- () =>
535
- new Set<ProviderInstanceId>(
536
- modelOptionsByInstance
537
- .get(props.activeInstanceId)
538
- ?.some((model) => model.slug === activeModelSlug && model.isLegacy)
539
- ? [props.activeInstanceId]
540
- : [],
541
- ),
542
- );
543
- const serverKeybindings = useAtomValue(primaryServerKeybindingsAtom);
544
- const keybindings = providedKeybindings ?? serverKeybindings;
545
- const navigate = useNavigate();
546
- const toggleFavorite = useToggleEnvironmentModelFavorite(props.environmentId);
547
-
548
- const focusSearchInput = () => {
549
- searchInputRef.current?.focus({ preventScroll: true });
550
- };
551
-
552
- const handleSelectInstance = (instanceId: ProviderInstanceId | "favorites") => {
553
- setSelectedInstanceId(instanceId);
554
- window.requestAnimationFrame(() => {
555
- focusSearchInput();
556
- });
557
- };
558
-
559
- useLayoutEffect(() => {
560
- focusSearchInput();
561
- const frame = window.requestAnimationFrame(() => {
562
- focusSearchInput();
563
- });
564
- const timeout = window.setTimeout(() => {
565
- focusSearchInput();
566
- }, 0);
567
- return () => {
568
- window.cancelAnimationFrame(frame);
569
- window.clearTimeout(timeout);
570
- };
571
- }, [focusSearchInput]);
740
573
- const {
574
- favoritesSet,
575
- entryByInstanceId,
576
- selectableUnavailableInstanceIds,
577
- isLocked,
578
- isSearching,
579
- lockedDisabledInstanceIds,
580
- sidebarInstanceEntries,
581
- showSidebar,
582
- legacySection,
583
- providerSetupEntries,
584
- updateRequiredNotices,
585
- modelJumpCommandByKey,
741
+ const modelJumpLabelByKey = modelJumpLabelsByKey(
742
modelJumpModelKeys,
587
- allItemKeys,
588
- filteredItemKeys,
589
- filteredModelByKey,
590
- } = useModelPickerLists(
591
- favorites,
592
- instanceEntries,
593
- modelOptionsByInstance,
594
- props.activeInstanceId,
595
- activeModelSlug,
596
- activeInstanceHasSelectableUnavailableModel,
597
- props.lockedProvider,
598
- props.lockedContinuationGroupKey,
599
- props.onOpenProviderSetup !== undefined,
600
- searchQuery,
601
- selectedInstanceId,
602
- expandedLegacyInstances,
603
- getModelDisabledReason,
604
- );
605
-
606
- const toggleLegacySection = (instanceId: ProviderInstanceId) => {
607
- setExpandedLegacyInstances((expanded) => {
608
- const next = new Set(expanded);
609
- if (next.has(instanceId)) {
610
- next.delete(instanceId);
611
- } else {
612
- next.add(instanceId);
613
- }
614
- return next;
615
- });
616
- };
617
-
618
- const handleModelSelect = (
619
- modelSlug: string,
620
- instanceId: ProviderInstanceId,
621
- additive = false,
622
- ) => {
623
- if (getModelDisabledReason?.(instanceId, modelSlug)) {
624
- return;
625
- }
626
- const options = modelOptionsByInstance.get(instanceId);
627
- if (!options) {
628
- return;
629
- }
630
- const entry = entryByInstanceId.get(instanceId);
631
- if (!entry) {
632
- return;
633
- }
634
- const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);
635
- if (resolvedModel) {
636
- if (additive && onToggleModel) {
637
- onToggleModel(instanceId, resolvedModel);
638
- } else {
639
- onInstanceModelChange(instanceId, resolvedModel);
640
- }
641
- }
642
- };
643
-
644
- const [modelListContentSize, setModelListContentSize] = useState(
645
- () => filteredItemKeys.length * MODEL_LIST_ESTIMATED_ITEM_SIZE,
646
- );
647
- const [searchHeight, setSearchHeight] = useState(0);
648
- useLayoutEffect(
649
- () => modelListRef.current?.getState().listen("totalSize", setModelListContentSize),
650
- [],
743
+ keybindings,
744
+ props.terminalOpen,
745
);
652
- const modelListHeight =
653
- filteredItemKeys.length === 0 ? 0 : `calc(${modelListContentSize}px + var(--spacing) * 5)`;
654
- const updateModelListScrollFades = () => {
655
- const scrollElement = modelListRef.current?.getScrollableNode();
656
- if (!(scrollElement instanceof HTMLElement)) {
657
- return;
658
- }
659
- const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
660
- setShowTopScrollFade(scrollElement.scrollTop > 1);
661
- setShowBottomScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
662
- };
663
- const modelJumpShortcutContext = {
664
- terminalFocus: false,
665
- terminalOpen: props.terminalOpen,
666
- modelPickerOpen: true,
667
- } as const;
668
- const modelJumpLabelByKey = ((): ReadonlyMap<string, string> => {
669
- if (modelJumpCommandByKey.size === 0) {
670
- return EMPTY_MODEL_JUMP_LABELS;
671
- }
672
- const shortcutLabelOptions = {
673
- platform: navigator.platform,
674
- context: modelJumpShortcutContext,
675
- };
676
- const mapping = new Map<string, string>();
677
- for (const [modelKey, command] of modelJumpCommandByKey) {
678
- const label = shortcutLabelForCommand(keybindings, command, shortcutLabelOptions);
679
- if (label) {
680
- mapping.set(modelKey, label);
681
- }
682
- }
683
- return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
684
- })();
746
const modelListExtraData = {
747
favoritesSet,
748
modelJumpLabelByKey,
@@ -689,7 +750,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
750
selectedModelKeySet,
751
};
752
692
- const onWindowKeyDown = useEffectEvent((event: globalThis.KeyboardEvent) => {
753
+ const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
754
if (event.defaultPrevented || event.repeat || isCommandPaletteOpen()) {
755
return;
756
}
@@ -728,40 +789,11 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
789
return;
790
}
791
handleModelSelect(model.slug, model.instanceId);
731
- });
732
- useEffect(() => {
733
- const listener = (event: globalThis.KeyboardEvent) => onWindowKeyDown(event);
734
- window.addEventListener("keydown", listener, true);
735
- return () => {
736
- window.removeEventListener("keydown", listener, true);
737
- };
738
- }, []);
739
-
740
- // Keyed by content: a new disabled-reason closure rebuilds an identical key array.
741
- const filteredItemListKey = JSON.stringify(filteredItemKeys);
742
- // A new list starts from the top until the measurement below lands.
743
- const [fadesResetFor, setFadesResetFor] = useState(filteredItemListKey);
744
- if (fadesResetFor !== filteredItemListKey) {
745
- setFadesResetFor(filteredItemListKey);
746
- setShowTopScrollFade(false);
747
- setShowBottomScrollFade(filteredItemKeys.length > 5);
748
- }
749
- const measureScrollFades = useEffectEvent(updateModelListScrollFades);
750
- useLayoutEffect(() => {
751
- let nestedFrame = 0;
752
- const frame = window.requestAnimationFrame(() => {
753
- measureScrollFades();
754
- nestedFrame = window.requestAnimationFrame(() => measureScrollFades());
755
- });
756
- return () => {
757
- window.cancelAnimationFrame(frame);
758
- window.cancelAnimationFrame(nestedFrame);
759
- };
760
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new list re-measures its scroll fades once it has laid out.
761
- }, [filteredItemListKey]);
792
+ };
793
794
return (
795
<TooltipProvider delay={0}>
796
+ <WindowKeyDownListener onKeyDown={onWindowKeyDown} />
797
<div
798
ref={pickerContentRef}
799
className="relative flex max-h-86.5 w-screen max-w-90 flex-row overflow-hidden"
@@ -868,7 +900,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
900
if (e.key === "Escape") {
901
e.preventDefault();
902
e.stopPropagation();
871
- props.onRequestClose?.();
903
+ onRequestClose?.();
904
return;
905
}
906
if (e.key === "Enter" && highlightedModelKeyRef.current) {
@@ -894,135 +926,77 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
926
onTouchStart={(e) => e.stopPropagation()}
927
/>
928
897
- <div
898
- className="relative min-h-0 overflow-hidden pr-px"
899
- style={{ height: modelListHeight }}
900
- >
901
- <ComboboxListVirtualized>
902
- <LegendList<string>
903
- ref={modelListRef}
904
- data={filteredItemKeys}
905
- extraData={modelListExtraData}
906
- keyExtractor={(modelKey) => modelKey}
907
- renderItem={({ item: modelKey, index }) => {
908
- if (legacySection?.key === modelKey) {
909
- return (
910
- <ComboboxItem
911
- hideIndicator
912
- index={index}
913
- value={modelKey}
914
- aria-expanded={legacySection.isExpanded}
915
- className="group w-full cursor-pointer"
916
- >
917
- <div className="min-w-0 flex-1 text-left">
918
- <div className="text-xs font-medium leading-snug">Legacy models</div>
919
- <div className="mt-1 text-xs font-normal leading-snug text-muted-foreground/70">
920
- {legacySection.legacyModels.length} models
921
- </div>
922
- </div>
923
- <ChevronRightIcon
924
- className={cn(
925
- "size-4 transition-transform",
926
- legacySection.isExpanded && "rotate-90",
927
- )}
928
- />
929
- </ComboboxItem>
930
- );
931
- }
932
- const model = filteredModelByKey.get(modelKey);
933
- if (!model) {
934
- return null;
935
- }
936
- const disabledReason =
937
- getModelDisabledReason?.(model.instanceId, model.slug) ?? null;
938
- return (
939
- <ModelListRow
940
- key={modelKey}
941
- index={index}
942
- model={model}
943
- instanceId={model.instanceId}
944
- driverKind={model.driverKind}
945
- providerDisplayName={model.instanceDisplayName}
946
- providerAccentColor={model.instanceAccentColor}
947
- acpRegistryAgentId={model.acpRegistryAgentId}
948
- acpRegistryIconUrl={model.acpRegistryIconUrl}
949
- isFavorite={favoritesSet.has(
950
- providerModelKey(model.instanceId, model.slug),
929
+ <ModelPickerList
930
+ listRef={modelListRef}
931
+ itemKeys={filteredItemKeys}
932
+ extraData={modelListExtraData}
933
+ renderItem={({ item: modelKey, index }) => {
934
+ if (legacySection?.key === modelKey) {
935
+ return (
936
+ <ComboboxItem
937
+ hideIndicator
938
+ index={index}
939
+ value={modelKey}
940
+ aria-expanded={legacySection.isExpanded}
941
+ className="group w-full cursor-pointer"
942
+ >
943
+ <div className="min-w-0 flex-1 text-left">
944
+ <div className="text-xs font-medium leading-snug">Legacy models</div>
945
+ <div className="mt-1 text-xs font-normal leading-snug text-muted-foreground/70">
946
+ {legacySection.legacyModels.length} models
947
+ </div>
948
+ </div>
949
+ <ChevronRightIcon
950
+ className={cn(
951
+ "size-4 transition-transform",
952
+ legacySection.isExpanded && "rotate-90",
953
)}
952
- isSelected={
953
- selectedModelKeys !== undefined
954
- ? selectedModelKeySet.has(modelKey)
955
- : modelKey === activeModelKey
956
- }
957
- showSelection={selectedModelKeys !== undefined}
958
- showProvider
959
- preferShortName={!isLocked}
960
- useTriggerLabel={false}
961
- showNewBadge={model.badge === "new"}
962
- unavailable={model.isUnavailable === true}
963
- jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
964
- disabledReason={disabledReason}
965
- onToggleFavorite={() => toggleFavorite(model.instanceId, model.slug)}
954
/>
967
- );
968
- }}
969
- estimatedItemSize={MODEL_LIST_ESTIMATED_ITEM_SIZE}
970
- drawDistance={480}
971
- recycleItems
972
- contentContainerClassName="pl-2 pr-px"
973
- ItemSeparatorComponent={ModelListSeparator}
974
- onLayout={updateModelListScrollFades}
975
- onScroll={updateModelListScrollFades}
976
- className={cn(
977
- "scrollbar-gutter-stable h-full overflow-x-hidden overscroll-y-contain py-1.5 [&::-webkit-scrollbar-track]:my-2",
978
- getVirtualizedScrollFadeClassName({
979
- top: showTopScrollFade,
980
- bottom: showBottomScrollFade,
981
- }),
982
- )}
983
- />
984
- </ComboboxListVirtualized>
985
- </div>
986
- {providerSetupEntries.length > 0 ? (
987
- <div className="max-h-44 shrink-0 overflow-y-auto border-t border-border/70 p-2">
988
- {providerSetupEntries.map((entry) => (
989
- <div key={entry.instanceId} className="px-1 py-1.5 text-xs leading-snug">
990
- <p className="line-clamp-3 text-muted-foreground">
991
- {getProviderStatusMessage(entry.snapshot)}
992
- </p>
993
- <InlineButton
994
- className="mt-1"
995
- onClick={() => {
996
- props.onRequestClose?.();
997
- props.onOpenProviderSetup?.(entry.instanceId);
998
- }}
999
- >
1000
- {providerSetupEntries.length > 1
1001
- ? `Set up ${entry.displayName}`
1002
- : "Open provider setup"}
1003
- </InlineButton>
1004
- </div>
1005
- ))}
1006
- </div>
1007
- ) : (
1008
- <ComboboxEmpty className="empty:h-0">No models found</ComboboxEmpty>
1009
- )}
1010
- {updateRequiredNotices.map(({ instanceId, notice }) => (
1011
- <p
1012
- key={instanceId}
1013
- className="shrink-0 border-t border-border/70 px-3 py-2 text-xs leading-snug text-muted-foreground"
1014
- >
1015
- {notice}{" "}
1016
- <InlineButton
1017
- onClick={() => {
1018
- props.onRequestClose?.();
1019
- void navigate({ to: "/settings/providers" });
1020
- }}
1021
- >
1022
- Provider settings
1023
- </InlineButton>
1024
- </p>
1025
- ))}
955
+ </ComboboxItem>
956
+ );
957
+ }
958
+ const model = filteredModelByKey.get(modelKey);
959
+ if (!model) {
960
+ return null;
961
+ }
962
+ const disabledReason =
963
+ getModelDisabledReason?.(model.instanceId, model.slug) ?? null;
964
+ return (
965
+ <ModelListRow
966
+ key={modelKey}
967
+ index={index}
968
+ model={model}
969
+ instanceId={model.instanceId}
970
+ driverKind={model.driverKind}
971
+ providerDisplayName={model.instanceDisplayName}
972
+ providerAccentColor={model.instanceAccentColor}
973
+ acpRegistryAgentId={model.acpRegistryAgentId}
974
+ acpRegistryIconUrl={model.acpRegistryIconUrl}
975
+ isFavorite={favoritesSet.has(providerModelKey(model.instanceId, model.slug))}
976
+ isSelected={
977
+ selectedModelKeys !== undefined
978
+ ? selectedModelKeySet.has(modelKey)
979
+ : modelKey === activeModelKey
980
+ }
981
+ showSelection={selectedModelKeys !== undefined}
982
+ showProvider
983
+ preferShortName={!isLocked}
984
+ useTriggerLabel={false}
985
+ showNewBadge={model.badge === "new"}
986
+ unavailable={model.isUnavailable === true}
987
+ jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
988
+ disabledReason={disabledReason}
989
+ onToggleFavorite={() => toggleFavorite(model.instanceId, model.slug)}
990
+ />
991
+ );
992
+ }}
993
+ />
994
+ <ModelPickerProviderNotices
995
+ setupEntries={providerSetupEntries}
996
+ updateRequiredNotices={updateRequiredNotices}
997
+ onRequestClose={onRequestClose}
998
+ onOpenProviderSetup={onOpenProviderSetup}
999
+ />
1000
</div>
1001
</Combobox>
1002
</div>