Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

providerInstances.ts

420 lines16.5 KB

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>;
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";
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";
95​
96/** Picker rails contain configured, enabled instances only. */
97export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
98 return entry.enabled;
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(" ");
126​
127function driverKindLabel(driverKind: ProviderDriverKind): string {
128 return PROVIDER_DISPLAY_NAMES[driverKind] ?? formatProviderDriverKindLabel(driverKind);
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;
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;
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;
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 });
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;
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 * Only built-in default instances have a legacy `providers` entry. Every
255 * other instance exists through `providerInstances`; if it is absent there,
256 * its streamed snapshot is stale (for example immediately after deletion)
257 * and is treated as disabled.
258 */
259export function applyProviderInstanceSettings(
260 entries: ReadonlyArray<ProviderInstanceEntry>,
261 settings: Pick<ServerSettings, "providerInstances" | "providers">,
262): ReadonlyArray<ProviderInstanceEntry> {
263 const legacyProviders = settings.providers as Readonly<
264 Record<string, { readonly enabled?: boolean } | undefined>
265 >;
266​
267 return entries.map((entry) => {
268 const explicitInstance = Object.hasOwn(settings.providerInstances, entry.instanceId)
269 ? settings.providerInstances[entry.instanceId]
270 : undefined;
271 const legacyProvider = Object.hasOwn(legacyProviders, entry.driverKind)
272 ? legacyProviders[entry.driverKind]
273 : undefined;
274 const enabled = explicitInstance
275 ? resolveProviderInstanceEnabled(explicitInstance)
276 : entry.isDefault && legacyProvider
277 ? (legacyProvider.enabled ?? entry.enabled)
278 : false;
279 return enabled === entry.enabled ? entry : { ...entry, enabled };
280 });
282​
283/**
284 * Sort instance entries so the default instance of each driver kind appears
285 * before any custom instances of the same kind. Within a kind, custom
286 * instances keep their settings-author order (which is how the server
287 * emits them). Stable across kinds: entries retain the server's
288 * cross-driver ordering.
289 */
290export function sortProviderInstanceEntries(
291 entries: ReadonlyArray<ProviderInstanceEntry>,
292): ReadonlyArray<ProviderInstanceEntry> {
293 // Group by driver kind preserving first-appearance order, then emit
294 // default-first within each kind. Using a Map keeps the "first-seen"
295 // semantics for kinds whose default instance is absent (unusual but
296 // possible during the migration).
297 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
298 for (const entry of entries) {
299 const bucket = byKind.get(entry.driverKind);
300 if (bucket) {
301 bucket.push(entry);
302 } else {
303 byKind.set(entry.driverKind, [entry]);
304 }
305 }
306 const sorted: ProviderInstanceEntry[] = [];
307 for (const bucket of byKind.values()) {
308 const defaults = bucket.filter((entry) => entry.isDefault);
309 const customs = bucket.filter((entry) => !entry.isDefault);
310 sorted.push(...defaults, ...customs);
311 }
312 return sorted;
314​
315/**
316 * Look up a single instance entry by exact `instanceId`. Missing snapshots
317 * are not inferred from driver kind in UI routing code.
318 */
319export function getProviderInstanceEntry(
320 providers: ReadonlyArray<ServerProvider>,
321 instanceId: ProviderInstanceId,
322): ProviderInstanceEntry | undefined {
323 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
325​
326/**
327 * Default model slug for a specific instance: its declared built-in default,
328 * then its first built-in model, then any model it reports, then the driver-level default. Custom
329 * instances can serve a different model list than the default instance of
330 * the same driver kind, so the lookup must be instance-scoped rather than
331 * kind-scoped.
332 */
333export function getDefaultProviderInstanceModel(
334 providers: ReadonlyArray<ServerProvider>,
335 instanceId: ProviderInstanceId,
336): string | undefined {
337 const entry = getProviderInstanceEntry(providers, instanceId);
338 if (!entry) return undefined;
339 return (
340 entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ??
341 entry.models.find((model) => !model.isCustom)?.slug ??
342 entry.models[0]?.slug ??
343 DEFAULT_MODEL_BY_PROVIDER[entry.driverKind]
344 );
346​
347const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean =>
348 entry.enabled && entry.isAvailable;
349​
350/**
351 * Resolve an exact stored instance when it remains enabled and available.
352 * Otherwise choose a deterministic fallback that can plausibly start now:
353 * ready first, then a non-error probe result. An errored provider is retained
354 * only when it was explicitly requested; it is never invented as a new-user
355 * default.
356 */
357export function resolveSelectableProviderInstanceEntry(
358 entries: ReadonlyArray<ProviderInstanceEntry>,
359 instanceId: ProviderInstanceId | undefined,
360): ProviderInstanceEntry | undefined {
361 if (instanceId !== undefined) {
362 const requested = entries.find((entry) => entry.instanceId === instanceId);
363 if (requested && isSelectableProviderInstanceEntry(requested)) {
364 return requested;
365 }
366 }
367 return (
368 entries.find(isProviderInstancePickerReady) ??
369 entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error")
370 );
372​
373/**
374 * Resolve the routing key for a selection that may reference an instance
375 * id that no longer exists (e.g. a persisted thread selection after the
376 * user deleted the custom instance). Returns a ready or non-error fallback,
377 * or `undefined` when no provider can safely become a new selection.
378 */
379export function resolveSelectableProviderInstance(
380 providers: ReadonlyArray<ServerProvider>,
381 instanceId: ProviderInstanceId | undefined,
382): ProviderInstanceId | undefined {
383 const entries = deriveProviderInstanceEntries(providers);
384 return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId;
386​
387/**
388 * Resolve the model selection persisted for a project or new thread. A valid
389 * stored selection is preserved byte-for-byte. Falling back to another
390 * instance also resets the model to that instance's own default, avoiding
391 * cross-provider instance/model pairs.
392 */
393export function resolveDefaultProviderModelSelection(
394 providers: ReadonlyArray<ServerProvider>,
395 selection: ModelSelection | null | undefined,
396): ModelSelection | null {
397 const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId);
398 if (instanceId === undefined) return null;
399 if (selection?.instanceId === instanceId) return selection;
400 const model = getDefaultProviderInstanceModel(providers, instanceId);
401 return model ? { instanceId, model } : null;
403​
404/**
405 * Resolve an open model-selection routing key back to a driver kind.
406 * Custom instance ids such as `claude_openrouter` are not themselves
407 * driver-kind slugs, but the composer still needs the owning driver kind
408 * for capabilities, options, icons, and turn dispatch metadata.
409 */
410export function resolveProviderDriverKindForInstanceSelection(
411 entries: ReadonlyArray<ProviderInstanceEntry>,
412 providers: ReadonlyArray<ServerProvider>,
413 selection: ProviderInstanceId | ProviderDriverKind | null | undefined,
414): ProviderDriverKind | undefined {
415 const matchedEntry = entries.find((entry) => entry.instanceId === selection);
416 if (matchedEntry) {
417 return matchedEntry.driverKind;
418 }
419 return undefined;