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

providerInstances.ts

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