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

providerInstances.ts

250 lines9.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 defaultInstanceIdForDriver,
17 PROVIDER_DISPLAY_NAMES,
18 type ProviderDriverKind,
19 type ProviderInstanceId,
20 type ServerProvider,
21 type ServerProviderModel,
22 type ServerProviderState,
23} from "@t3tools/contracts";
24​
25import { formatProviderDriverKindLabel } from "./providerModels";
26​
27/**
28 * UI-facing projection of one configured provider instance. Carries the
29 * snapshot verbatim for callers that need server-side fields we don't
30 * hoist here, plus the precomputed `instanceId` / `driverKind` /
31 * `displayName` used by every picker and settings view.
32 */
33export interface ProviderInstanceEntry {
34 readonly instanceId: ProviderInstanceId;
35 readonly driverKind: ProviderDriverKind;
36 readonly displayName: string;
37 readonly accentColor?: string | undefined;
38 readonly continuationGroupKey?: string | undefined;
39 readonly enabled: boolean;
40 readonly installed: boolean;
41 readonly status: ServerProviderState;
42 /**
43 * True when this entry is the default instance for its driver kind —
44 * i.e. its instance id equals `defaultInstanceIdForDriver(driverKind)`.
45 * The settings panel and picker sort defaults before customs.
46 */
47 readonly isDefault: boolean;
48 /** True when `availability === "unavailable"` is absent or "available". */
49 readonly isAvailable: boolean;
50 readonly snapshot: ServerProvider;
51 readonly models: ReadonlyArray<ServerProviderModel>;
53​
54/**
55 * Turn an instance id slug into a human-readable label. Splits on `_` / `-`
56 * and camelCase boundaries and title-cases each token, so `codex_personal`
57 * becomes "Codex Personal" and `myCustomInstance` becomes "My Custom
58 * Instance".
59 *
60 * This is a fallback used only when the wire snapshot's `displayName`
61 * doesn't disambiguate a non-default instance from the default one of the
62 * same driver (today every built-in driver hard-codes a single presentation
63 * label per kind, so two instances of the same kind arrive with identical
64 * display names). When a server/driver later plumbs the user's configured
65 * `ProviderInstanceConfig.displayName` through to the snapshot, that value
66 * will take precedence over this fallback.
67 */
68function humanizeInstanceId(instanceId: ProviderInstanceId): string {
69 const words: string[] = [];
70 for (const token of instanceId
71 .replace(/[_-]+/g, " ")
72 .replace(/([a-z])([A-Z])/g, "$1 $2")
73 .split(" ")) {
74 if (token.length === 0) continue;
75 words.push(token.charAt(0).toUpperCase() + token.slice(1));
76 }
77 return words.join(" ");
79​
80function driverKindLabel(driverKind: ProviderDriverKind): string {
81 return PROVIDER_DISPLAY_NAMES[driverKind] ?? formatProviderDriverKindLabel(driverKind);
83​
84export function normalizeProviderAccentColor(value: string | undefined): string | undefined {
85 const trimmed = value?.trim();
86 if (!trimmed) return undefined;
87 return /^#[0-9a-fA-F]{6}$/u.test(trimmed) ? trimmed : undefined;
89​
90/**
91 * Resolve an entry's displayName with a tiered priority:
92 *
93 * 1. A snapshot `displayName` that differs from the driver-kind label —
94 * the server has explicitly named this instance, trust it.
95 * 2. For non-default instances, a humanized `instanceId` — the server
96 * fell back to the driver-level presentation constant (which is the
97 * same for every instance of that kind), so we differentiate at the
98 * UI layer by slug. This is what keeps "Codex" + "Codex Personal"
99 * distinguishable in tooltips and list labels today.
100 * 3. The snapshot's `displayName` (if any) — default instance, trust
101 * whatever label the driver stamped.
102 * 4. `driverKindLabel(driverKind)` — nothing else on hand, so use the
103 * canonical brand label from contracts (falling back to a generic
104 * title-case of the kind slug).
105 */
106function resolveInstanceDisplayName(
107 snapshot: ServerProvider,
108 instanceId: ProviderInstanceId,
109 driverKind: ProviderDriverKind,
110 isDefault: boolean,
111): string {
112 const trimmedSnapshotName = snapshot.displayName?.trim();
113 const kindLabel = driverKindLabel(driverKind);
114 if (trimmedSnapshotName && trimmedSnapshotName !== kindLabel) {
115 return trimmedSnapshotName;
116 }
117 if (!isDefault) {
118 const humanized = humanizeInstanceId(instanceId);
119 if (humanized.length > 0) return humanized;
120 }
121 return trimmedSnapshotName || kindLabel;
123​
124/**
125 * Project the wire `ServerProvider[]` into instance entries, one per
126 * configured instance. Preserves the server's ordering (which sources
127 * from `deriveProviderInstanceConfigMap` — explicit `providerInstances.*`
128 * first, synthesized defaults after) so callers that want "default first"
129 * should sort with `sortProviderInstanceEntries` below.
130 */
131export function deriveProviderInstanceEntries(
132 providers: ReadonlyArray<ServerProvider>,
133): ReadonlyArray<ProviderInstanceEntry> {
134 return providers.map((snapshot) => {
135 const instanceId = snapshot.instanceId;
136 const driverKind = snapshot.driver;
137 const defaultId = defaultInstanceIdForDriver(driverKind);
138 const isDefault = instanceId === defaultId;
139 const displayName = resolveInstanceDisplayName(snapshot, instanceId, driverKind, isDefault);
140 return {
141 instanceId,
142 driverKind,
143 displayName,
144 accentColor: normalizeProviderAccentColor(snapshot.accentColor),
145 continuationGroupKey: snapshot.continuation?.groupKey,
146 enabled: snapshot.enabled,
147 installed: snapshot.installed,
148 status: snapshot.status,
149 isDefault,
150 isAvailable: snapshot.availability !== "unavailable",
151 snapshot,
152 models: snapshot.models,
153 } satisfies ProviderInstanceEntry;
154 });
156​
157/**
158 * Sort instance entries so the default instance of each driver kind appears
159 * before any custom instances of the same kind. Within a kind, custom
160 * instances keep their settings-author order (which is how the server
161 * emits them). Stable across kinds: entries retain the server's
162 * cross-driver ordering.
163 */
164export function sortProviderInstanceEntries(
165 entries: ReadonlyArray<ProviderInstanceEntry>,
166): ReadonlyArray<ProviderInstanceEntry> {
167 // Group by driver kind preserving first-appearance order, then emit
168 // default-first within each kind. Using a Map keeps the "first-seen"
169 // semantics for kinds whose default instance is absent (unusual but
170 // possible during the migration).
171 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
172 for (const entry of entries) {
173 const bucket = byKind.get(entry.driverKind);
174 if (bucket) {
175 bucket.push(entry);
176 } else {
177 byKind.set(entry.driverKind, [entry]);
178 }
179 }
180 const sorted: ProviderInstanceEntry[] = [];
181 for (const bucket of byKind.values()) {
182 const defaults = bucket.filter((entry) => entry.isDefault);
183 const customs = bucket.filter((entry) => !entry.isDefault);
184 sorted.push(...defaults, ...customs);
185 }
186 return sorted;
188​
189/**
190 * Look up a single instance entry by exact `instanceId`. Missing snapshots
191 * are not inferred from driver kind in UI routing code.
192 */
193export function getProviderInstanceEntry(
194 providers: ReadonlyArray<ServerProvider>,
195 instanceId: ProviderInstanceId,
196): ProviderInstanceEntry | undefined {
197 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
199​
200/**
201 * Model list for a specific instance. Returns `[]` when the instance isn't
202 * present so callers don't have to thread optionality through render code.
203 */
204export function getProviderInstanceModels(
205 providers: ReadonlyArray<ServerProvider>,
206 instanceId: ProviderInstanceId,
207): ReadonlyArray<ServerProviderModel> {
208 return getProviderInstanceEntry(providers, instanceId)?.models ?? [];
210​
211/**
212 * Resolve the routing key for a selection that may reference an instance
213 * id that no longer exists (e.g. a persisted thread selection after the
214 * user deleted the custom instance). Returns the first enabled instance
215 * as a fallback so downstream code can still send a turn.
216 */
217export function resolveSelectableProviderInstance(
218 providers: ReadonlyArray<ServerProvider>,
219 instanceId: ProviderInstanceId | undefined,
220): ProviderInstanceId | undefined {
221 if (instanceId === undefined) {
222 return deriveProviderInstanceEntries(providers).find(
223 (entry) => entry.enabled && entry.isAvailable,
224 )?.instanceId;
225 }
226 const entries = deriveProviderInstanceEntries(providers);
227 const requested = entries.find((entry) => entry.instanceId === instanceId);
228 if (requested && requested.enabled && requested.isAvailable) {
229 return instanceId;
230 }
231 return entries.find((entry) => entry.enabled && entry.isAvailable)?.instanceId;
233​
234/**
235 * Resolve an open model-selection routing key back to a driver kind.
236 * Custom instance ids such as `claude_openrouter` are not themselves
237 * driver-kind slugs, but the composer still needs the owning driver kind
238 * for capabilities, options, icons, and turn dispatch metadata.
239 */
240export function resolveProviderDriverKindForInstanceSelection(
241 entries: ReadonlyArray<ProviderInstanceEntry>,
242 providers: ReadonlyArray<ServerProvider>,
243 selection: ProviderInstanceId | ProviderDriverKind | null | undefined,
244): ProviderDriverKind | undefined {
245 const matchedEntry = entries.find((entry) => entry.instanceId === selection);
246 if (matchedEntry) {
247 return matchedEntry.driverKind;
248 }
249 return undefined;