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

providerInstances.ts

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