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

providerInstances.ts

379 lines14.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 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>;
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";
76​
77/** Picker rails contain configured, enabled instances only. */
78export function isProviderInstancePickerVisible(entry: ProviderInstanceEntry): boolean {
79 return entry.enabled;
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(" ");
107​
108function driverKindLabel(driverKind: ProviderDriverKind): string {
109 return PROVIDER_DISPLAY_NAMES[driverKind] ?? formatProviderDriverKindLabel(driverKind);
111​
112/**
113 * Whether an instance's icon carries the account badge: accent color set, or
114 * several instances sharing a driver so the brand glyph alone is ambiguous.
115 * Shared by the composer trigger, the picker rail, and sidebar rows.
116 */
117export function shouldShowInstanceBadge(
118 entry: ProviderInstanceEntry,
119 entries: Iterable<ProviderInstanceEntry>,
120): boolean {
121 if (entry.accentColor) return true;
122 let sharedDriverCount = 0;
123 for (const candidate of entries) {
124 if (candidate.driverKind === entry.driverKind && ++sharedDriverCount > 1) return true;
125 }
126 return false;
128​
129export function normalizeProviderAccentColor(value: string | undefined): string | undefined {
130 const trimmed = value?.trim();
131 if (!trimmed) return undefined;
132 return /^#[0-9a-fA-F]{6}$/u.test(trimmed) ? trimmed : undefined;
134​
135/**
136 * Resolve an entry's displayName with a tiered priority:
137 *
138 * 1. A snapshot `displayName` that differs from the driver-kind label —
139 * the server has explicitly named this instance, trust it.
140 * 2. For non-default instances, a humanized `instanceId` — the server
141 * fell back to the driver-level presentation constant (which is the
142 * same for every instance of that kind), so we differentiate at the
143 * UI layer by slug. This is what keeps "Codex" + "Codex Personal"
144 * distinguishable in tooltips and list labels today.
145 * 3. The snapshot's `displayName` (if any) — default instance, trust
146 * whatever label the driver stamped.
147 * 4. `driverKindLabel(driverKind)` — nothing else on hand, so use the
148 * canonical brand label from contracts (falling back to a generic
149 * title-case of the kind slug).
150 */
151function resolveInstanceDisplayName(
152 snapshot: ServerProvider,
153 instanceId: ProviderInstanceId,
154 driverKind: ProviderDriverKind,
155 isDefault: boolean,
156): string {
157 const trimmedSnapshotName = snapshot.displayName?.trim();
158 const kindLabel = driverKindLabel(driverKind);
159 if (trimmedSnapshotName && trimmedSnapshotName !== kindLabel) {
160 return trimmedSnapshotName;
161 }
162 if (!isDefault) {
163 const humanized = humanizeInstanceId(instanceId);
164 if (humanized.length > 0) return humanized;
165 }
166 return trimmedSnapshotName || kindLabel;
168​
169/**
170 * Project the wire `ServerProvider[]` into instance entries, one per
171 * configured instance. Preserves the server's ordering (which sources
172 * from `deriveProviderInstanceConfigMap` — explicit `providerInstances.*`
173 * first, synthesized defaults after) so callers that want "default first"
174 * should sort with `sortProviderInstanceEntries` below.
175 */
176export function deriveProviderInstanceEntries(
177 providers: ReadonlyArray<ServerProvider>,
178): ReadonlyArray<ProviderInstanceEntry> {
179 return providers.map((snapshot) => {
180 const instanceId = snapshot.instanceId;
181 const driverKind = snapshot.driver;
182 const defaultId = defaultInstanceIdForDriver(driverKind);
183 const isDefault = instanceId === defaultId;
184 const displayName = resolveInstanceDisplayName(snapshot, instanceId, driverKind, isDefault);
185 return {
186 instanceId,
187 driverKind,
188 displayName,
189 accentColor: normalizeProviderAccentColor(snapshot.accentColor),
190 continuationGroupKey: snapshot.continuation?.groupKey,
191 enabled: snapshot.enabled,
192 installed: snapshot.installed,
193 status: snapshot.status,
194 isDefault,
195 isAvailable: snapshot.availability !== "unavailable",
196 snapshot,
197 models: snapshot.models,
198 } satisfies ProviderInstanceEntry;
199 });
201​
202/**
203 * Overlay the current settings configuration onto streamed provider snapshots.
204 * Provider probes can briefly retain their previous `enabled` value after a
205 * settings write, so picker visibility must follow settings rather than waiting
206 * for probe reconciliation.
207 *
208 * Non-default instances only exist through `providerInstances`; if one is
209 * absent there, its streamed snapshot is stale (for example immediately after
210 * deletion) and is treated as disabled.
211 */
212export function applyProviderInstanceSettings(
213 entries: ReadonlyArray<ProviderInstanceEntry>,
214 settings: Pick<ServerSettings, "providerInstances" | "providers">,
215): ReadonlyArray<ProviderInstanceEntry> {
216 const legacyProviders = settings.providers as Readonly<
217 Record<string, { readonly enabled?: boolean } | undefined>
218 >;
219​
220 return entries.map((entry) => {
221 const explicitInstance = settings.providerInstances?.[entry.instanceId];
222 const enabled = explicitInstance
223 ? (explicitInstance.enabled ?? true)
224 : entry.isDefault
225 ? (legacyProviders[entry.driverKind]?.enabled ?? entry.enabled)
226 : false;
227 return enabled === entry.enabled ? entry : { ...entry, enabled };
228 });
230​
231/**
232 * Sort instance entries so the default instance of each driver kind appears
233 * before any custom instances of the same kind. Within a kind, custom
234 * instances keep their settings-author order (which is how the server
235 * emits them). Stable across kinds: entries retain the server's
236 * cross-driver ordering.
237 */
238export function sortProviderInstanceEntries(
239 entries: ReadonlyArray<ProviderInstanceEntry>,
240): ReadonlyArray<ProviderInstanceEntry> {
241 // Group by driver kind preserving first-appearance order, then emit
242 // default-first within each kind. Using a Map keeps the "first-seen"
243 // semantics for kinds whose default instance is absent (unusual but
244 // possible during the migration).
245 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
246 for (const entry of entries) {
247 const bucket = byKind.get(entry.driverKind);
248 if (bucket) {
249 bucket.push(entry);
250 } else {
251 byKind.set(entry.driverKind, [entry]);
252 }
253 }
254 const sorted: ProviderInstanceEntry[] = [];
255 for (const bucket of byKind.values()) {
256 const defaults = bucket.filter((entry) => entry.isDefault);
257 const customs = bucket.filter((entry) => !entry.isDefault);
258 sorted.push(...defaults, ...customs);
259 }
260 return sorted;
262​
263/**
264 * Look up a single instance entry by exact `instanceId`. Missing snapshots
265 * are not inferred from driver kind in UI routing code.
266 */
267export function getProviderInstanceEntry(
268 providers: ReadonlyArray<ServerProvider>,
269 instanceId: ProviderInstanceId,
270): ProviderInstanceEntry | undefined {
271 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
273​
274/**
275 * Model list for a specific instance. Returns `[]` when the instance isn't
276 * present so callers don't have to thread optionality through render code.
277 */
278export function getProviderInstanceModels(
279 providers: ReadonlyArray<ServerProvider>,
280 instanceId: ProviderInstanceId,
281): ReadonlyArray<ServerProviderModel> {
282 return getProviderInstanceEntry(providers, instanceId)?.models ?? [];
284​
285/**
286 * Default model slug for a specific instance: its declared built-in default,
287 * then its first built-in model, then any model it reports, then the driver-level default. Custom
288 * instances can serve a different model list than the default instance of
289 * the same driver kind, so the lookup must be instance-scoped rather than
290 * kind-scoped.
291 */
292export function getDefaultProviderInstanceModel(
293 providers: ReadonlyArray<ServerProvider>,
294 instanceId: ProviderInstanceId,
295): string | undefined {
296 const entry = getProviderInstanceEntry(providers, instanceId);
297 if (!entry) return undefined;
298 return (
299 entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ??
300 entry.models.find((model) => !model.isCustom)?.slug ??
301 entry.models[0]?.slug ??
302 DEFAULT_MODEL_BY_PROVIDER[entry.driverKind]
303 );
305​
306const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean =>
307 entry.enabled && entry.isAvailable;
308​
309/**
310 * Resolve an exact stored instance when it remains enabled and available.
311 * Otherwise choose a deterministic fallback that can plausibly start now:
312 * ready first, then a non-error probe result. An errored provider is retained
313 * only when it was explicitly requested; it is never invented as a new-user
314 * default.
315 */
316export function resolveSelectableProviderInstanceEntry(
317 entries: ReadonlyArray<ProviderInstanceEntry>,
318 instanceId: ProviderInstanceId | undefined,
319): ProviderInstanceEntry | undefined {
320 if (instanceId !== undefined) {
321 const requested = entries.find((entry) => entry.instanceId === instanceId);
322 if (requested && isSelectableProviderInstanceEntry(requested)) {
323 return requested;
324 }
325 }
326 return (
327 entries.find(isProviderInstancePickerReady) ??
328 entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error")
329 );
331​
332/**
333 * Resolve the routing key for a selection that may reference an instance
334 * id that no longer exists (e.g. a persisted thread selection after the
335 * user deleted the custom instance). Returns a ready or non-error fallback,
336 * or `undefined` when no provider can safely become a new selection.
337 */
338export function resolveSelectableProviderInstance(
339 providers: ReadonlyArray<ServerProvider>,
340 instanceId: ProviderInstanceId | undefined,
341): ProviderInstanceId | undefined {
342 const entries = deriveProviderInstanceEntries(providers);
343 return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId;
345​
346/**
347 * Resolve the model selection persisted for a project or new thread. A valid
348 * stored selection is preserved byte-for-byte. Falling back to another
349 * instance also resets the model to that instance's own default, avoiding
350 * cross-provider instance/model pairs.
351 */
352export function resolveDefaultProviderModelSelection(
353 providers: ReadonlyArray<ServerProvider>,
354 selection: ModelSelection | null | undefined,
355): ModelSelection | null {
356 const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId);
357 if (instanceId === undefined) return null;
358 if (selection?.instanceId === instanceId) return selection;
359 const model = getDefaultProviderInstanceModel(providers, instanceId);
360 return model ? { instanceId, model } : null;
362​
363/**
364 * Resolve an open model-selection routing key back to a driver kind.
365 * Custom instance ids such as `claude_openrouter` are not themselves
366 * driver-kind slugs, but the composer still needs the owning driver kind
367 * for capabilities, options, icons, and turn dispatch metadata.
368 */
369export function resolveProviderDriverKindForInstanceSelection(
370 entries: ReadonlyArray<ProviderInstanceEntry>,
371 providers: ReadonlyArray<ServerProvider>,
372 selection: ProviderInstanceId | ProviderDriverKind | null | undefined,
373): ProviderDriverKind | undefined {
374 const matchedEntry = entries.find((entry) => entry.instanceId === selection);
375 if (matchedEntry) {
376 return matchedEntry.driverKind;
377 }
378 return undefined;