@devries-cameron20 / t3code-1 / commits / 07528262fc
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(web): the model picker compiles without manual memoization (#20706)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 16, 2026 at 22:42 UTC 07528262fc9cf1f2b4b2cb59e96f2023def09f73
1 file changed +365 -333
apps/web/src/components/chat/ModelPickerContent.tsx
+365 -333
@@ -10,7 +10,7 @@ import { useAtomValue } from "@effect/atom-react";
10 import { formatProviderUpdateRequiredNotice } from "@t3tools/client-runtime/providerUpdateRequiredModels";
11 import { useNavigate } from "@tanstack/react-router";
12 import { LegendList, type LegendListRef } from "@legendapp/list/react";
13 -import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react";
13 +import { memo, useState, useEffect, useEffectEvent, useLayoutEffect, useRef } from "react";
14 import { ChevronRightIcon } from "lucide-react";
15 import { ModelListRow } from "./ModelListRow";
16 import { ModelPickerSidebar } from "./ModelPickerSidebar";
@@ -156,166 +156,46 @@ function ModelListSeparator() {
156 return <div className="h-0.5" />;
157 }
158
159 -export const ModelPickerContent = memo(function ModelPickerContent(props: {
160 - environmentId: EnvironmentId | null;
161 - activeInstanceId: ProviderInstanceId;
162 - model: string;
163 - selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>;
164 - onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void;
165 - lockedProvider: ProviderDriverKind | null;
166 - lockedContinuationGroupKey?: string | null;
167 - instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
168 - keybindings?: ResolvedKeybindingsConfig;
169 - modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
170 - terminalOpen: boolean;
171 - onRequestClose?: () => void;
172 - onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void;
173 - getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
174 - onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
175 -}) {
176 - const {
177 - keybindings: providedKeybindings,
178 - modelOptionsByInstance,
179 - instanceEntries,
180 - getModelDisabledReason,
181 - onInstanceModelChange,
182 - onToggleModel,
183 - } = props;
184 - const [searchQuery, setSearchQuery] = useState("");
185 - const [showTopScrollFade, setShowTopScrollFade] = useState(false);
186 - const [showBottomScrollFade, setShowBottomScrollFade] = useState(false);
187 - const searchInputRef = useRef<HTMLInputElement>(null);
188 - const modelListRef = useRef<LegendListRef | null>(null);
189 - const pickerContentRef = useRef<HTMLDivElement>(null);
190 - const highlightedModelKeyRef = useRef<string | null>(null);
191 - const { favorites } = useEnvironmentModelPreferences(props.environmentId);
192 - const activeEntry = props.instanceEntries.find(
193 - (entry) => entry.instanceId === props.activeInstanceId,
194 - );
195 - const activeModel = resolveModelPickerSelectedModel({
196 - driverKind: activeEntry?.driverKind,
197 - model: props.model,
198 - options: modelOptionsByInstance.get(props.activeInstanceId) ?? [],
199 - });
200 - const activeModelSlug =
201 - activeModel?.slug ?? (props.model === ANTIGRAVITY_DEFAULT_MODEL ? "" : props.model);
202 - const activeModelKey = activeModelSlug
203 - ? modelPickerModelKey(props.activeInstanceId, activeModelSlug)
204 - : null;
205 - const selectedModelKeys = useMemo(
206 - () =>
207 - props.selectedModels?.map((selection) => {
208 - const entry = instanceEntries.find((entry) => entry.instanceId === selection.instanceId);
209 - const model = resolveModelPickerSelectedModel({
210 - driverKind: entry?.driverKind,
211 - model: selection.model,
212 - options: modelOptionsByInstance.get(selection.instanceId) ?? [],
213 - });
214 - return modelPickerModelKey(selection.instanceId, model?.slug ?? selection.model);
215 - }),
216 - [instanceEntries, modelOptionsByInstance, props.selectedModels],
217 - );
218 - const selectedModelKeySet = useMemo(
219 - () => new Set(selectedModelKeys ?? (activeModelKey ? [activeModelKey] : [])),
220 - [selectedModelKeys, activeModelKey],
221 - );
222 - const activeInstanceHasSelectableUnavailableModel =
223 - activeEntry !== undefined &&
224 - (modelOptionsByInstance.get(props.activeInstanceId) ?? []).some((option) =>
225 - shouldIncludeModelPickerOption({
226 - entry: activeEntry,
227 - option,
228 - activeInstanceId: props.activeInstanceId,
229 - activeModel: activeModelSlug,
230 - }),
231 - ) &&
232 - !isProviderInstancePickerReady(activeEntry);
233 - const activeInstanceNeedsSetup =
234 - props.onOpenProviderSetup !== undefined &&
235 - activeEntry !== undefined &&
236 - shouldOfferModelPickerSetup(
237 - activeEntry,
238 - modelOptionsByInstance.get(props.activeInstanceId) ?? [],
239 - );
240 - const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(
241 - () => {
242 - if (
243 - props.lockedProvider !== null ||
244 - activeInstanceHasSelectableUnavailableModel ||
245 - activeInstanceNeedsSetup
246 - ) {
247 - return props.activeInstanceId;
248 - }
249 - return favorites.length > 0 ? "favorites" : props.activeInstanceId;
250 - },
251 - );
252 - const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
253 - () =>
254 - new Set<ProviderInstanceId>(
255 - modelOptionsByInstance
256 - .get(props.activeInstanceId)
257 - ?.some((model) => model.slug === activeModelSlug && model.isLegacy)
258 - ? [props.activeInstanceId]
259 - : [],
260 - ),
261 - );
262 - const serverKeybindings = useAtomValue(primaryServerKeybindingsAtom);
263 - const keybindings = providedKeybindings ?? serverKeybindings;
264 - const navigate = useNavigate();
265 - const toggleFavorite = useToggleEnvironmentModelFavorite(props.environmentId);
266 -
267 - const focusSearchInput = useCallback(() => {
268 - searchInputRef.current?.focus({ preventScroll: true });
269 - }, []);
270 -
271 - const handleSelectInstance = useCallback(
272 - (instanceId: ProviderInstanceId | "favorites") => {
273 - setSelectedInstanceId(instanceId);
274 - window.requestAnimationFrame(() => {
275 - focusSearchInput();
276 - });
277 - },
278 - [focusSearchInput],
279 - );
280 -
281 - useLayoutEffect(() => {
282 - focusSearchInput();
283 - const frame = window.requestAnimationFrame(() => {
284 - focusSearchInput();
285 - });
286 - const timeout = window.setTimeout(() => {
287 - focusSearchInput();
288 - }, 0);
289 - return () => {
290 - window.cancelAnimationFrame(frame);
291 - window.clearTimeout(timeout);
292 - };
293 - }, [focusSearchInput]);
294 -
295 - const favoritesSet = useMemo(() => {
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";
179 + const favoritesSet = (() => {
180 return new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model)));
297 - }, [favorites]);
181 + })();
182
299 - const entryByInstanceId = useMemo(
300 - () => new Map(instanceEntries.map((entry) => [entry.instanceId, entry])),
301 - [instanceEntries],
302 - );
303 - const matchesLockedProvider = useCallback(
304 - (entry: Pick<ProviderInstanceEntry, "driverKind" | "continuationGroupKey">): boolean => {
305 - if (props.lockedProvider === null) return true;
306 - if (entry.driverKind !== props.lockedProvider) return false;
307 - if (!props.lockedContinuationGroupKey) return true;
308 - return entry.continuationGroupKey === props.lockedContinuationGroupKey;
309 - },
310 - [props.lockedContinuationGroupKey, props.lockedProvider],
311 - );
183 + const entryByInstanceId = new Map(instanceEntries.map((entry) => [entry.instanceId, entry]));
184 + const matchesLockedProvider = (
185 + entry: Pick<ProviderInstanceEntry, "driverKind" | "continuationGroupKey">,
186 + ): boolean => {
187 + if (lockedProvider === null) return true;
188 + if (entry.driverKind !== lockedProvider) return false;
189 + if (!lockedContinuationGroupKey) return true;
190 + return entry.continuationGroupKey === lockedContinuationGroupKey;
191 + };
192
313 - const selectableUnavailableInstanceIds = useMemo(() => {
193 + const selectableUnavailableInstanceIds = (() => {
194 const instanceIds = new Set<ProviderInstanceId>();
195 if (activeInstanceHasSelectableUnavailableModel) {
316 - instanceIds.add(props.activeInstanceId);
196 + instanceIds.add(activeInstanceId);
197 }
318 - if (props.onOpenProviderSetup) {
198 + if (hasProviderSetup) {
199 for (const entry of instanceEntries) {
200 if (
201 shouldOfferModelPickerSetup(entry, modelOptionsByInstance.get(entry.instanceId) ?? [])
@@ -325,15 +205,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
205 }
206 }
207 return instanceIds.size > 0 ? instanceIds : undefined;
328 - }, [
329 - activeInstanceHasSelectableUnavailableModel,
330 - instanceEntries,
331 - modelOptionsByInstance,
332 - props.activeInstanceId,
333 - props.onOpenProviderSetup,
334 - ]);
208 + })();
209
336 - const flatModels = useMemo(() => {
210 + const flatModels = (() => {
211 const out: ModelPickerItem[] = [];
212 for (const [instanceId, models] of modelOptionsByInstance) {
213 const entry = entryByInstanceId.get(instanceId);
@@ -345,7 +219,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
219 !shouldIncludeModelPickerOption({
220 entry,
221 option: model,
348 - activeInstanceId: props.activeInstanceId,
222 + activeInstanceId: activeInstanceId,
223 activeModel: activeModelSlug,
224 })
225 ) {
@@ -372,11 +246,11 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
246 }
247 }
248 return out;
375 - }, [modelOptionsByInstance, entryByInstanceId, props.activeInstanceId, activeModelSlug]);
249 + })();
250
377 - const isLocked = props.lockedProvider !== null;
251 + const isLocked = lockedProvider !== null;
252 const isSearching = searchQuery.trim().length > 0;
379 - const lockedDisabledInstanceIds = useMemo(() => {
253 + const lockedDisabledInstanceIds = (() => {
254 if (!isLocked) {
255 return undefined;
256 }
@@ -387,8 +261,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
261 }
262 }
263 return disabled;
390 - }, [instanceEntries, isLocked, matchesLockedProvider]);
391 - const sidebarInstanceEntries = useMemo(() => {
264 + })();
265 + const sidebarInstanceEntries = (() => {
266 const enabledEntries = instanceEntries.filter(isProviderInstancePickerVisible);
267 if (!isLocked) {
268 return enabledEntries;
@@ -403,19 +277,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
277 }
278 }
279 return [...available, ...disabled];
406 - }, [instanceEntries, isLocked, matchesLockedProvider]);
280 + })();
281 const showSidebar = !isSearching && sidebarInstanceEntries.length > 0;
408 - const instanceOrder = useMemo(
409 - () => instanceEntries.map((entry) => entry.instanceId),
410 - [instanceEntries],
411 - );
282 + const instanceOrder = instanceEntries.map((entry) => entry.instanceId);
283
413 - const filteredModels = useMemo(() => {
284 + const filteredModels = (() => {
285 let result = flatModels;
286
287 if (searchQuery.trim()) {
288 const candidates =
418 - props.lockedProvider !== null ? result.filter((m) => matchesLockedProvider(m)) : result;
289 + lockedProvider !== null ? result.filter((m) => matchesLockedProvider(m)) : result;
290 return rankModelPickerSearch(candidates, searchQuery, (model) => ({
291 name: model.name,
292 ...(model.shortName ? { shortName: model.shortName } : {}),
@@ -426,7 +297,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
297 }));
298 }
299
429 - if (props.lockedProvider !== null) {
300 + if (lockedProvider !== null) {
301 result = result.filter((m) => matchesLockedProvider(m));
302 if (selectedInstanceId === "favorites") {
303 result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
@@ -444,17 +315,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
315 groupFavorites: selectedInstanceId !== "favorites",
316 instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [],
317 });
447 - }, [
448 - favoritesSet,
449 - flatModels,
450 - instanceOrder,
451 - matchesLockedProvider,
452 - props.lockedProvider,
453 - searchQuery,
454 - selectedInstanceId,
455 - ]);
318 + })();
319
457 - const legacySection = useMemo(() => {
320 + const legacySection = (() => {
321 if (isSearching || selectedInstanceId === "favorites") {
322 return null;
323 }
@@ -469,9 +332,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
332 legacyModels,
333 isExpanded: expandedLegacyInstances.has(selectedInstanceId),
334 };
472 - }, [expandedLegacyInstances, filteredModels, isSearching, selectedInstanceId]);
335 + })();
336
474 - const visibleModels = useMemo(() => {
337 + const visibleModels = (() => {
338 if (!legacySection) {
339 return filteredModels;
340 }
@@ -479,12 +342,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
342 ...legacySection.currentModels,
343 ...(legacySection.isExpanded ? legacySection.legacyModels : []),
344 ];
482 - }, [filteredModels, legacySection]);
345 + })();
346
347 const selectedEntry =
348 selectedInstanceId === "favorites" ? undefined : entryByInstanceId.get(selectedInstanceId);
349 const providerSetupEntries =
487 - !isSearching && props.onOpenProviderSetup
350 + !isSearching && hasProviderSetup
351 ? instanceEntries.filter(
352 (entry) =>
353 matchesLockedProvider(entry) &&
@@ -509,50 +372,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
372 return notice ? [{ instanceId: entry.instanceId, notice }] : [];
373 });
374
512 - const toggleLegacySection = useCallback((instanceId: ProviderInstanceId) => {
513 - setExpandedLegacyInstances((expanded) => {
514 - const next = new Set(expanded);
515 - if (next.has(instanceId)) {
516 - next.delete(instanceId);
517 - } else {
518 - next.add(instanceId);
519 - }
520 - return next;
521 - });
522 - }, []);
523 -
524 - const handleModelSelect = useCallback(
525 - (modelSlug: string, instanceId: ProviderInstanceId, additive = false) => {
526 - if (getModelDisabledReason?.(instanceId, modelSlug)) {
527 - return;
528 - }
529 - const options = modelOptionsByInstance.get(instanceId);
530 - if (!options) {
531 - return;
532 - }
533 - const entry = entryByInstanceId.get(instanceId);
534 - if (!entry) {
535 - return;
536 - }
537 - const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);
538 - if (resolvedModel) {
539 - if (additive && onToggleModel) {
540 - onToggleModel(instanceId, resolvedModel);
541 - } else {
542 - onInstanceModelChange(instanceId, resolvedModel);
543 - }
544 - }
545 - },
546 - [
547 - entryByInstanceId,
548 - getModelDisabledReason,
549 - modelOptionsByInstance,
550 - onInstanceModelChange,
551 - onToggleModel,
552 - ],
553 - );
554 -
555 - const modelJumpCommandByKey = useMemo(() => {
375 + const modelJumpCommandByKey = (() => {
376 const mapping = new Map<
377 string,
378 NonNullable<ReturnType<typeof modelPickerJumpCommandForIndex>>
@@ -570,23 +390,17 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
390 selectableModelIndex += 1;
391 }
392 return mapping;
573 - }, [getModelDisabledReason, visibleModels]);
574 - const modelJumpModelKeys = useMemo(
575 - () => [...modelJumpCommandByKey.keys()],
576 - [modelJumpCommandByKey],
577 - );
578 - const allItemKeys = useMemo(
579 - (): string[] => [
580 - ...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
581 - ...new Set(
582 - flatModels
583 - .filter((model) => model.isLegacy)
584 - .map((model) => modelPickerLegacySectionKey(model.instanceId)),
585 - ),
586 - ],
587 - [flatModels],
588 - );
589 - const filteredItemKeys = useMemo((): string[] => {
393 + })();
394 + const modelJumpModelKeys = [...modelJumpCommandByKey.keys()];
395 + const allItemKeys = ((): string[] => [
396 + ...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
397 + ...new Set(
398 + flatModels
399 + .filter((model) => model.isLegacy)
400 + .map((model) => modelPickerLegacySectionKey(model.instanceId)),
401 + ),
402 + ])();
403 + const filteredItemKeys = ((): string[] => {
404 const modelKeys = visibleModels.map((model) =>
405 modelPickerModelKey(model.instanceId, model.slug),
406 );
@@ -595,16 +409,238 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
409 }
410 modelKeys.splice(legacySection.currentModels.length, 0, legacySection.key);
411 return modelKeys;
598 - }, [legacySection, visibleModels]);
599 - const filteredModelByKey = useMemo(
600 - (): ReadonlyMap<string, ModelPickerItem> =>
601 - new Map(
602 - visibleModels.map(
603 - (model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const,
604 - ),
412 + })();
413 + const filteredModelByKey = ((): ReadonlyMap<string, ModelPickerItem> =>
414 + new Map(
415 + visibleModels.map(
416 + (model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const,
417 ),
606 - [visibleModels],
418 + ))();
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]);
572 +
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,
586 + 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 );
@@ -615,7 +651,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
651 );
652 const modelListHeight =
653 filteredItemKeys.length === 0 ? 0 : `calc(${modelListContentSize}px + var(--spacing) * 5)`;
618 - const updateModelListScrollFades = useCallback(() => {
654 + const updateModelListScrollFades = () => {
655 const scrollElement = modelListRef.current?.getScrollableNode();
656 if (!(scrollElement instanceof HTMLElement)) {
657 return;
@@ -623,17 +659,13 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
659 const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
660 setShowTopScrollFade(scrollElement.scrollTop > 1);
661 setShowBottomScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
626 - }, []);
627 - const modelJumpShortcutContext = useMemo(
628 - () =>
629 - ({
630 - terminalFocus: false,
631 - terminalOpen: props.terminalOpen,
632 - modelPickerOpen: true,
633 - }) as const,
634 - [props.terminalOpen],
635 - );
636 - const modelJumpLabelByKey = useMemo((): ReadonlyMap<string, string> => {
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 }
@@ -649,84 +681,84 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
681 }
682 }
683 return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
652 - }, [keybindings, modelJumpCommandByKey, modelJumpShortcutContext]);
653 - const modelListExtraData = useMemo(
654 - () => ({ favoritesSet, modelJumpLabelByKey, activeModelKey, selectedModelKeySet }),
655 - [favoritesSet, modelJumpLabelByKey, activeModelKey, selectedModelKeySet],
656 - );
684 + })();
685 + const modelListExtraData = {
686 + favoritesSet,
687 + modelJumpLabelByKey,
688 + activeModelKey,
689 + selectedModelKeySet,
690 + };
691
658 - useEffect(() => {
659 - const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
660 - if (event.defaultPrevented || event.repeat || isCommandPaletteOpen()) {
661 - return;
662 - }
692 + const onWindowKeyDown = useEffectEvent((event: globalThis.KeyboardEvent) => {
693 + if (event.defaultPrevented || event.repeat || isCommandPaletteOpen()) {
694 + return;
695 + }
696
664 - const command = resolveShortcutCommand(event, keybindings, {
665 - platform: navigator.platform,
666 - context: modelJumpShortcutContext,
667 - });
668 - if (command === "modelPicker.previousProvider" || command === "modelPicker.nextProvider") {
669 - event.preventDefault();
670 - event.stopPropagation();
671 - const next = adjacentModelPickerProvider({
672 - entries: sidebarInstanceEntries,
673 - selectedInstanceId,
674 - direction: command === "modelPicker.nextProvider" ? 1 : -1,
675 - disabledInstanceIds: lockedDisabledInstanceIds,
676 - selectableUnavailableInstanceIds,
677 - });
678 - setSearchQuery("");
679 - handleSelectInstance(next);
680 - return;
681 - }
682 - const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");
683 - if (jumpIndex === null) {
684 - return;
685 - }
697 + const command = resolveShortcutCommand(event, keybindings, {
698 + platform: navigator.platform,
699 + context: modelJumpShortcutContext,
700 + });
701 + if (command === "modelPicker.previousProvider" || command === "modelPicker.nextProvider") {
702 event.preventDefault();
703 event.stopPropagation();
704 + const next = adjacentModelPickerProvider({
705 + entries: sidebarInstanceEntries,
706 + selectedInstanceId,
707 + direction: command === "modelPicker.nextProvider" ? 1 : -1,
708 + disabledInstanceIds: lockedDisabledInstanceIds,
709 + selectableUnavailableInstanceIds,
710 + });
711 + setSearchQuery("");
712 + handleSelectInstance(next);
713 + return;
714 + }
715 + const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");
716 + if (jumpIndex === null) {
717 + return;
718 + }
719 + event.preventDefault();
720 + event.stopPropagation();
721
689 - const targetModelKey = modelJumpModelKeys[jumpIndex];
690 - if (!targetModelKey) {
691 - return;
692 - }
693 - const model = parseModelPickerModelKey(targetModelKey);
694 - if (!model) {
695 - return;
696 - }
697 - handleModelSelect(model.slug, model.instanceId);
698 - };
699 -
700 - window.addEventListener("keydown", onWindowKeyDown, true);
701 -
722 + const targetModelKey = modelJumpModelKeys[jumpIndex];
723 + if (!targetModelKey) {
724 + return;
725 + }
726 + const model = parseModelPickerModelKey(targetModelKey);
727 + if (!model) {
728 + return;
729 + }
730 + handleModelSelect(model.slug, model.instanceId);
731 + });
732 + useEffect(() => {
733 + const listener = (event: globalThis.KeyboardEvent) => onWindowKeyDown(event);
734 + window.addEventListener("keydown", listener, true);
735 return () => {
703 - window.removeEventListener("keydown", onWindowKeyDown, true);
736 + window.removeEventListener("keydown", listener, true);
737 };
705 - }, [
706 - handleModelSelect,
707 - handleSelectInstance,
708 - keybindings,
709 - lockedDisabledInstanceIds,
710 - modelJumpModelKeys,
711 - modelJumpShortcutContext,
712 - selectableUnavailableInstanceIds,
713 - selectedInstanceId,
714 - sidebarInstanceEntries,
715 - ]);
738 + }, []);
739
717 - useLayoutEffect(() => {
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(() => {
722 - updateModelListScrollFades();
723 - nestedFrame = window.requestAnimationFrame(updateModelListScrollFades);
753 + measureScrollFades();
754 + nestedFrame = window.requestAnimationFrame(() => measureScrollFades());
755 });
756 return () => {
757 window.cancelAnimationFrame(frame);
758 window.cancelAnimationFrame(nestedFrame);
759 };
729 - }, [filteredItemKeys, updateModelListScrollFades]);
760 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new list re-measures its scroll fades once it has laid out.
761 + }, [filteredItemListKey]);
762
763 return (
764 <TooltipProvider delay={0}>