Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 86 additions & 47 deletions apps/web/src/components/chat/ModelPickerContent.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { useLegendListRef } from "~/hooks/useLegendListRef";
import {
ANTIGRAVITY_DEFAULT_MODEL,
type ProviderInstanceId,
ProviderInstanceId,
type EnvironmentId,
type ProviderDriverKind,
type ResolvedKeybindingsConfig,
MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { resolveSelectableModel } from "@t3tools/shared/model";
import { useAtomValue } from "@effect/atom-react";
import { formatProviderUpdateRequiredNotice } from "@t3tools/client-runtime/providerUpdateRequiredModels";
Expand Down Expand Up @@ -54,6 +55,7 @@ import {
useEnvironmentModelPreferences,
useToggleEnvironmentModelFavorite,
} from "~/hooks/useSettings";
import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
import { announce } from "~/lib/announce";
import { cn } from "~/lib/utils";
import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area";
Expand All @@ -62,8 +64,10 @@ import { InlineButton } from "../ui/button";
import {
isProviderInstancePickerReady,
isProviderInstancePickerVisible,
type ModelPickerTab,
shouldShowInstanceBadge,
type ProviderInstanceEntry,
resolveModelPickerTab,
} from "../../providerInstances";
import { providerModelKey, sortProviderModelItems } from "../../modelOrdering";
import { hasRuntimeModelCatalog } from "../../providerModels";
Expand Down Expand Up @@ -164,6 +168,26 @@ function adjacentModelPickerProvider(input: {
]!;
}

const LAST_PICKED_TAB_STORAGE_KEY = "t3code:model-picker-last-tab:v1";
const ModelPickerTabSchema = Schema.Union([Schema.Literal("favorites"), ProviderInstanceId]);

function readLastPickedTab(): ModelPickerTab | null {
try {
return getLocalStorageItem(LAST_PICKED_TAB_STORAGE_KEY, ModelPickerTabSchema);
} catch (error) {
console.error("Could not read the last model picker tab.", error);
return null;
}
}

function writeLastPickedTab(tab: ModelPickerTab): void {
try {
setLocalStorageItem(LAST_PICKED_TAB_STORAGE_KEY, tab, ModelPickerTabSchema);
} catch (error) {
console.error("Could not persist the last model picker tab.", error);
}
}

const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
const MODEL_LIST_ESTIMATED_ITEM_SIZE = 32;
// Rendered heights in `--spacing` units. Chrome is the search box and list padding, plus a 1px border.
Expand Down Expand Up @@ -411,34 +435,54 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
activeEntry,
modelOptionsByInstance.get(props.activeInstanceId) ?? [],
);
const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(
() => {
if (
props.lockedProvider !== null ||
activeInstanceHasSelectableUnavailableModel ||
activeInstanceNeedsSetup
) {
return props.activeInstanceId;
const selectableUnavailableInstanceIds = (() => {
const instanceIds = new Set<ProviderInstanceId>();
if (activeInstanceHasSelectableUnavailableModel) {
instanceIds.add(props.activeInstanceId);
}
if (onOpenProviderSetup !== undefined) {
for (const entry of instanceEntries) {
if (
shouldOfferModelPickerSetup(entry, modelOptionsByInstance.get(entry.instanceId) ?? [])
) {
instanceIds.add(entry.instanceId);
}
}
const hasPickableFavorite = favorites.some((favorite) => {
const entry = instanceEntries.find((entry) => entry.instanceId === favorite.provider);
return (
entry !== undefined &&
(modelOptionsByInstance.get(favorite.provider) ?? []).some(
(option) =>
option.slug === favorite.model &&
shouldIncludeModelPickerOption({
entry,
option,
activeInstanceId: props.activeInstanceId,
activeModel: activeModelSlug,
}),
)
);
});
return hasPickableFavorite ? "favorites" : props.activeInstanceId;
},
);
}
return instanceIds.size > 0 ? instanceIds : undefined;
})();
const hasPickableFavorite = favorites.some((favorite) => {
const entry = instanceEntries.find((entry) => entry.instanceId === favorite.provider);
return (
entry !== undefined &&
(modelOptionsByInstance.get(favorite.provider) ?? []).some(
(option) =>
option.slug === favorite.model &&
shouldIncludeModelPickerOption({
entry,
option,
activeInstanceId: props.activeInstanceId,
activeModel: activeModelSlug,
}),
)
);
});

const [lastPickedTab] = useState(readLastPickedTab);
const [chosenTab, setChosenTab] = useState<ModelPickerTab | null>(null);
const keepActiveInstance =
props.lockedProvider !== null ||
activeInstanceHasSelectableUnavailableModel ||
activeInstanceNeedsSetup;
const selectedInstanceId = resolveModelPickerTab({
activeInstanceId: props.activeInstanceId,
chosenTab,
lastPickedTab,
hasFavorites: hasPickableFavorite,
keepActiveInstance,
instanceEntries,
selectableUnavailableInstanceIds,
});
const { scanning: workspaceModelsScanning } = useProviderWorkspaceSnapshotRefresh({
environmentId: props.environmentId,
gitCwd: props.workspaceCwd ?? null,
Expand All @@ -457,14 +501,21 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
const serverKeybindings = useAtomValue(primaryServerKeybindingsAtom);
const keybindings = providedKeybindings ?? serverKeybindings;
const [searchHeight, setSearchHeight] = useState(0);
const toggleFavorite = useToggleEnvironmentModelFavorite(props.environmentId);
const toggleEnvironmentModelFavorite = useToggleEnvironmentModelFavorite(props.environmentId);
// Pins the open tab so the first or last favorite does not move the default tab under the cursor.
const toggleFavorite = (instanceId: ProviderInstanceId, slug: string) => {
if (chosenTab === null && !keepActiveInstance) {
setChosenTab(selectedInstanceId);
}
return toggleEnvironmentModelFavorite(instanceId, slug);
};

const focusSearchInput = () => {
searchInputRef.current?.focus({ preventScroll: true });
};

const handleSelectInstance = (instanceId: ProviderInstanceId | "favorites") => {
setSelectedInstanceId(instanceId);
setChosenTab(instanceId);
// Focusing the search on touch raises the on-screen keyboard on every provider tap.
if (window.matchMedia("(pointer: coarse)").matches) return;
window.requestAnimationFrame(() => {
Expand Down Expand Up @@ -502,6 +553,11 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
}
const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);
if (!resolvedModel) return null;
// Search results span every tab, and a forced locked or setup tab is not a habit, so
// neither replaces the remembered tab.
if (!isSearching && (chosenTab !== null || !keepActiveInstance)) {
writeLastPickedTab(selectedInstanceId);
}
if (additive && onToggleModel) {
onToggleModel(instanceId, resolvedModel);
} else {
Expand Down Expand Up @@ -529,23 +585,6 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
return entry.continuationGroupKey === lockedContinuationGroupKey;
};

const selectableUnavailableInstanceIds = (() => {
const instanceIds = new Set<ProviderInstanceId>();
if (activeInstanceHasSelectableUnavailableModel) {
instanceIds.add(props.activeInstanceId);
}
if (canOpenProviderSetup) {
for (const entry of instanceEntries) {
if (
shouldOfferModelPickerSetup(entry, modelOptionsByInstance.get(entry.instanceId) ?? [])
) {
instanceIds.add(entry.instanceId);
}
}
}
return instanceIds.size > 0 ? instanceIds : undefined;
})();

const flatModels = (() => {
const out: ModelPickerItem[] = [];
const seenKeys = new Set<string>();
Expand Down
77 changes: 77 additions & 0 deletions apps/web/src/providerInstances.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
getDefaultProviderInstanceModel,
isProviderInstancePickerReady,
resolveDefaultProviderModelSelection,
resolveModelPickerTab,
resolveSelectableProviderInstance,
shouldShowInstanceBadge,
} from "./providerInstances";
Expand Down Expand Up @@ -591,3 +592,79 @@ describe("provider icon metadata", () => {
expect(restoredEntry?.enabled).toBe(true);
});
});

describe("resolveModelPickerTab", () => {
const activeInstanceId = ProviderInstanceId.make("claudeAgent_personal");
const otherInstanceId = ProviderInstanceId.make("codex_work");
const opening = {
activeInstanceId,
chosenTab: null,
lastPickedTab: null,
hasFavorites: true,
keepActiveInstance: false,
instanceEntries: deriveProviderInstanceEntries([
provider({ provider: ProviderDriverKind.make("claudeAgent"), instanceId: activeInstanceId }),
provider({ provider: ProviderDriverKind.make("codex"), instanceId: otherInstanceId }),
]),
selectableUnavailableInstanceIds: undefined,
} as const;

it("reopens on the tab the last model was picked from", () => {
expect(resolveModelPickerTab({ ...opening, lastPickedTab: "favorites" })).toBe("favorites");
expect(resolveModelPickerTab({ ...opening, lastPickedTab: activeInstanceId })).toBe(
activeInstanceId,
);
// An additive pick leaves another account active, so the tab is remembered by account.
expect(resolveModelPickerTab({ ...opening, lastPickedTab: otherInstanceId })).toBe(
otherInstanceId,
);
// Locked and setup-needed accounts, and a hidden remembered account, keep today's tab.
expect(
resolveModelPickerTab({ ...opening, lastPickedTab: "favorites", keepActiveInstance: true }),
).toBe(activeInstanceId);
expect(
resolveModelPickerTab({
...opening,
lastPickedTab: otherInstanceId,
instanceEntries: opening.instanceEntries.filter(
(entry) => entry.instanceId === activeInstanceId,
),
}),
).toBe("favorites");
});

it("does not reopen on a remembered account that is enabled but unavailable", () => {
const remembered = {
...opening,
lastPickedTab: otherInstanceId,
instanceEntries: deriveProviderInstanceEntries([
provider({
provider: ProviderDriverKind.make("claudeAgent"),
instanceId: activeInstanceId,
}),
provider({
provider: ProviderDriverKind.make("codex"),
instanceId: otherInstanceId,
status: "error",
}),
]),
} as const;
expect(resolveModelPickerTab(remembered)).toBe("favorites");
// Still reachable when the sidebar offers its setup action or a selectable unavailable model.
expect(
resolveModelPickerTab({
...remembered,
selectableUnavailableInstanceIds: new Set([otherInstanceId]),
}),
).toBe(otherInstanceId);
});

it("lands on favorites once they load unless a tab was chosen", () => {
const beforeLoad = { ...opening, lastPickedTab: "favorites", hasFavorites: false } as const;
expect(resolveModelPickerTab(beforeLoad)).toBe(activeInstanceId);
expect(resolveModelPickerTab({ ...beforeLoad, hasFavorites: true })).toBe("favorites");
expect(
resolveModelPickerTab({ ...beforeLoad, hasFavorites: true, chosenTab: activeInstanceId }),
).toBe(activeInstanceId);
});
});
35 changes: 35 additions & 0 deletions apps/web/src/providerInstances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,41 @@ export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): b
return entry.enabled;
}

export type ModelPickerTab = ProviderInstanceId | "favorites";

// Favorites can load after the picker opens, so the default follows them until the user picks a tab.
export function resolveModelPickerTab(input: {
activeInstanceId: ProviderInstanceId;
chosenTab: ModelPickerTab | null;
lastPickedTab: ModelPickerTab | null;
hasFavorites: boolean;
keepActiveInstance: boolean;
instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
selectableUnavailableInstanceIds: ReadonlySet<ProviderInstanceId> | undefined;
}): ModelPickerTab {
if (input.chosenTab !== null) {
return input.chosenTab;
}
if (input.keepActiveInstance) {
return input.activeInstanceId;
}
const lastPickedTab = input.lastPickedTab;
// Only a tab the sidebar leaves enabled, so the picker never opens on an empty, unpickable list.
const lastPickedEntry =
lastPickedTab === null || lastPickedTab === "favorites"
? undefined
: input.instanceEntries.find((entry) => entry.instanceId === lastPickedTab);
if (
lastPickedEntry !== undefined &&
isProviderInstancePickerVisible(lastPickedEntry) &&
(isProviderInstancePickerReady(lastPickedEntry) ||
input.selectableUnavailableInstanceIds?.has(lastPickedEntry.instanceId))
) {
return lastPickedEntry.instanceId;
}
return input.hasFavorites ? "favorites" : input.activeInstanceId;
}

export function deriveProviderInstanceEntries(
providers: ReadonlyArray<ServerProvider>,
): ReadonlyArray<ProviderInstanceEntry> {
Expand Down
Loading