Open History to see the last commit
1import type { MenuAction } from "@react-native-menu/menu";
2import type {
3 ModelCapabilities,
4 ModelSelection,
5 RuntimeMode,
6 ServerConfig as T3ServerConfig,
7} from "@t3tools/contracts";
8import {
9 buildExplicitProviderOptionSelectionsFromDescriptors,
10 getProviderOptionDescriptors,
11} from "@t3tools/shared/model";
12
13export type ModelOption = {
14 readonly key: string;
15 readonly label: string;
16 readonly subtitle: string;
17 readonly providerKey: string;
18 readonly providerLabel: string;
19 readonly providerDriver: string;
20 readonly supportedRuntimeModes?: ReadonlyArray<RuntimeMode>;
21 readonly providerIconUrl?: string | undefined;
22 readonly isDefault: boolean;
23 readonly isLegacy: boolean;
24 readonly isUnavailable?: boolean;
25 readonly capabilities: ModelCapabilities | null;
26 readonly selection: ModelSelection;
27};
28
29export type ProviderGroup = {
30 readonly providerKey: string;
31 readonly providerLabel: string;
32 readonly models: ReadonlyArray<ModelOption>;
33};
34
35function providerDisplayLabel(provider: {
36 readonly displayName?: string | undefined;
37 readonly driver: string;
38 readonly instanceId: string;
39}): string {
40 if (provider.displayName) return provider.displayName;
41 if (provider.driver === "codex") return "Codex";
42 if (provider.driver === "claudeAgent") return "Claude";
43 if (provider.driver === "pi") return "Pi";
44 return provider.instanceId;
45}
46
47function normalizeSelectionOptions(
48 selection: ModelSelection,
49 capabilities: ModelCapabilities | null,
50): ModelSelection {
51 if (!capabilities) {
52 return selection;
53 }
54 if (!selection.options?.length) {
55 return { instanceId: selection.instanceId, model: selection.model };
56 }
57 const options = buildExplicitProviderOptionSelectionsFromDescriptors(
58 getProviderOptionDescriptors({
59 caps: capabilities,
60 selections: selection.options,
61 }),
62 selection.options,
63 );
64 return options
65 ? { ...selection, options }
66 : {
67 instanceId: selection.instanceId,
68 model: selection.model,
69 };
70}
71
72/** Whether a saved dynamic catalog selection needs setup or a different model. */
73export function isModelSelectionUnavailable(
74 config: T3ServerConfig | null | undefined,
75 selection: ModelSelection | null | undefined,
76): boolean {
77 if (!config || !selection) {
78 return false;
79 }
80 const provider = config.providers.find(
81 (candidate) => candidate.instanceId === selection.instanceId,
82 );
83 const driver =
84 provider?.driver ?? config.settings?.providerInstances[selection.instanceId]?.driver;
85 return (
86 (driver === "antigravity" || driver === "muse") &&
87 (!provider ||
88 !provider.enabled ||
89 !provider.installed ||
90 provider.auth.status === "unauthenticated" ||
91 provider.availability === "unavailable" ||
92 ((driver !== "muse" || provider.status === "ready") &&
93 !provider.models.some((model) => model.slug === selection.model)))
94 );
95}
96
97/**
98 * Keep Antigravity and Muse selections when setup or catalog changes make them
99 * unavailable. Other providers fall through to the server default when they
100 * are disabled, missing, or signed out. Without config, keep stored selections.
101 */
102export function resolveSelectableModelSelection(
103 config: T3ServerConfig | null | undefined,
104 selection: ModelSelection | null,
105): ModelSelection | null {
106 if (!selection || !config) {
107 return selection;
108 }
109 const provider = config.providers.find(
110 (candidate) => candidate.instanceId === selection.instanceId,
111 );
112 const driver =
113 provider?.driver ?? config.settings?.providerInstances[selection.instanceId]?.driver;
114 if (driver === "antigravity" || driver === "muse") {
115 return selection;
116 }
117 return provider &&
118 provider.enabled &&
119 provider.installed &&
120 provider.auth.status !== "unauthenticated"
121 ? selection
122 : null;
123}
124
125/**
126 * Reject legacy models for implicit defaults, except Antigravity selections,
127 * which must not silently change after a catalog update. Explicit picks in
128 * the settings sheet are unaffected.
129 */
130export function resolveDefaultableModelSelection(
131 config: T3ServerConfig | null | undefined,
132 selection: ModelSelection | null,
133): ModelSelection | null {
134 const usable = resolveSelectableModelSelection(config, selection);
135 if (!usable || !config) {
136 return usable;
137 }
138 const provider = config.providers.find((candidate) => candidate.instanceId === usable.instanceId);
139 const model = provider?.models.find((candidate) => candidate.slug === usable.model);
140 return provider?.driver !== "antigravity" && model?.isLegacy === true ? null : usable;
141}
142
143export function resolveNewTaskModelSelection(input: {
144 readonly draftSelection: ModelSelection | null;
145 readonly projectDefaultSelection: ModelSelection | null;
146 readonly stickySelection: ModelSelection | null;
147 readonly modelOptions: ReadonlyArray<ModelOption>;
148}): ModelSelection | null {
149 return (
150 input.draftSelection ??
151 input.projectDefaultSelection ??
152 input.stickySelection ??
153 input.modelOptions.find((option) => option.isDefault && !option.isUnavailable)?.selection ??
154 input.modelOptions.find((option) => !option.isUnavailable)?.selection ??
155 null
156 );
157}
158
159export function buildModelOptions(
160 config: T3ServerConfig | null | undefined,
161 fallbackModelSelection: ModelSelection | null,
162 providerInstanceId?: ModelSelection["instanceId"],
163): ReadonlyArray<ModelOption> {
164 const options = new Map<string, ModelOption>();
165
166 for (const provider of config?.providers ?? []) {
167 if (
168 (providerInstanceId !== undefined && provider.instanceId !== providerInstanceId) ||
169 !provider.enabled ||
170 !provider.installed ||
171 provider.auth.status === "unauthenticated" ||
172 ((provider.driver === "antigravity" || provider.driver === "muse") &&
173 provider.availability === "unavailable")
174 ) {
175 continue;
176 }
177
178 const providerLabel = providerDisplayLabel(provider);
179 for (const model of provider.models) {
180 const key = `${provider.instanceId}:${model.slug}`;
181 options.set(key, {
182 key,
183 label: model.name,
184 subtitle: model.subProvider ?? "",
185 providerKey: provider.instanceId,
186 providerLabel,
187 providerDriver: provider.driver,
188 ...(provider.supportedRuntimeModes === undefined
189 ? {}
190 : { supportedRuntimeModes: provider.supportedRuntimeModes }),
191 ...(provider.iconUrl ? { providerIconUrl: provider.iconUrl } : {}),
192 isDefault: model.isDefault === true,
193 isLegacy: model.isLegacy === true,
194 capabilities: model.capabilities,
195 selection: normalizeSelectionOptions(
196 {
197 instanceId: provider.instanceId,
198 model: model.slug,
199 },
200 model.capabilities,
201 ),
202 });
203 }
204 }
205
206 if (
207 fallbackModelSelection &&
208 (providerInstanceId === undefined || fallbackModelSelection.instanceId === providerInstanceId)
209 ) {
210 const key = `${fallbackModelSelection.instanceId}:${fallbackModelSelection.model}`;
211 const existing = options.get(key);
212 if (existing) {
213 options.set(key, {
214 ...existing,
215 selection:
216 existing.providerDriver === "antigravity"
217 ? fallbackModelSelection
218 : normalizeSelectionOptions(fallbackModelSelection, existing.capabilities),
219 });
220 } else {
221 const provider = config?.providers.find(
222 (candidate) => candidate.instanceId === fallbackModelSelection.instanceId,
223 );
224 const instanceConfig = config?.settings?.providerInstances[fallbackModelSelection.instanceId];
225 const model = provider?.models.find(
226 (candidate) => candidate.slug === fallbackModelSelection.model,
227 );
228 const providerDriver =
229 provider?.driver ?? instanceConfig?.driver ?? fallbackModelSelection.instanceId;
230 const providerLabel = providerDisplayLabel({
231 driver: providerDriver,
232 displayName: provider?.displayName ?? instanceConfig?.displayName,
233 instanceId: fallbackModelSelection.instanceId,
234 });
235 options.set(key, {
236 key,
237 label: model?.name ?? fallbackModelSelection.model,
238 subtitle: model?.subProvider ?? "",
239 providerKey: fallbackModelSelection.instanceId,
240 providerLabel,
241 providerDriver,
242 isDefault: false,
243 isLegacy: model?.isLegacy === true,
244 ...(isModelSelectionUnavailable(config, fallbackModelSelection)
245 ? { isUnavailable: true }
246 : {}),
247 capabilities: model?.capabilities ?? null,
248 selection: fallbackModelSelection,
249 });
250 }
251 }
252
253 return [...options.values()];
254}
255
256export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyArray<ProviderGroup> {
257 const groups = new Map<string, { providerLabel: string; models: ModelOption[] }>();
258 for (const option of options) {
259 const existing = groups.get(option.providerKey);
260 if (existing) {
261 existing.models.push(option);
262 } else {
263 groups.set(option.providerKey, {
264 providerLabel: option.providerLabel,
265 models: [option],
266 });
267 }
268 }
269
270 return [...groups.entries()].map(([providerKey, group]) => ({
271 providerKey,
272 providerLabel: group.providerLabel,
273 models: group.models,
274 }));
275}
276
277function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
278 return {
279 id: `model:${option.key}`,
280 title: option.label,
281 state:
282 option.selection.instanceId === selectedModel?.instanceId &&
283 option.selection.model === selectedModel.model
284 ? "on"
285 : undefined,
286 };
287}
288
289export function buildModelMenuActions(
290 groups: ReadonlyArray<ProviderGroup>,
291 selectedModel: ModelSelection | null,
292): MenuAction[] {
293 return groups.flatMap((group) => {
294 const currentModels = group.models.filter((model) => !model.isLegacy);
295 const legacyModels = group.models.filter((model) => model.isLegacy);
296 const selected = group.models.find(
297 (model) =>
298 model.selection.instanceId === selectedModel?.instanceId &&
299 model.selection.model === selectedModel.model,
300 );
301
302 return [
303 ...(currentModels.length > 0
304 ? [
305 {
306 id: `provider:${group.providerKey}`,
307 title: group.providerLabel,
308 subtitle: selected && !selected.isLegacy ? selected.label : undefined,
309 subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
310 },
311 ]
312 : []),
313 ...(legacyModels.length > 0
314 ? [
315 {
316 id: `legacy-models:${group.providerKey}`,
317 title: `${group.providerLabel} legacy models`,
318 subtitle: selected?.isLegacy ? selected.label : undefined,
319 subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
320 },
321 ]
322 : []),
323 ];
324 });
325}