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

ProviderInstanceCard.tsx

935 lines35.7 KB

1"use client";
2​
3import {
4 ArrowUpCircleIcon,
5 CopyIcon,
6 DownloadIcon,
7 LoaderIcon,
8 LockIcon,
9 LockOpenIcon,
10 PlusIcon,
11 Trash2Icon,
12 XIcon,
13} from "lucide-react";
14import * as Arr from "effect/Array";
15import * as Result from "effect/Result";
16import { useEffect, useRef, useState, type ReactNode } from "react";
17import {
18 isProviderDriverKind,
19 resolveProviderInstanceEnabled,
20 type ProviderInstanceConfig,
21 type ProviderInstanceEnvironmentVariable,
22 type ProviderInstanceId,
23 type ProviderDriverKind,
24 type ServerProvider,
25 type ServerProviderModel,
26} from "@t3tools/contracts";
27​
28import { cn } from "../../lib/utils";
29import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
30import { normalizeProviderAccentColor } from "../../providerInstances";
31import { Badge } from "../ui/badge";
32import { Button } from "../ui/button";
33import { DraftInput } from "../ui/draft-input";
34import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
35import { ScrollArea } from "../ui/scroll-area";
36import { Switch } from "../ui/switch";
37import { stackedThreadToast, toastManager } from "../ui/toast";
38import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
39import type { DriverOption } from "./providerDriverMeta";
40import { providerSettingsTabClassName } from "./providerSettingsTabs";
41import { ProviderSettingsForm } from "./ProviderSettingsForm";
42import { ProviderModelsSection } from "./ProviderModelsSection";
43import { ProviderInstanceIcon, providerInstanceInitials } from "../chat/ProviderInstanceIcon";
44import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
45import { RedactedSensitiveText } from "./RedactedSensitiveText";
46import {
47 getProviderVersionAdvisoryPresentation,
48 PROVIDER_STATUS_STYLES,
49 getProviderSummary,
50 getProviderVersionLabel,
51 type ProviderStatusKey,
52} from "./providerStatus";
53​
54const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
55​
56/** Label-left field grid for the Configuration tab: one row per field. */
57const PROVIDER_FIELD_GRID_CLASS_NAME =
58 "grid gap-x-4 gap-y-2.5 sm:grid-cols-[8rem_minmax(0,1fr)] sm:items-start";
59/** Full-width divider row that names the group of fields below it. */
60const PROVIDER_FIELD_GROUP_LABEL_CLASS_NAME =
61 "col-span-full mt-1 border-t border-border/60 pt-2.5 text-[11px] text-muted-foreground";
62​
63let environmentVariableDraftId = 0;
64const nextEnvironmentVariableDraftId = () => `provider-env-${environmentVariableDraftId++}`;
65​
66type EnvironmentDraftRow = {
67 readonly id: string;
68 readonly name: string;
69 readonly value: string;
70 readonly sensitive: boolean;
71 readonly valueRedacted?: boolean;
72};
73​
74function makeEnvironmentDraftRow(
75 variable: ProviderInstanceEnvironmentVariable,
76 index: number,
77): EnvironmentDraftRow {
78 return {
79 id: `${index}:${variable.name}`,
80 name: variable.name,
81 value: variable.value,
82 sensitive: variable.sensitive,
83 ...(variable.valueRedacted !== undefined ? { valueRedacted: variable.valueRedacted } : {}),
84 };
86​
87function providerEnvironmentsEqual(
88 left: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
89 right: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
90): boolean {
91 return (
92 left.length === right.length &&
93 left.every((variable, index) => {
94 const other = right[index];
95 return (
96 other !== undefined &&
97 variable.name === other.name &&
98 variable.value === other.value &&
99 variable.sensitive === other.sensitive &&
100 variable.valueRedacted === other.valueRedacted
101 );
102 })
103 );
105​
106/**
107 * Read a string[] at `key` from the opaque config blob, filtering out
108 * non-string entries. Used for `customModels`, which is always typed as
109 * `string[]` by the concrete driver schemas but arrives here as
110 * `Schema.Unknown`.
111 */
112function readConfigStringArray(config: unknown, key: string): ReadonlyArray<string> {
113 if (config === null || typeof config !== "object") return [];
114 const value = (config as Record<string, unknown>)[key];
115 if (!Array.isArray(value)) return [];
116 return value.filter((entry): entry is string => typeof entry === "string");
118​
119/**
120 * Set `key` to an arbitrary value on the opaque config blob. Unlike
121 * provider settings field updates, does not drop empty-looking values — the
122 * caller is responsible for deciding whether an empty array / empty
123 * object should be stored explicitly (e.g. `customModels: []` is a
124 * meaningful "user cleared their custom list" state distinct from
125 * "driver default").
126 */
127function nextConfigBlobWithValue(
128 config: unknown,
129 key: string,
130 value: unknown,
131): Record<string, unknown> {
132 const base: Record<string, unknown> =
133 config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
134 base[key] = value;
135 return base;
137​
138export function deriveProviderModelsForDisplay(input: {
139 readonly liveModels: ReadonlyArray<ServerProviderModel> | undefined;
140 readonly customModels: ReadonlyArray<string>;
141}): ReadonlyArray<ServerProviderModel> {
142 const liveCustomModelsBySlug = new Map(
143 Arr.filterMap(input.liveModels ?? [], (model) =>
144 model.isCustom ? Result.succeed([model.slug, model] as const) : Result.failVoid,
145 ),
146 );
147 const serverModels = input.liveModels?.filter((model) => !model.isCustom) ?? [];
148 const customModels = input.customModels.map(
149 (slug) =>
150 liveCustomModelsBySlug.get(slug) ?? {
151 slug,
152 name: slug,
153 isCustom: true,
154 capabilities: null,
155 },
156 );
157 return [...serverModels, ...customModels];
159​
160function ProviderAuthEmail(props: { readonly email: string | undefined }) {
161 const email = props.email?.trim();
162 if (!email) return null;
163​
164 return (
165 <RedactedSensitiveText
166 value={email}
167 ariaLabel="Toggle account email visibility"
168 revealTooltip="Click to reveal email"
169 hideTooltip="Click to hide email"
170 className="max-w-full truncate"
171 />
172 );
174​
175function ProviderEnvironmentSection(props: {
176 readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
177 readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;
178}) {
179 const [rows, setRows] = useState<ReadonlyArray<EnvironmentDraftRow>>(() =>
180 props.environment.map(makeEnvironmentDraftRow),
181 );
182 const previousEnvironmentRef = useRef(props.environment);
183 const lastPublishedEnvironmentRef = useRef<
184 ReadonlyArray<ProviderInstanceEnvironmentVariable> | undefined
185 >(undefined);
186​
187 useEffect(() => {
188 const previousEnvironment = previousEnvironmentRef.current;
189 const lastPublishedEnvironment = lastPublishedEnvironmentRef.current;
190 previousEnvironmentRef.current = props.environment;
191 lastPublishedEnvironmentRef.current = undefined;
192 if (
193 previousEnvironment === props.environment ||
194 providerEnvironmentsEqual(previousEnvironment, props.environment) ||
195 (lastPublishedEnvironment !== undefined &&
196 providerEnvironmentsEqual(lastPublishedEnvironment, props.environment))
197 ) {
198 return;
199 }
200 setRows(props.environment.map(makeEnvironmentDraftRow));
201 }, [props.environment]);
202​
203 const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {
204 const published: ProviderInstanceEnvironmentVariable[] = [];
205 for (const row of nextRows) {
206 const name = row.name.trim();
207 if (!ENVIRONMENT_VARIABLE_NAME_PATTERN.test(name)) {
208 if (
209 name.length > 0 ||
210 row.value.length > 0 ||
211 row.sensitive !== true ||
212 row.valueRedacted !== undefined
213 ) {
214 return;
215 }
216 continue;
217 }
218 const { id: _id, ...rest } = row;
219 published.push({ ...rest, name });
220 }
221 lastPublishedEnvironmentRef.current = published;
222 props.onChange(published);
223 };
224​
225 const updateVariable = (id: string, patch: Partial<Omit<EnvironmentDraftRow, "id">>) => {
226 const nextRows = rows.map((row) =>
227 row.id === id
228 ? {
229 ...row,
230 ...patch,
231 ...(patch.value !== undefined ? { valueRedacted: false } : {}),
232 }
233 : row,
234 );
235 setRows(nextRows);
236 publishRows(nextRows);
237 };
238​
239 const removeVariable = (id: string) => {
240 const nextRows = rows.filter((row) => row.id !== id);
241 setRows(nextRows);
242 publishRows(nextRows);
243 };
244​
245 const addVariable = () =>
246 setRows([
247 ...rows,
248 {
249 id: nextEnvironmentVariableDraftId(),
250 name: "",
251 value: "",
252 sensitive: true,
253 },
254 ]);
255​
256 return (
257 <div className="min-w-0 space-y-1.5">
258 {rows.map((variable, index) => (
259 <div key={variable.id} className="flex min-w-0 items-center gap-1.5">
260 <DraftInput
261 size="sm"
262 className="w-44 shrink-0 font-mono"
263 value={variable.name}
264 onCommit={(name) => updateVariable(variable.id, { name: name.trim() })}
265 placeholder="VARIABLE_NAME"
266 spellCheck={false}
267 aria-label={`Environment variable name ${index + 1}`}
268 />
269 <span className="text-xs text-muted-foreground" aria-hidden>
270 =
271 </span>
272 <DraftInput
273 size="sm"
274 className="min-w-0 flex-1 font-mono"
275 value={variable.valueRedacted ? "" : variable.value}
276 onCommit={(value) => updateVariable(variable.id, { value })}
277 type={variable.sensitive ? "password" : undefined}
278 autoComplete="off"
279 placeholder={
280 variable.valueRedacted ? "Stored secret, enter a new value to replace" : "value"
281 }
282 spellCheck={false}
283 aria-label={`Environment variable value ${index + 1}`}
284 />
285 <Tooltip>
286 <TooltipTrigger
287 render={
288 <Button
289 type="button"
290 size="icon-micro"
291 variant="ghost-muted"
292 className={cn(
293 "[--control-icon-color:currentColor]",
294 variable.sensitive && "text-foreground",
295 )}
296 onClick={() => {
297 const sensitive = !variable.sensitive;
298 updateVariable(variable.id, {
299 sensitive,
300 ...(sensitive && variable.valueRedacted === undefined
301 ? {}
302 : { valueRedacted: sensitive ? variable.valueRedacted : false }),
303 });
304 }}
305 aria-pressed={variable.sensitive}
306 aria-label={`Mark environment variable ${variable.name || index + 1} as sensitive`}
307 >
308 {variable.sensitive ? (
309 <LockIcon className="size-3" />
310 ) : (
311 <LockOpenIcon className="size-3" />
312 )}
313 </Button>
314 }
315 />
316 <TooltipPopup side="top">
317 {variable.sensitive ? "Sensitive, stored separately" : "Plain text"}
318 </TooltipPopup>
319 </Tooltip>
320 <Button
321 type="button"
322 size="icon-micro"
323 variant="ghost-muted"
324 className="[--control-icon-color:currentColor] hover:text-destructive"
325 onClick={() => removeVariable(variable.id)}
326 aria-label={`Remove environment variable ${variable.name || index + 1}`}
327 >
328 <XIcon className="size-3" />
329 </Button>
330 </div>
331 ))}
332 <div className="flex min-h-[1.875rem] flex-wrap items-center gap-x-3 gap-y-1">
333 <Button type="button" size="xs" variant="ghost-muted" onClick={addVariable}>
334 <PlusIcon className="size-3" />
335 Add variable
336 </Button>
337 <span className="text-xs text-muted-foreground">
338 {rows.length === 0
339 ? "API keys, base URLs, or other per-instance CLI settings."
340 : "Sensitive values are stored separately and never returned to the app."}
341 </span>
342 </div>
343 </div>
344 );
346​
347interface ProviderInstanceCardProps {
348 readonly instanceId: ProviderInstanceId;
349 readonly instance: ProviderInstanceConfig;
350 readonly driverOption: DriverOption | undefined;
351 readonly liveProvider: ServerProvider | undefined;
352 readonly mode: "list" | "editor";
353 readonly selected?: boolean | undefined;
354 readonly onSelect?: (() => void) | undefined;
355 readonly readOnly?: boolean | undefined;
356 readonly onUpdate: (nextInstance: ProviderInstanceConfig) => void;
357 /**
358 * Pass `undefined` to hide the delete footer entirely. Built-in default
359 * instance slots use `undefined` — they can't be deleted without losing
360 * the slot, and their "reset to defaults" affordance lives on an outer
361 * reset button instead. Explicit `| undefined` in the type accommodates
362 * `exactOptionalPropertyTypes: true`, where an absent key and
363 * `{ onDelete: undefined }` are treated as distinct shapes.
364 */
365 readonly onDelete?: (() => void) | undefined;
366 /**
367 * Optional outer reset button rendered next to the driver icon. Built-in
368 * default slots supply a reset-to-factory control here; custom instances
369 * omit it.
370 */
371 readonly headerAction?: ReactNode | undefined;
372 readonly setup?: ReactNode;
373 readonly hiddenModels: ReadonlyArray<string>;
374 readonly favoriteModels: ReadonlyArray<string>;
375 readonly modelOrder: ReadonlyArray<string>;
376 readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
377 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
378 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
379 readonly onRunUpdate?: (() => void) | undefined;
380 readonly isUpdating?: boolean | undefined;
382​
383/**
384 * Renders one provider instance as either a compact selectable list row or
385 * the full editor shown beside that list. Both modes use the same enabled
386 * state and provider metadata.
387 *
388 * Behavior notes:
389 * - `liveProvider` is matched by the caller via `instanceId`; when no
390 * match is available (e.g. the server hasn't probed yet, or the
391 * driver is not shipped by the current build) the card still renders
392 * with a neutral "checking" summary.
393 * - Unknown drivers (`driverOption === undefined`) get a read-only
394 * notice instead of editable fields, so fork instances round-trip
395 * without accidentally destroying their config.
396 * - The enabled Switch writes to the envelope's `instance.enabled`
397 * field, which is the single enabled flag: the server folds any legacy
398 * driver-specific `config.enabled` into the envelope on load and both
399 * sides resolve through `resolveProviderInstanceEnabled` (an explicit
400 * false wins, then envelope, then config, then the driver default).
401 */
402export function ProviderInstanceCard({
403 instanceId,
404 instance,
405 driverOption,
406 liveProvider,
407 mode,
408 selected = false,
409 onSelect,
410 readOnly = false,
411 onUpdate,
412 onDelete,
413 headerAction,
414 setup,
415 hiddenModels,
416 favoriteModels,
417 modelOrder,
418 onHiddenModelsChange,
419 onFavoriteModelsChange,
420 onModelOrderChange,
421 onRunUpdate,
422 isUpdating = false,
423}: ProviderInstanceCardProps) {
424 const [activeTab, setActiveTab] = useState<"configuration" | "models">("configuration");
425 const enabled = resolveProviderInstanceEnabled(instance);
426 // A locally disabled provider reads "Disabled" with a muted dot even if its
427 // last server status is stale. Enabled providers use the server status.
428 const statusKey: ProviderStatusKey = enabled
429 ? ((liveProvider?.status as ProviderStatusKey | undefined) ?? "warning")
430 : "disabled";
431 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
432 const summary = enabled
433 ? getProviderSummary(liveProvider)
434 : { headline: "Disabled", detail: null };
435 const authEmail = liveProvider?.auth.email?.trim();
436 // The editor header folds the account email into the status line —
437 // "Authenticated as <email> · <plan>" — with the email redacted until its
438 // reveal toggle is clicked.
439 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
440 const authLabel =
441 enabled && liveProvider?.auth.status === "authenticated"
442 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
443 : null;
444 const versionLabel = getProviderVersionLabel(liveProvider?.version);
445 const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
446 const updateCommand = versionAdvisory?.updateCommand ?? null;
447 const FallbackIconComponent = driverOption?.icon;
448 const displayName =
449 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
450 const accentColor = normalizeProviderAccentColor(instance.accentColor);
451 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
452 onCopy: ({ providerName }) => {
453 toastManager.add({
454 type: "success",
455 title: `${providerName} update command copied`,
456 description: "Run it in a terminal when you are ready to update.",
457 });
458 },
459 onError: (error, { providerName }) => {
460 toastManager.add(
461 stackedThreadToast({
462 type: "error",
463 title: `Could not copy ${providerName} update command`,
464 description: error.message,
465 }),
466 );
467 },
468 });
469​
470 // Narrow `instance.driver` for callers that key on the closed
471 // `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
472 // fork drivers pass through as `null` and those callers fall back to
473 // verbatim behaviour.
474 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
475 ? instance.driver
476 : null;
477 const visibleTab = driverOption === undefined ? "configuration" : activeTab;
478​
479 const customModels =
480 instance.driver === "antigravity" ? [] : readConfigStringArray(instance.config, "customModels");
481 // Server-returned models may lag behind settings writes. Treat probe
482 // models as the source for built-ins only; custom rows come directly
483 // from the current instance config so add/remove reflects immediately.
484 const modelsForDisplay = deriveProviderModelsForDisplay({
485 liveModels: liveProvider?.models,
486 customModels,
487 });
488 const hiddenModelCount = modelsForDisplay.filter(
489 (model) => !model.isCustom && hiddenModels.includes(model.slug),
490 ).length;
491​
492 const updateDisplayName = (value: string) => {
493 const trimmed = value.trim();
494 const { displayName: _omit, ...rest } = instance;
495 onUpdate(
496 trimmed.length > 0
497 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
498 : (rest as ProviderInstanceConfig),
499 );
500 };
501​
502 const updateEnabled = (value: boolean) => {
503 onUpdate({ ...instance, enabled: value });
504 };
505​
506 const updateAccentColor = (value: string) => {
507 const normalized = normalizeProviderAccentColor(value);
508 const { accentColor: _omit, ...rest } = instance;
509 onUpdate(
510 normalized
511 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
512 : (rest as ProviderInstanceConfig),
513 );
514 };
515​
516 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
517 const { config: _omit, ...rest } = instance;
518 onUpdate(
519 nextConfig !== undefined
520 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
521 : (rest as ProviderInstanceConfig),
522 );
523 };
524​
525 const updateCustomModels = (next: ReadonlyArray<string>) => {
526 const nextConfig = nextConfigBlobWithValue(instance.config, "customModels", [...next]);
527 const { config: _omit, ...rest } = instance;
528 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
529 };
530​
531 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
532 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
533 const { environment: _omit, ...rest } = instance;
534 onUpdate(
535 cleaned.length > 0
536 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
537 : (rest as ProviderInstanceConfig),
538 );
539 };
540​
541 const titleIconNode = driverKind ? (
542 <ProviderInstanceIcon
543 driverKind={driverKind}
544 displayName={displayName}
545 accentColor={accentColor}
546 showBadge={Boolean(accentColor)}
547 className="size-5"
548 iconClassName="size-4 text-foreground/80"
549 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-[7px]"
550 />
551 ) : FallbackIconComponent ? (
552 <span className="inline-flex size-5 shrink-0 items-center justify-center">
553 <FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
554 </span>
555 ) : (
556 <span
557 className="inline-flex size-5 shrink-0 items-center justify-center text-[10px] font-semibold leading-none text-foreground/80"
558 aria-hidden
559 >
560 {providerInstanceInitials(displayName)}
561 </span>
562 );
563​
564 const titleHeadNode = (
565 <>
566 {titleIconNode}
567 <h3 className="truncate text-sm font-medium tracking-[-0.005em] text-foreground">
568 {displayName}
569 </h3>
570 {String(instanceId) !== String(instance.driver) ? (
571 <code className="truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
572 {instanceId}
573 </code>
574 ) : null}
575 {driverOption?.badgeLabel ? (
576 <Badge variant="warning" size="sm" className="shrink-0">
577 {driverOption.badgeLabel}
578 </Badge>
579 ) : null}
580 </>
581 );
582​
583 const titleTailNode = headerAction ? (
584 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
585 ) : null;
586​
587 const versionCodeNode = versionLabel ? (
588 <code className="text-xs text-muted-foreground">{versionLabel}</code>
589 ) : null;
590​
591 // Healthy and disabled rows read fine from their text; only trouble gets a dot.
592 const statusDotNode =
593 statusKey === "warning" || statusKey === "error" ? (
594 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
595 ) : null;
596 const statusHeadlineNode = <span>{summary.headline}</span>;
597 // Trouble states carry the server's explanation (a failed probe, a shadow
598 // home entry that is not a symlink, a missing binary). Show it wherever the
599 // headline shows so the user can act without opening the editor.
600 const needsAttention = statusKey === "warning" || statusKey === "error";
601 const statusLineClassName =
602 "flex min-w-0 flex-wrap items-center gap-x-1.5 text-[13px] leading-[1.45] text-muted-foreground/80";
603​
604 if (mode === "list") {
605 return (
606 <div
607 className={cn(
608 // Sidebar-style selection with a fixed row height so the list stays
609 // even; the status line clamps to two lines instead of growing.
610 "group flex min-h-19 items-start gap-3 rounded-md px-3 py-2 transition-colors",
611 // Foreground-alpha tint so the fill reads the same in light and dark themes.
612 selected ? "bg-foreground/8" : "hover:bg-foreground/4",
613 )}
614 >
615 <button
616 type="button"
617 className={cn(
618 "flex min-w-0 flex-1 cursor-pointer items-start gap-3 rounded-sm text-left outline-none transition-opacity focus-visible:ring-2 focus-visible:ring-ring",
619 !enabled && !selected && "opacity-60 group-hover:opacity-100",
620 )}
621 onClick={onSelect}
622 aria-pressed={selected}
623 >
624 {titleIconNode}
625 <span className="min-w-0 flex-1">
626 <span className="flex min-w-0 items-center gap-2">
627 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
628 {String(instanceId) !== String(instance.driver) ? (
629 <code className="min-w-0 truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
630 {instanceId}
631 </code>
632 ) : null}
633 {versionCodeNode}
634 {versionAdvisory ? (
635 <span role="img" aria-label="Update available" className="inline-flex shrink-0">
636 <ArrowUpCircleIcon className="size-3.5 text-muted-foreground" />
637 </span>
638 ) : null}
639 </span>
640 <span className="mt-0.5 flex items-start gap-1.5 text-[13px] leading-[1.45] text-muted-foreground/80">
641 {statusDotNode ? (
642 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
643 ) : null}
644 <span className="line-clamp-2 [overflow-wrap:anywhere]">
645 {summary.headline}
646 {needsAttention && summary.detail ? ` · ${summary.detail}` : null}
647 </span>
648 </span>
649 </span>
650 </button>
651 <span className="flex h-5 shrink-0 items-center">
652 <Switch
653 checked={enabled}
654 disabled={readOnly}
655 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
656 aria-label={`Enable ${displayName}`}
657 />
658 </span>
659 </div>
660 );
661 }
662​
663 return (
664 <div className="min-w-0 lg:flex lg:h-full lg:min-h-0 lg:flex-col">
665 <div className="flex min-h-16 shrink-0 items-start justify-between gap-3 border-b border-border/70 px-4 py-3">
666 <div className="min-w-0 flex-1 space-y-1">
667 <div className="flex min-w-0 flex-wrap items-center gap-2">
668 {titleHeadNode}
669 {versionCodeNode}
670 {/*
671 Only the write actions go inert on read-only sessions; the
672 status line below keeps its email reveal clickable.
673 */}
674 <span
675 inert={readOnly}
676 aria-disabled={readOnly || undefined}
677 className={cn("inline-flex items-center gap-2", readOnly && "opacity-50")}
678 >
679 {versionAdvisory ? (
680 <Popover>
681 <PopoverTrigger
682 render={
683 <Button
684 type="button"
685 size="icon-micro"
686 variant="ghost"
687 className={cn(
688 "[--control-icon-color:currentColor]",
689 versionAdvisory.emphasis === "strong"
690 ? "text-warning hover:text-warning"
691 : "text-muted-foreground hover:text-foreground",
692 )}
693 aria-label="Update available — view details"
694 >
695 <ArrowUpCircleIcon className="size-3.5" />
696 </Button>
697 }
698 />
699 <PopoverPopup
700 side="bottom"
701 align="start"
702 className="w-[min(21rem,calc(100vw-1.5rem))] [--popup-width:min(21rem,calc(100vw-1.5rem))]"
703 >
704 <div className="grid min-w-0 gap-3">
705 <div className="grid gap-0.5">
706 <p className="text-[13px] font-semibold leading-tight text-foreground">
707 Update available
708 </p>
709 <p
710 className={cn(
711 "text-xs leading-snug",
712 versionAdvisory.emphasis === "strong"
713 ? "text-warning"
714 : "text-muted-foreground",
715 )}
716 >
717 {versionAdvisory.detail}
718 </p>
719 </div>
720 {onRunUpdate ? (
721 <Button
722 type="button"
723 size="xs"
724 variant="outline"
725 className="w-full"
726 disabled={isUpdating}
727 onClick={onRunUpdate}
728 >
729 {isUpdating ? <LoaderIcon className="animate-spin" /> : <DownloadIcon />}
730 {isUpdating ? "Updating" : "Update now"}
731 </Button>
732 ) : null}
733 {onRunUpdate && updateCommand ? (
734 <div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
735 <span aria-hidden className="h-px flex-1 bg-border" />
736 or, update manually using
737 <span aria-hidden className="h-px flex-1 bg-border" />
738 </div>
739 ) : null}
740 {updateCommand ? (
741 <div className="flex min-w-0 items-center gap-1 rounded-md border border-border/70 bg-muted/40 py-0.5 pr-0.5 pl-2">
742 <ScrollArea scrollFade className="h-8 min-w-0 flex-1 rounded-none">
743 <code className="flex h-full w-max items-center whitespace-nowrap pr-3 font-mono text-[11px] text-foreground">
744 {updateCommand}
745 </code>
746 </ScrollArea>
747 <Tooltip>
748 <TooltipTrigger
749 render={
750 <Button
751 type="button"
752 size="icon-xs"
753 variant="ghost"
754 className="shrink-0 text-muted-foreground hover:text-foreground"
755 onClick={() =>
756 copyToClipboard(updateCommand, {
757 providerName: displayName,
758 })
759 }
760 aria-label="Copy update command"
761 >
762 <CopyIcon className="size-3" />
763 </Button>
764 }
765 />
766 <TooltipPopup side="top">Copy command</TooltipPopup>
767 </Tooltip>
768 </div>
769 ) : null}
770 </div>
771 </PopoverPopup>
772 </Popover>
773 ) : null}
774 {titleTailNode}
775 </span>
776 </div>
777 <p className={statusLineClassName}>
778 {statusDotNode}
779 {isAuthenticated && authEmail ? (
780 <>
781 <span>Authenticated as</span>
782 <ProviderAuthEmail email={authEmail} />
783 {authLabel ? <span>· {authLabel}</span> : null}
784 </>
785 ) : (
786 statusHeadlineNode
787 )}
788 {summary.detail && !needsAttention ? <span>· {summary.detail}</span> : null}
789 </p>
790 {summary.detail && needsAttention ? (
791 <p className="text-[13px] leading-[1.45] text-muted-foreground/80 [overflow-wrap:anywhere]">
792 {summary.detail}
793 </p>
794 ) : null}
795 </div>
796 {onDelete ? (
797 <span
798 inert={readOnly}
799 aria-disabled={readOnly || undefined}
800 className={cn("shrink-0", readOnly && "opacity-50")}
801 >
802 <Button
803 type="button"
804 size="xs"
805 variant="ghost"
806 className="[--control-icon-color:currentColor] text-muted-foreground hover:text-destructive"
807 onClick={onDelete}
808 aria-label={`Delete instance ${instanceId}`}
809 >
810 <Trash2Icon className="size-3" />
811 Delete instance
812 </Button>
813 </span>
814 ) : null}
815 </div>
816​
817 <div className="flex h-11 shrink-0 border-b border-border/70 px-1">
818 <button
819 type="button"
820 aria-pressed={visibleTab === "configuration"}
821 className={providerSettingsTabClassName(visibleTab === "configuration")}
822 onClick={() => setActiveTab("configuration")}
823 >
824 Configuration
825 </button>
826 {driverOption !== undefined ? (
827 <button
828 type="button"
829 aria-pressed={visibleTab === "models"}
830 className={cn(providerSettingsTabClassName(visibleTab === "models"), "gap-1.5")}
831 onClick={() => setActiveTab("models")}
832 >
833 Models
834 <span className="font-normal text-muted-foreground/70">
835 {modelsForDisplay.length}
836 {hiddenModelCount > 0 ? ` · ${hiddenModelCount} hidden` : ""}
837 </span>
838 </button>
839 ) : null}
840 </div>
841​
842 <div className="lg:min-h-0 lg:flex-1">
843 <ScrollArea
844 scrollFade
845 chainVerticalScroll
846 className="lg:h-full"
847 hidden={visibleTab !== "configuration"}
848 >
849 {setup ? <div className="border-b border-border/60 px-4 py-3">{setup}</div> : null}
850 <div
851 inert={readOnly}
852 aria-disabled={readOnly || undefined}
853 className={cn("px-4 py-4", readOnly && "opacity-50 select-none")}
854 >
855 <div className={PROVIDER_FIELD_GRID_CLASS_NAME}>
856 <label
857 htmlFor={`provider-instance-${instanceId}-display-name`}
858 className="pt-1.5 text-xs font-medium text-foreground"
859 >
860 Display name
861 </label>
862 <div className="flex min-w-0 flex-wrap items-center gap-3">
863 <DraftInput
864 id={`provider-instance-${instanceId}-display-name`}
865 size="sm"
866 className="w-44"
867 value={instance.displayName ?? ""}
868 onCommit={updateDisplayName}
869 placeholder={driverOption?.label ?? "Instance label"}
870 spellCheck={false}
871 />
872 <ProviderAccentColorPicker
873 layout="inline"
874 displayName={displayName}
875 value={accentColor}
876 onCommit={updateAccentColor}
877 commitDelayMs={120}
878 />
879 </div>
880 <div className={PROVIDER_FIELD_GROUP_LABEL_CLASS_NAME}>Runtime</div>
881 {driverOption ? (
882 <ProviderSettingsForm
883 definition={driverOption}
884 value={instance.config}
885 idPrefix={`provider-instance-${instanceId}`}
886 variant="grid"
887 onChange={updateConfig}
888 />
889 ) : (
890 <>
891 <span className="pt-1.5 text-xs font-medium text-foreground">Driver</span>
892 <p className="text-xs text-muted-foreground">
893 This instance uses a driver (
894 <code className="text-foreground">{String(instance.driver)}</code>) that is not
895 shipped with the current build. Configuration values are preserved but cannot be
896 edited from this surface.
897 </p>
898 </>
899 )}
900 <div className={PROVIDER_FIELD_GROUP_LABEL_CLASS_NAME}>Environment</div>
901 <div className="col-span-full">
902 <ProviderEnvironmentSection
903 environment={instance.environment ?? []}
904 onChange={updateEnvironment}
905 />
906 </div>
907 </div>
908 </div>
909 </ScrollArea>
910 {driverOption !== undefined ? (
911 <div
912 inert={readOnly}
913 aria-disabled={readOnly || undefined}
914 className={cn("px-4 py-5 lg:h-full lg:min-h-0", readOnly && "opacity-50 select-none")}
915 hidden={visibleTab !== "models"}
916 >
917 <ProviderModelsSection
918 instanceId={instanceId}
919 driverKind={driverKind}
920 models={modelsForDisplay}
921 customModels={customModels}
922 hiddenModels={hiddenModels}
923 favoriteModels={favoriteModels}
924 modelOrder={modelOrder}
925 onChange={updateCustomModels}
926 onHiddenModelsChange={onHiddenModelsChange}
927 onFavoriteModelsChange={onFavoriteModelsChange}
928 onModelOrderChange={onModelOrderChange}
929 />
930 </div>
931 ) : null}
932 </div>
933 </div>
934 );