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