Open History to see the last commit
1/**
2 * Instance-aware view over the wire `ServerProvider[]`.
3 *
4 * The wire carries one `ServerProvider` per *configured instance* — the
5 * default built-in codex instance, a user-authored `codex_personal`, an
6 * unavailable shadow for a fork driver, etc. Legacy UI code collapsed these
7 * into a single bucket per built-in driver via `.find((p) => p.driver === kind)`,
8 * which silently dropped every custom instance after the first. This module
9 * replaces that pattern with `ProviderInstanceEntry[]`, keyed on
10 * `ProviderInstanceId`, so the model picker, settings list, and composer
11 * can treat built-in and custom instances uniformly.
12 *
13 * @module providerInstances
14 */
15import {
16 DEFAULT_MODEL_BY_PROVIDER,
17 defaultInstanceIdForDriver,
18 PROVIDER_DISPLAY_NAMES,
19 type ModelSelection,
20 type ProviderDriverKind,
21 ProviderInstanceId,
22 type ServerProvider,
23 type ServerProviderModel,
24 type ServerSettings,
25 type ServerProviderState,
26} from "@t3tools/contracts";
27
28import { formatProviderDriverKindLabel } from "./providerModels";
29
30/**
31 * Local-only placeholder used while a draft has no provider it can safely
32 * target. It must never be persisted or dispatched; the composer disables
33 * send until a live provider replaces it.
34 */
35export const NO_PROVIDER_MODEL_SELECTION: ModelSelection = {
36 instanceId: ProviderInstanceId.make("t3code_no_provider"),
37 model: "",
38};
39
40/**
41 * UI-facing projection of one configured provider instance. Carries the
42 * snapshot verbatim for callers that need server-side fields we don't
43 * hoist here, plus the precomputed `instanceId` / `driverKind` /
44 * `displayName` used by every picker and settings view.
45 */
46export interface ProviderInstanceEntry {
47 readonly instanceId: ProviderInstanceId;
48 readonly driverKind: ProviderDriverKind;
49 readonly displayName: string;
50 readonly accentColor?: string | undefined;
51 readonly continuationGroupKey?: string | undefined;
52 readonly enabled: boolean;
53 readonly installed: boolean;
54 readonly status: ServerProviderState;
55 /**
56 * True when this entry is the default instance for its driver kind —
57 * i.e. its instance id equals `defaultInstanceIdForDriver(driverKind)`.
58 * The settings panel and picker sort defaults before customs.
59 */
60 readonly isDefault: boolean;
61 /** True when `availability === "unavailable"` is absent or "available". */
62 readonly isAvailable: boolean;
63 readonly snapshot: ServerProvider;
64 readonly models: ReadonlyArray<ServerProviderModel>;
65}
66
67/**
68 * Whether an instance can currently contribute models to an interactive picker.
69 *
70 * Disabling an instance updates `enabled` independently, while its previous
71 * `ready` probe status can remain in the streamed snapshot until reconciliation.
72 */
73export function isProviderInstancePickerReady(entry: ProviderInstanceEntry): boolean {
74 return entry.enabled && entry.isAvailable && entry.status === "ready";
75}
76
77/** Picker rails contain configured, enabled instances only. */
78export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
79 return entry.enabled;
80}
81
82/**
83 * Turn an instance id slug into a human-readable label. Splits on `_` / `-`
84 * and camelCase boundaries and title-cases each token, so `codex_personal`
85 * becomes "Codex Personal" and `myCustomInstance` becomes "My Custom
86 * Instance".
87 *
88 * This is a fallback used only when the wire snapshot's `displayName`
89 * doesn't disambiguate a non-default instance from the default one of the
90 * same driver (today every built-in driver hard-codes a single presentation
91 * label per kind, so two instances of the same kind arrive with identical
92 * display names). When a server/driver later plumbs the user's configured
93 * `ProviderInstanceConfig.displayName` through to the snapshot, that value
94 * will take precedence over this fallback.
95 */
96function humanizeInstanceId(instanceId: ProviderInstanceId): string {
97 const words: string[] = [];
98 for (const token of instanceId
99 .replace(/[_-]+/g, " ")
100 .replace(/([a-z])([A-Z])/g, "$1 $2")
101 .split(" ")) {
102 if (token.length === 0) continue;
103 words.push(token.charAt(0).toUpperCase() + token.slice(1));
104 }
105 return words.join(" ");
106}
107
108function driverKindLabel(driverKind: ProviderDriverKind): string {
109 return PROVIDER_DISPLAY_NAMES[driverKind] ?? formatProviderDriverKindLabel(driverKind);
110}
111
112export function normalizeProviderAccentColor(value: string | undefined): string | undefined {
113 const trimmed = value?.trim();
114 if (!trimmed) return undefined;
115 return /^#[0-9a-fA-F]{6}$/u.test(trimmed) ? trimmed : undefined;
116}
117
118/**
119 * Resolve an entry's displayName with a tiered priority:
120 *
121 * 1. A snapshot `displayName` that differs from the driver-kind label —
122 * the server has explicitly named this instance, trust it.
123 * 2. For non-default instances, a humanized `instanceId` — the server
124 * fell back to the driver-level presentation constant (which is the
125 * same for every instance of that kind), so we differentiate at the
126 * UI layer by slug. This is what keeps "Codex" + "Codex Personal"
127 * distinguishable in tooltips and list labels today.
128 * 3. The snapshot's `displayName` (if any) — default instance, trust
129 * whatever label the driver stamped.
130 * 4. `driverKindLabel(driverKind)` — nothing else on hand, so use the
131 * canonical brand label from contracts (falling back to a generic
132 * title-case of the kind slug).
133 */
134function resolveInstanceDisplayName(
135 snapshot: ServerProvider,
136 instanceId: ProviderInstanceId,
137 driverKind: ProviderDriverKind,
138 isDefault: boolean,
139): string {
140 const trimmedSnapshotName = snapshot.displayName?.trim();
141 const kindLabel = driverKindLabel(driverKind);
142 if (trimmedSnapshotName && trimmedSnapshotName !== kindLabel) {
143 return trimmedSnapshotName;
144 }
145 if (!isDefault) {
146 const humanized = humanizeInstanceId(instanceId);
147 if (humanized.length > 0) return humanized;
148 }
149 return trimmedSnapshotName || kindLabel;
150}
151
152/**
153 * Project the wire `ServerProvider[]` into instance entries, one per
154 * configured instance. Preserves the server's ordering (which sources
155 * from `deriveProviderInstanceConfigMap` — explicit `providerInstances.*`
156 * first, synthesized defaults after) so callers that want "default first"
157 * should sort with `sortProviderInstanceEntries` below.
158 */
159export function deriveProviderInstanceEntries(
160 providers: ReadonlyArray<ServerProvider>,
161): ReadonlyArray<ProviderInstanceEntry> {
162 return providers.map((snapshot) => {
163 const instanceId = snapshot.instanceId;
164 const driverKind = snapshot.driver;
165 const defaultId = defaultInstanceIdForDriver(driverKind);
166 const isDefault = instanceId === defaultId;
167 const displayName = resolveInstanceDisplayName(snapshot, instanceId, driverKind, isDefault);
168 return {
169 instanceId,
170 driverKind,
171 displayName,
172 accentColor: normalizeProviderAccentColor(snapshot.accentColor),
173 continuationGroupKey: snapshot.continuation?.groupKey,
174 enabled: snapshot.enabled,
175 installed: snapshot.installed,
176 status: snapshot.status,
177 isDefault,
178 isAvailable: snapshot.availability !== "unavailable",
179 snapshot,
180 models: snapshot.models,
181 } satisfies ProviderInstanceEntry;
182 });
183}
184
185/**
186 * Overlay the current settings configuration onto streamed provider snapshots.
187 * Provider probes can briefly retain their previous `enabled` value after a
188 * settings write, so picker visibility must follow settings rather than waiting
189 * for probe reconciliation.
190 *
191 * Non-default instances only exist through `providerInstances`; if one is
192 * absent there, its streamed snapshot is stale (for example immediately after
193 * deletion) and is treated as disabled.
194 */
195export function applyProviderInstanceSettings(
196 entries: ReadonlyArray<ProviderInstanceEntry>,
197 settings: Pick<ServerSettings, "providerInstances" | "providers">,
198): ReadonlyArray<ProviderInstanceEntry> {
199 const legacyProviders = settings.providers as Readonly<
200 Record<string, { readonly enabled?: boolean } | undefined>
201 >;
202
203 return entries.map((entry) => {
204 const explicitInstance = settings.providerInstances?.[entry.instanceId];
205 const enabled = explicitInstance
206 ? (explicitInstance.enabled ?? true)
207 : entry.isDefault
208 ? (legacyProviders[entry.driverKind]?.enabled ?? entry.enabled)
209 : false;
210 return enabled === entry.enabled ? entry : { ...entry, enabled };
211 });
212}
213
214/**
215 * Sort instance entries so the default instance of each driver kind appears
216 * before any custom instances of the same kind. Within a kind, custom
217 * instances keep their settings-author order (which is how the server
218 * emits them). Stable across kinds: entries retain the server's
219 * cross-driver ordering.
220 */
221export function sortProviderInstanceEntries(
222 entries: ReadonlyArray<ProviderInstanceEntry>,
223): ReadonlyArray<ProviderInstanceEntry> {
224 // Group by driver kind preserving first-appearance order, then emit
225 // default-first within each kind. Using a Map keeps the "first-seen"
226 // semantics for kinds whose default instance is absent (unusual but
227 // possible during the migration).
228 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
229 for (const entry of entries) {
230 const bucket = byKind.get(entry.driverKind);
231 if (bucket) {
232 bucket.push(entry);
233 } else {
234 byKind.set(entry.driverKind, [entry]);
235 }
236 }
237 const sorted: ProviderInstanceEntry[] = [];
238 for (const bucket of byKind.values()) {
239 const defaults = bucket.filter((entry) => entry.isDefault);
240 const customs = bucket.filter((entry) => !entry.isDefault);
241 sorted.push(...defaults, ...customs);
242 }
243 return sorted;
244}
245
246/**
247 * Look up a single instance entry by exact `instanceId`. Missing snapshots
248 * are not inferred from driver kind in UI routing code.
249 */
250export function getProviderInstanceEntry(
251 providers: ReadonlyArray<ServerProvider>,
252 instanceId: ProviderInstanceId,
253): ProviderInstanceEntry | undefined {
254 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
255}
256
257/**
258 * Model list for a specific instance. Returns `[]` when the instance isn't
259 * present so callers don't have to thread optionality through render code.
260 */
261export function getProviderInstanceModels(
262 providers: ReadonlyArray<ServerProvider>,
263 instanceId: ProviderInstanceId,
264): ReadonlyArray<ServerProviderModel> {
265 return getProviderInstanceEntry(providers, instanceId)?.models ?? [];
266}
267
268/**
269 * Default model slug for a specific instance: its declared built-in default,
270 * then its first built-in model, then any model it reports, then the driver-level default. Custom
271 * instances can serve a different model list than the default instance of
272 * the same driver kind, so the lookup must be instance-scoped rather than
273 * kind-scoped.
274 */
275export function getDefaultProviderInstanceModel(
276 providers: ReadonlyArray<ServerProvider>,
277 instanceId: ProviderInstanceId,
278): string | undefined {
279 const entry = getProviderInstanceEntry(providers, instanceId);
280 if (!entry) return undefined;
281 return (
282 entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ??
283 entry.models.find((model) => !model.isCustom)?.slug ??
284 entry.models[0]?.slug ??
285 DEFAULT_MODEL_BY_PROVIDER[entry.driverKind]
286 );
287}
288
289const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean =>
290 entry.enabled && entry.isAvailable;
291
292/**
293 * Resolve an exact stored instance when it remains enabled and available.
294 * Otherwise choose a deterministic fallback that can plausibly start now:
295 * ready first, then a non-error probe result. An errored provider is retained
296 * only when it was explicitly requested; it is never invented as a new-user
297 * default.
298 */
299export function resolveSelectableProviderInstanceEntry(
300 entries: ReadonlyArray<ProviderInstanceEntry>,
301 instanceId: ProviderInstanceId | undefined,
302): ProviderInstanceEntry | undefined {
303 if (instanceId !== undefined) {
304 const requested = entries.find((entry) => entry.instanceId === instanceId);
305 if (requested && isSelectableProviderInstanceEntry(requested)) {
306 return requested;
307 }
308 }
309 return (
310 entries.find(isProviderInstancePickerReady) ??
311 entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error")
312 );
313}
314
315/**
316 * Resolve the routing key for a selection that may reference an instance
317 * id that no longer exists (e.g. a persisted thread selection after the
318 * user deleted the custom instance). Returns a ready or non-error fallback,
319 * or `undefined` when no provider can safely become a new selection.
320 */
321export function resolveSelectableProviderInstance(
322 providers: ReadonlyArray<ServerProvider>,
323 instanceId: ProviderInstanceId | undefined,
324): ProviderInstanceId | undefined {
325 const entries = deriveProviderInstanceEntries(providers);
326 return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId;
327}
328
329/**
330 * Resolve the model selection persisted for a project or new thread. A valid
331 * stored selection is preserved byte-for-byte. Falling back to another
332 * instance also resets the model to that instance's own default, avoiding
333 * cross-provider instance/model pairs.
334 */
335export function resolveDefaultProviderModelSelection(
336 providers: ReadonlyArray<ServerProvider>,
337 selection: ModelSelection | null | undefined,
338): ModelSelection | null {
339 const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId);
340 if (instanceId === undefined) return null;
341 if (selection?.instanceId === instanceId) return selection;
342 const model = getDefaultProviderInstanceModel(providers, instanceId);
343 return model ? { instanceId, model } : null;
344}
345
346/**
347 * Resolve an open model-selection routing key back to a driver kind.
348 * Custom instance ids such as `claude_openrouter` are not themselves
349 * driver-kind slugs, but the composer still needs the owning driver kind
350 * for capabilities, options, icons, and turn dispatch metadata.
351 */
352export function resolveProviderDriverKindForInstanceSelection(
353 entries: ReadonlyArray<ProviderInstanceEntry>,
354 providers: ReadonlyArray<ServerProvider>,
355 selection: ProviderInstanceId | ProviderDriverKind | null | undefined,
356): ProviderDriverKind | undefined {
357 const matchedEntry = entries.find((entry) => entry.instanceId === selection);
358 if (matchedEntry) {
359 return matchedEntry.driverKind;
360 }
361 return undefined;
362}