Open History to see the last commit
1import type { MenuAction } from "@react-native-menu/menu";
2import type {
3 ModelCapabilities,
4 ModelSelection,
5 ProjectId,
6 RuntimeMode,
7 ServerConfig as T3ServerConfig,
8} from "@t3tools/contracts";
9import { resolveProjectProviderInstanceEnabled } from "@t3tools/contracts";
10import {
11 buildExplicitProviderOptionSelectionsFromDescriptors,
12 getProviderOptionDescriptors,
13} from "@t3tools/shared/model";
14
15export type ModelOption = {
16 readonly key: string;
17 readonly label: string;
18 readonly subtitle: string;
19 readonly providerKey: string;
20 readonly providerLabel: string;
21 readonly providerDriver: string;
22 readonly supportedRuntimeModes?: ReadonlyArray<RuntimeMode>;
23 readonly providerIconUrl?: string | undefined;
24 readonly isDefault: boolean;
25 readonly isLegacy: boolean;
26 readonly isUnavailable?: boolean;
27 readonly isHidden?: boolean;
28 readonly canHide?: boolean;
29 readonly capabilities: ModelCapabilities | null;
30 readonly selection: ModelSelection;
31 readonly providerUpdateRequired?: ProviderUpdateRequired;
32};
33
34type ProviderUpdateRequired = Pick<
35 T3ServerConfig["providers"][number],
36 "driver" | "updateRequiredModels"
37>;
38
39export type ProviderGroup = {
40 readonly providerKey: string;
41 readonly providerLabel: string;
42 readonly models: ReadonlyArray<ModelOption>;
43 readonly updateRequired?: ProviderUpdateRequired;
44};
45
46function providerDisplayLabel(provider: {
47 readonly displayName?: string | undefined;
48 readonly driver: string;
49 readonly instanceId: string;
50}): string {
51 if (provider.displayName) return provider.displayName;
52 if (provider.driver === "codex") return "Codex";
53 if (provider.driver === "claudeAgent") return "Claude";
54 if (provider.driver === "pi") return "Pi";
55 return provider.instanceId;
56}
57
58function isProviderEnabledForProject(
59 config: T3ServerConfig | null | undefined,
60 provider:
61 | { readonly instanceId: ModelSelection["instanceId"]; readonly enabled: boolean }
62 | undefined,
63 projectId: ProjectId | null,
64): boolean {
65 if (!provider) {
66 return false;
67 }
68 return config?.settings
69 ? resolveProjectProviderInstanceEnabled(config.settings, projectId, provider.instanceId)
70 : provider.enabled;
71}
72
73function isProjectDisabledOverride(
74 config: T3ServerConfig | null | undefined,
75 instanceId: ModelSelection["instanceId"],
76 projectId: ProjectId | null,
77): boolean {
78 if (!projectId || !config?.settings) {
79 return false;
80 }
81 return (
82 config.settings.projectSettingsOverrides[projectId]?.providerInstances?.[instanceId]
83 ?.enabled === false
84 );
85}
86
87function isDisabledForProject(
88 config: T3ServerConfig | null | undefined,
89 provider:
90 | { readonly instanceId: ModelSelection["instanceId"]; readonly enabled: boolean }
91 | undefined,
92 instanceId: ModelSelection["instanceId"],
93 projectId: ProjectId | null,
94): boolean {
95 if (isProjectDisabledOverride(config, instanceId, projectId)) {
96 return true;
97 }
98 return provider !== undefined && !isProviderEnabledForProject(config, provider, projectId);
99}
100
101function normalizeSelectionOptions(
102 selection: ModelSelection,
103 capabilities: ModelCapabilities | null,
104): ModelSelection {
105 if (!capabilities) {
106 return selection;
107 }
108 if (!selection.options?.length) {
109 return { instanceId: selection.instanceId, model: selection.model };
110 }
111 const options = buildExplicitProviderOptionSelectionsFromDescriptors(
112 getProviderOptionDescriptors({
113 caps: capabilities,
114 selections: selection.options,
115 }),
116 selection.options,
117 );
118 return options
119 ? { ...selection, options }
120 : {
121 instanceId: selection.instanceId,
122 model: selection.model,
123 };
124}
125
126/**
127 * `projectId` has no default: a caller that forgets it would silently check only the
128 * machine-wide state and miss a project that turned this instance off. Pass `null` explicitly
129 * outside a project's scope.
130 */
131export function isModelSelectionUnavailable(
132 config: T3ServerConfig | null | undefined,
133 selection: ModelSelection | null | undefined,
134 projectId: ProjectId | null,
135): boolean {
136 if (!config || !selection) {
137 return false;
138 }
139 const provider = config.providers.find(
140 (candidate) => candidate.instanceId === selection.instanceId,
141 );
142 if (isDisabledForProject(config, provider, selection.instanceId, projectId)) {
143 return true;
144 }
145 const driver =
146 provider?.driver ?? config.settings?.providerInstances[selection.instanceId]?.driver;
147 return (
148 driver === "antigravity" &&
149 (!provider ||
150 !provider.installed ||
151 provider.auth.status === "unauthenticated" ||
152 provider.availability === "unavailable" ||
153 !provider.models.some((model) => model.slug === selection.model))
154 );
155}
156
157export function describeUnavailableModelSelection(
158 config: T3ServerConfig | null | undefined,
159 selection: ModelSelection,
160 projectId: ProjectId | null,
161): { readonly title: string; readonly detail: string } {
162 const provider = config?.providers.find(
163 (candidate) => candidate.instanceId === selection.instanceId,
164 );
165 return isDisabledForProject(config, provider, selection.instanceId, projectId)
166 ? {
167 title: "Model turned off for this project",
168 detail: "Turn it back on from web or desktop, or choose another model.",
169 }
170 : {
171 title: "Antigravity model unavailable",
172 detail: "Set up Antigravity on web or desktop, or choose another model.",
173 };
174}
175
176export function resolveSelectableModelSelection(
177 config: T3ServerConfig | null | undefined,
178 selection: ModelSelection | null,
179 projectId: ProjectId | null,
180): ModelSelection | null {
181 if (!selection || !config) {
182 return selection;
183 }
184 const provider = config.providers.find(
185 (candidate) => candidate.instanceId === selection.instanceId,
186 );
187 const driver =
188 provider?.driver ?? config.settings?.providerInstances[selection.instanceId]?.driver;
189 if (driver === "antigravity") {
190 return isProjectDisabledOverride(config, selection.instanceId, projectId) ? null : selection;
191 }
192 return provider &&
193 isProviderEnabledForProject(config, provider, projectId) &&
194 provider.installed &&
195 provider.auth.status !== "unauthenticated"
196 ? selection
197 : null;
198}
199
200export function resolveDefaultableModelSelection(
201 config: T3ServerConfig | null | undefined,
202 selection: ModelSelection | null,
203 projectId: ProjectId | null,
204): ModelSelection | null {
205 const usable = resolveSelectableModelSelection(config, selection, projectId);
206 if (!usable || !config) {
207 return usable;
208 }
209 const provider = config.providers.find((candidate) => candidate.instanceId === usable.instanceId);
210 const model = provider?.models.find((candidate) => candidate.slug === usable.model);
211 return provider?.driver !== "antigravity" && model?.isLegacy === true ? null : usable;
212}
213
214export function resolveNewTaskModelSelection(input: {
215 readonly draftSelection: ModelSelection | null;
216 readonly projectDefaultSelection: ModelSelection | null;
217 readonly stickySelection: ModelSelection | null;
218 readonly modelOptions: ReadonlyArray<ModelOption>;
219}): ModelSelection | null {
220 return (
221 input.draftSelection ??
222 input.projectDefaultSelection ??
223 input.stickySelection ??
224 input.modelOptions.find((option) => option.isDefault && !option.isUnavailable)?.selection ??
225 input.modelOptions.find((option) => !option.isUnavailable)?.selection ??
226 null
227 );
228}
229
230export function buildModelOptions(
231 config: T3ServerConfig | null | undefined,
232 fallbackModelSelection: ModelSelection | null,
233 providerInstanceId: ModelSelection["instanceId"] | undefined,
234 projectId: ProjectId | null,
235 includeHidden = false,
236): ReadonlyArray<ModelOption> {
237 const options = new Map<string, ModelOption>();
238
239 for (const provider of config?.providers ?? []) {
240 if (
241 (providerInstanceId !== undefined && provider.instanceId !== providerInstanceId) ||
242 !isProviderEnabledForProject(config, provider, projectId) ||
243 !provider.installed ||
244 provider.auth.status === "unauthenticated" ||
245 (provider.driver === "antigravity" && provider.availability === "unavailable")
246 ) {
247 continue;
248 }
249
250 const providerLabel = providerDisplayLabel(provider);
251 const updateRequired = provider.updateRequiredModels?.length
252 ? { driver: provider.driver, updateRequiredModels: provider.updateRequiredModels }
253 : undefined;
254 const preferences = config?.settings?.providerModelPreferences?.[provider.instanceId];
255 const hiddenModels = new Set(preferences?.hiddenModels ?? []);
256 const order = new Map((preferences?.modelOrder ?? []).map((slug, index) => [slug, index]));
257 const models = provider.models.filter(
258 (model) => includeHidden || model.isCustom || !hiddenModels.has(model.slug),
259 );
260 if (order.size > 0)
261 models.sort((a, b) => (order.get(a.slug) ?? Infinity) - (order.get(b.slug) ?? Infinity));
262 for (const model of models) {
263 const key = `${provider.instanceId}:${model.slug}`;
264 options.set(key, {
265 key,
266 label: model.name,
267 subtitle: model.subProvider ?? "",
268 providerKey: provider.instanceId,
269 providerLabel,
270 providerDriver: provider.driver,
271 ...(provider.supportedRuntimeModes === undefined
272 ? {}
273 : { supportedRuntimeModes: provider.supportedRuntimeModes }),
274 ...(provider.iconUrl ? { providerIconUrl: provider.iconUrl } : {}),
275 isHidden: !model.isCustom && hiddenModels.has(model.slug),
276 canHide: !model.isCustom,
277 isDefault: model.isDefault === true,
278 isLegacy: model.isLegacy === true,
279 ...(updateRequired ? { providerUpdateRequired: updateRequired } : {}),
280 capabilities: model.capabilities,
281 selection: normalizeSelectionOptions(
282 {
283 instanceId: provider.instanceId,
284 model: model.slug,
285 },
286 model.capabilities,
287 ),
288 });
289 }
290 }
291
292 if (
293 fallbackModelSelection &&
294 (providerInstanceId === undefined ||
295 fallbackModelSelection.instanceId === providerInstanceId) &&
296 (!config?.settings?.providerModelPreferences?.[
297 fallbackModelSelection.instanceId
298 ]?.hiddenModels.includes(fallbackModelSelection.model) ||
299 config?.providers
300 .find((provider) => provider.instanceId === fallbackModelSelection.instanceId)
301 ?.models.find((model) => model.slug === fallbackModelSelection.model)?.isCustom)
302 ) {
303 const key = `${fallbackModelSelection.instanceId}:${fallbackModelSelection.model}`;
304 const existing = options.get(key);
305 if (existing) {
306 options.set(key, {
307 ...existing,
308 selection:
309 existing.providerDriver === "antigravity"
310 ? fallbackModelSelection
311 : normalizeSelectionOptions(fallbackModelSelection, existing.capabilities),
312 });
313 } else {
314 const provider = config?.providers.find(
315 (candidate) => candidate.instanceId === fallbackModelSelection.instanceId,
316 );
317 const instanceConfig = config?.settings?.providerInstances[fallbackModelSelection.instanceId];
318 const model = provider?.models.find(
319 (candidate) => candidate.slug === fallbackModelSelection.model,
320 );
321 const providerDriver =
322 provider?.driver ?? instanceConfig?.driver ?? fallbackModelSelection.instanceId;
323 const providerLabel = providerDisplayLabel({
324 driver: providerDriver,
325 displayName: provider?.displayName ?? instanceConfig?.displayName,
326 instanceId: fallbackModelSelection.instanceId,
327 });
328 options.set(key, {
329 key,
330 label: model?.name ?? fallbackModelSelection.model,
331 subtitle: model?.subProvider ?? "",
332 providerKey: fallbackModelSelection.instanceId,
333 providerLabel,
334 providerDriver,
335 isDefault: false,
336 isLegacy: model?.isLegacy === true,
337 ...(isModelSelectionUnavailable(config, fallbackModelSelection, projectId) ||
338 (provider !== undefined && !isProviderEnabledForProject(config, provider, projectId)) ||
339 provider?.updateRequiredModels?.some((gated) => gated.slug === fallbackModelSelection.model)
340 ? { isUnavailable: true }
341 : {}),
342 capabilities: model?.capabilities ?? null,
343 selection: fallbackModelSelection,
344 });
345 }
346 }
347
348 return [...options.values()];
349}
350
351export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyArray<ProviderGroup> {
352 const groups = new Map<
353 string,
354 {
355 providerLabel: string;
356 models: ModelOption[];
357 updateRequired: ProviderUpdateRequired | undefined;
358 }
359 >();
360 for (const option of options) {
361 const existing = groups.get(option.providerKey);
362 if (existing) {
363 existing.models.push(option);
364 existing.updateRequired ??= option.providerUpdateRequired;
365 } else {
366 groups.set(option.providerKey, {
367 providerLabel: option.providerLabel,
368 models: [option],
369 updateRequired: option.providerUpdateRequired,
370 });
371 }
372 }
373
374 return [...groups.entries()].map(([providerKey, group]) => ({
375 providerKey,
376 providerLabel: group.providerLabel,
377 models: group.models,
378 ...(group.updateRequired ? { updateRequired: group.updateRequired } : {}),
379 }));
380}
381
382function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
383 return {
384 id: `model:${option.key}`,
385 title: option.label,
386 state:
387 option.selection.instanceId === selectedModel?.instanceId &&
388 option.selection.model === selectedModel.model
389 ? "on"
390 : undefined,
391 };
392}
393
394export function buildModelMenuActions(
395 groups: ReadonlyArray<ProviderGroup>,
396 selectedModel: ModelSelection | null,
397): MenuAction[] {
398 return groups.flatMap((group) => {
399 const currentModels = group.models.filter((model) => !model.isLegacy);
400 const legacyModels = group.models.filter((model) => model.isLegacy);
401 const selected = group.models.find(
402 (model) =>
403 model.selection.instanceId === selectedModel?.instanceId &&
404 model.selection.model === selectedModel.model,
405 );
406
407 return [
408 ...(currentModels.length > 0
409 ? [
410 {
411 id: `provider:${group.providerKey}`,
412 title: group.providerLabel,
413 subtitle: selected && !selected.isLegacy ? selected.label : undefined,
414 subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
415 },
416 ]
417 : []),
418 ...(legacyModels.length > 0
419 ? [
420 {
421 id: `legacy-models:${group.providerKey}`,
422 title: `${group.providerLabel} legacy models`,
423 subtitle: selected?.isLegacy ? selected.label : undefined,
424 subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
425 },
426 ]
427 : []),
428 ];
429 });
430}