Open History to see the last commit
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>;
52}
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 return instanceId
70 .replace(/[_-]+/g, " ")
71 .replace(/([a-z])([A-Z])/g, "$1 $2")
72 .split(" ")
73 .filter((token) => token.length > 0)
74 .map((token) => token.charAt(0).toUpperCase() + token.slice(1))
75 .join(" ");
76}
77
78function driverKindLabel(driverKind: ProviderDriverKind): string {
79 return PROVIDER_DISPLAY_NAMES[driverKind] ?? formatProviderDriverKindLabel(driverKind);
80}
81
82export function normalizeProviderAccentColor(value: string | undefined): string | undefined {
83 const trimmed = value?.trim();
84 if (!trimmed) return undefined;
85 return /^#[0-9a-fA-F]{6}$/u.test(trimmed) ? trimmed : undefined;
86}
87
88/**
89 * Resolve an entry's displayName with a tiered priority:
90 *
91 * 1. A snapshot `displayName` that differs from the driver-kind label —
92 * the server has explicitly named this instance, trust it.
93 * 2. For non-default instances, a humanized `instanceId` — the server
94 * fell back to the driver-level presentation constant (which is the
95 * same for every instance of that kind), so we differentiate at the
96 * UI layer by slug. This is what keeps "Codex" + "Codex Personal"
97 * distinguishable in tooltips and list labels today.
98 * 3. The snapshot's `displayName` (if any) — default instance, trust
99 * whatever label the driver stamped.
100 * 4. `driverKindLabel(driverKind)` — nothing else on hand, so use the
101 * canonical brand label from contracts (falling back to a generic
102 * title-case of the kind slug).
103 */
104function resolveInstanceDisplayName(
105 snapshot: ServerProvider,
106 instanceId: ProviderInstanceId,
107 driverKind: ProviderDriverKind,
108 isDefault: boolean,
109): string {
110 const trimmedSnapshotName = snapshot.displayName?.trim();
111 const kindLabel = driverKindLabel(driverKind);
112 if (trimmedSnapshotName && trimmedSnapshotName !== kindLabel) {
113 return trimmedSnapshotName;
114 }
115 if (!isDefault) {
116 const humanized = humanizeInstanceId(instanceId);
117 if (humanized.length > 0) return humanized;
118 }
119 return trimmedSnapshotName || kindLabel;
120}
121
122/**
123 * Project the wire `ServerProvider[]` into instance entries, one per
124 * configured instance. Preserves the server's ordering (which sources
125 * from `deriveProviderInstanceConfigMap` — explicit `providerInstances.*`
126 * first, synthesized defaults after) so callers that want "default first"
127 * should sort with `sortProviderInstanceEntries` below.
128 */
129export function deriveProviderInstanceEntries(
130 providers: ReadonlyArray<ServerProvider>,
131): ReadonlyArray<ProviderInstanceEntry> {
132 return providers.map((snapshot) => {
133 const instanceId = snapshot.instanceId;
134 const driverKind = snapshot.driver;
135 const defaultId = defaultInstanceIdForDriver(driverKind);
136 const isDefault = instanceId === defaultId;
137 const displayName = resolveInstanceDisplayName(snapshot, instanceId, driverKind, isDefault);
138 return {
139 instanceId,
140 driverKind,
141 displayName,
142 accentColor: normalizeProviderAccentColor(snapshot.accentColor),
143 continuationGroupKey: snapshot.continuation?.groupKey,
144 enabled: snapshot.enabled,
145 installed: snapshot.installed,
146 status: snapshot.status,
147 isDefault,
148 isAvailable: snapshot.availability !== "unavailable",
149 snapshot,
150 models: snapshot.models,
151 } satisfies ProviderInstanceEntry;
152 });
153}
154
155/**
156 * Sort instance entries so the default instance of each driver kind appears
157 * before any custom instances of the same kind. Within a kind, custom
158 * instances keep their settings-author order (which is how the server
159 * emits them). Stable across kinds: entries retain the server's
160 * cross-driver ordering.
161 */
162export function sortProviderInstanceEntries(
163 entries: ReadonlyArray<ProviderInstanceEntry>,
164): ReadonlyArray<ProviderInstanceEntry> {
165 // Group by driver kind preserving first-appearance order, then emit
166 // default-first within each kind. Using a Map keeps the "first-seen"
167 // semantics for kinds whose default instance is absent (unusual but
168 // possible during the migration).
169 const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
170 for (const entry of entries) {
171 const bucket = byKind.get(entry.driverKind);
172 if (bucket) {
173 bucket.push(entry);
174 } else {
175 byKind.set(entry.driverKind, [entry]);
176 }
177 }
178 const sorted: ProviderInstanceEntry[] = [];
179 for (const bucket of byKind.values()) {
180 const defaults = bucket.filter((entry) => entry.isDefault);
181 const customs = bucket.filter((entry) => !entry.isDefault);
182 sorted.push(...defaults, ...customs);
183 }
184 return sorted;
185}
186
187/**
188 * Look up a single instance entry by exact `instanceId`. Missing snapshots
189 * are not inferred from driver kind in UI routing code.
190 */
191export function getProviderInstanceEntry(
192 providers: ReadonlyArray<ServerProvider>,
193 instanceId: ProviderInstanceId,
194): ProviderInstanceEntry | undefined {
195 return deriveProviderInstanceEntries(providers).find((entry) => entry.instanceId === instanceId);
196}
197
198/**
199 * Model list for a specific instance. Returns `[]` when the instance isn't
200 * present so callers don't have to thread optionality through render code.
201 */
202export function getProviderInstanceModels(
203 providers: ReadonlyArray<ServerProvider>,
204 instanceId: ProviderInstanceId,
205): ReadonlyArray<ServerProviderModel> {
206 return getProviderInstanceEntry(providers, instanceId)?.models ?? [];
207}
208
209/**
210 * Resolve the routing key for a selection that may reference an instance
211 * id that no longer exists (e.g. a persisted thread selection after the
212 * user deleted the custom instance). Returns the first enabled instance
213 * as a fallback so downstream code can still send a turn.
214 */
215export function resolveSelectableProviderInstance(
216 providers: ReadonlyArray<ServerProvider>,
217 instanceId: ProviderInstanceId | undefined,
218): ProviderInstanceId | undefined {
219 if (instanceId === undefined) {
220 return deriveProviderInstanceEntries(providers).find(
221 (entry) => entry.enabled && entry.isAvailable,
222 )?.instanceId;
223 }
224 const entries = deriveProviderInstanceEntries(providers);
225 const requested = entries.find((entry) => entry.instanceId === instanceId);
226 if (requested && requested.enabled && requested.isAvailable) {
227 return instanceId;
228 }
229 return entries.find((entry) => entry.enabled && entry.isAvailable)?.instanceId;
230}
231
232/**
233 * Resolve an open model-selection routing key back to a driver kind.
234 * Custom instance ids such as `claude_openrouter` are not themselves
235 * driver-kind slugs, but the composer still needs the owning driver kind
236 * for capabilities, options, icons, and turn dispatch metadata.
237 */
238export function resolveProviderDriverKindForInstanceSelection(
239 entries: ReadonlyArray<ProviderInstanceEntry>,
240 providers: ReadonlyArray<ServerProvider>,
241 selection: ProviderInstanceId | ProviderDriverKind | null | undefined,
242): ProviderDriverKind | undefined {
243 const matchedEntry = entries.find((entry) => entry.instanceId === selection);
244 if (matchedEntry) {
245 return matchedEntry.driverKind;
246 }
247 return undefined;
248}