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

providerInstances.ts

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