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 isHidden?: boolean;
26 readonly canHide?: boolean;
27 readonly capabilities: ModelCapabilities | null;
28 readonly selection: ModelSelection;
29 readonly providerUpdateRequired?: ProviderUpdateRequired;
30};
31
32type ProviderUpdateRequired = Pick<
33 T3ServerConfig["providers"][number],
34 "driver" | "updateRequiredModels"
35>;
36
37export type ProviderGroup = {
38 readonly providerKey: string;
39 readonly providerLabel: string;
40 readonly models: ReadonlyArray<ModelOption>;
41 /** The provider fields that name announced models its CLI is too old to run. */
42 readonly updateRequired?: ProviderUpdateRequired;
43};
44
45function providerDisplayLabel(provider: {
46 readonly displayName?: string | undefined;
47 readonly driver: string;
48 readonly instanceId: string;
49}): string {
50 if (provider.displayName) return provider.displayName;
51 if (provider.driver === "codex") return "Codex";
52 if (provider.driver === "claudeAgent") return "Claude";
53 if (provider.driver === "pi") return "Pi";
54 return provider.instanceId;
55}
56
57function normalizeSelectionOptions(
58 selection: ModelSelection,
59 capabilities: ModelCapabilities | null,
60): ModelSelection {
61 if (!capabilities) {
62 return selection;
63 }
64 if (!selection.options?.length) {
65 return { instanceId: selection.instanceId, model: selection.model };
66 }
67 const options = buildExplicitProviderOptionSelectionsFromDescriptors(
68 getProviderOptionDescriptors({
69 caps: capabilities,
70 selections: selection.options,
71 }),
72 selection.options,
73 );
74 return options
75 ? { ...selection, options }
76 : {
77 instanceId: selection.instanceId,
78 model: selection.model,
79 };
80}
81
82/** Whether a known Antigravity selection needs setup or a different model. */
83export function isModelSelectionUnavailable(
84 config: T3ServerConfig | null | undefined,
85 selection: ModelSelection | null | undefined,
86): boolean {
87 if (!config || !selection) {
88 return false;
89 }
90 const provider = config.providers.find(
91 (candidate) => candidate.instanceId === selection.instanceId,
92 );
93 const driver =
94 provider?.driver ?? config.settings?.providerInstances[selection.instanceId]?.driver;
95 return (
96 driver === "antigravity" &&
97 (!provider ||
98 !provider.enabled ||
99 !provider.installed ||
100 provider.auth.status === "unauthenticated" ||
101 provider.availability === "unavailable" ||
102 !provider.models.some((model) => model.slug === selection.model))
103 );
104}
105
106/**
107 * Keep Antigravity selections when setup or catalog changes make them
108 * unavailable. Other providers fall through to the server default when they
109 * are disabled, missing, or signed out. Without config, keep stored selections.
110 */
111export function resolveSelectableModelSelection(
112 config: T3ServerConfig | null | undefined,
113 selection: ModelSelection | null,
114): ModelSelection | null {
115 if (!selection || !config) {
116 return selection;
117 }
118 const provider = config.providers.find(
119 (candidate) => candidate.instanceId === selection.instanceId,
120 );
121 const driver =
122 provider?.driver ?? config.settings?.providerInstances[selection.instanceId]?.driver;
123 if (driver === "antigravity") {
124 return selection;
125 }
126 return provider &&
127 provider.enabled &&
128 provider.installed &&
129 provider.auth.status !== "unauthenticated"
130 ? selection
131 : null;
132}
133
134/**
135 * Reject legacy models for implicit defaults, except Antigravity selections,
136 * which must not silently change after a catalog update. Explicit picks in
137 * the settings sheet are unaffected.
138 */
139export function resolveDefaultableModelSelection(
140 config: T3ServerConfig | null | undefined,
141 selection: ModelSelection | null,
142): ModelSelection | null {
143 const usable = resolveSelectableModelSelection(config, selection);
144 if (!usable || !config) {
145 return usable;
146 }
147 const provider = config.providers.find((candidate) => candidate.instanceId === usable.instanceId);
148 const model = provider?.models.find((candidate) => candidate.slug === usable.model);
149 return provider?.driver !== "antigravity" && model?.isLegacy === true ? null : usable;
150}
151
152export function resolveNewTaskModelSelection(input: {
153 readonly draftSelection: ModelSelection | null;
154 readonly projectDefaultSelection: ModelSelection | null;
155 readonly stickySelection: ModelSelection | null;
156 readonly modelOptions: ReadonlyArray<ModelOption>;
157}): ModelSelection | null {
158 return (
159 input.draftSelection ??
160 input.projectDefaultSelection ??
161 input.stickySelection ??
162 input.modelOptions.find((option) => option.isDefault && !option.isUnavailable)?.selection ??
163 input.modelOptions.find((option) => !option.isUnavailable)?.selection ??
164 null
165 );
166}
167
168export function buildModelOptions(
169 config: T3ServerConfig | null | undefined,
170 fallbackModelSelection: ModelSelection | null,
171 providerInstanceId?: ModelSelection["instanceId"],
172 includeHidden = false,
173): ReadonlyArray<ModelOption> {
174 const options = new Map<string, ModelOption>();
175
176 for (const provider of config?.providers ?? []) {
177 if (
178 (providerInstanceId !== undefined && provider.instanceId !== providerInstanceId) ||
179 !provider.enabled ||
180 !provider.installed ||
181 provider.auth.status === "unauthenticated" ||
182 (provider.driver === "antigravity" && provider.availability === "unavailable")
183 ) {
184 continue;
185 }
186
187 const providerLabel = providerDisplayLabel(provider);
188 const updateRequired = provider.updateRequiredModels?.length
189 ? { driver: provider.driver, updateRequiredModels: provider.updateRequiredModels }
190 : undefined;
191 const preferences = config?.settings?.providerModelPreferences?.[provider.instanceId];
192 const hiddenModels = new Set(preferences?.hiddenModels ?? []);
193 const order = new Map((preferences?.modelOrder ?? []).map((slug, index) => [slug, index]));
194 const models = provider.models.filter(
195 (model) => includeHidden || model.isCustom || !hiddenModels.has(model.slug),
196 );
197 if (order.size > 0)
198 models.sort((a, b) => (order.get(a.slug) ?? Infinity) - (order.get(b.slug) ?? Infinity));
199 for (const model of models) {
200 const key = `${provider.instanceId}:${model.slug}`;
201 options.set(key, {
202 key,
203 label: model.name,
204 subtitle: model.subProvider ?? "",
205 providerKey: provider.instanceId,
206 providerLabel,
207 providerDriver: provider.driver,
208 ...(provider.supportedRuntimeModes === undefined
209 ? {}
210 : { supportedRuntimeModes: provider.supportedRuntimeModes }),
211 ...(provider.iconUrl ? { providerIconUrl: provider.iconUrl } : {}),
212 isHidden: !model.isCustom && hiddenModels.has(model.slug),
213 canHide: !model.isCustom,
214 isDefault: model.isDefault === true,
215 isLegacy: model.isLegacy === true,
216 ...(updateRequired ? { providerUpdateRequired: updateRequired } : {}),
217 capabilities: model.capabilities,
218 selection: normalizeSelectionOptions(
219 {
220 instanceId: provider.instanceId,
221 model: model.slug,
222 },
223 model.capabilities,
224 ),
225 });
226 }
227 }
228
229 if (
230 fallbackModelSelection &&
231 (providerInstanceId === undefined ||
232 fallbackModelSelection.instanceId === providerInstanceId) &&
233 (!config?.settings?.providerModelPreferences?.[
234 fallbackModelSelection.instanceId
235 ]?.hiddenModels.includes(fallbackModelSelection.model) ||
236 config?.providers
237 .find((provider) => provider.instanceId === fallbackModelSelection.instanceId)
238 ?.models.find((model) => model.slug === fallbackModelSelection.model)?.isCustom)
239 ) {
240 const key = `${fallbackModelSelection.instanceId}:${fallbackModelSelection.model}`;
241 const existing = options.get(key);
242 if (existing) {
243 options.set(key, {
244 ...existing,
245 selection:
246 existing.providerDriver === "antigravity"
247 ? fallbackModelSelection
248 : normalizeSelectionOptions(fallbackModelSelection, existing.capabilities),
249 });
250 } else {
251 const provider = config?.providers.find(
252 (candidate) => candidate.instanceId === fallbackModelSelection.instanceId,
253 );
254 const instanceConfig = config?.settings?.providerInstances[fallbackModelSelection.instanceId];
255 const model = provider?.models.find(
256 (candidate) => candidate.slug === fallbackModelSelection.model,
257 );
258 const providerDriver =
259 provider?.driver ?? instanceConfig?.driver ?? fallbackModelSelection.instanceId;
260 const providerLabel = providerDisplayLabel({
261 driver: providerDriver,
262 displayName: provider?.displayName ?? instanceConfig?.displayName,
263 instanceId: fallbackModelSelection.instanceId,
264 });
265 options.set(key, {
266 key,
267 label: model?.name ?? fallbackModelSelection.model,
268 subtitle: model?.subProvider ?? "",
269 providerKey: fallbackModelSelection.instanceId,
270 providerLabel,
271 providerDriver,
272 isDefault: false,
273 isLegacy: model?.isLegacy === true,
274 ...(isModelSelectionUnavailable(config, fallbackModelSelection) ||
275 provider?.updateRequiredModels?.some((gated) => gated.slug === fallbackModelSelection.model)
276 ? { isUnavailable: true }
277 : {}),
278 capabilities: model?.capabilities ?? null,
279 selection: fallbackModelSelection,
280 });
281 }
282 }
283
284 return [...options.values()];
285}
286
287export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyArray<ProviderGroup> {
288 const groups = new Map<
289 string,
290 {
291 providerLabel: string;
292 models: ModelOption[];
293 updateRequired: ProviderUpdateRequired | undefined;
294 }
295 >();
296 for (const option of options) {
297 const existing = groups.get(option.providerKey);
298 if (existing) {
299 existing.models.push(option);
300 existing.updateRequired ??= option.providerUpdateRequired;
301 } else {
302 groups.set(option.providerKey, {
303 providerLabel: option.providerLabel,
304 models: [option],
305 updateRequired: option.providerUpdateRequired,
306 });
307 }
308 }
309
310 return [...groups.entries()].map(([providerKey, group]) => ({
311 providerKey,
312 providerLabel: group.providerLabel,
313 models: group.models,
314 ...(group.updateRequired ? { updateRequired: group.updateRequired } : {}),
315 }));
316}
317
318function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
319 return {
320 id: `model:${option.key}`,
321 title: option.label,
322 state:
323 option.selection.instanceId === selectedModel?.instanceId &&
324 option.selection.model === selectedModel.model
325 ? "on"
326 : undefined,
327 };
328}
329
330export function buildModelMenuActions(
331 groups: ReadonlyArray<ProviderGroup>,
332 selectedModel: ModelSelection | null,
333): MenuAction[] {
334 return groups.flatMap((group) => {
335 const currentModels = group.models.filter((model) => !model.isLegacy);
336 const legacyModels = group.models.filter((model) => model.isLegacy);
337 const selected = group.models.find(
338 (model) =>
339 model.selection.instanceId === selectedModel?.instanceId &&
340 model.selection.model === selectedModel.model,
341 );
342
343 return [
344 ...(currentModels.length > 0
345 ? [
346 {
347 id: `provider:${group.providerKey}`,
348 title: group.providerLabel,
349 subtitle: selected && !selected.isLegacy ? selected.label : undefined,
350 subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
351 },
352 ]
353 : []),
354 ...(legacyModels.length > 0
355 ? [
356 {
357 id: `legacy-models:${group.providerKey}`,
358 title: `${group.providerLabel} legacy models`,
359 subtitle: selected?.isLegacy ? selected.label : undefined,
360 subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
361 },
362 ]
363 : []),
364 ];
365 });
366}