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