Open History to see the last commit
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 };
85}
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 );
104}
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");
117}
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;
136}
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];
158}
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 );
173}
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 );
345}
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 hiddenModels: ReadonlyArray<string>;
373 readonly favoriteModels: ReadonlyArray<string>;
374 readonly modelOrder: ReadonlyArray<string>;
375 readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
376 readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
377 readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
378 readonly onRunUpdate?: (() => void) | undefined;
379 readonly isUpdating?: boolean | undefined;
380}
381
382/**
383 * Renders one provider instance as either a compact selectable list row or
384 * the full editor shown beside that list. Both modes use the same enabled
385 * state and provider metadata.
386 *
387 * Behavior notes:
388 * - `liveProvider` is matched by the caller via `instanceId`; when no
389 * match is available (e.g. the server hasn't probed yet, or the
390 * driver is not shipped by the current build) the card still renders
391 * with a neutral "checking" summary.
392 * - Unknown drivers (`driverOption === undefined`) get a read-only
393 * notice instead of editable fields, so fork instances round-trip
394 * without accidentally destroying their config.
395 * - The enabled Switch writes to the envelope's `instance.enabled`
396 * field, which is the single enabled flag: the server folds any legacy
397 * driver-specific `config.enabled` into the envelope on load and both
398 * sides resolve through `resolveProviderInstanceEnabled` (an explicit
399 * false wins, then envelope, then config, then the driver default).
400 */
401export function ProviderInstanceCard({
402 instanceId,
403 instance,
404 driverOption,
405 liveProvider,
406 mode,
407 selected = false,
408 onSelect,
409 readOnly = false,
410 onUpdate,
411 onDelete,
412 headerAction,
413 hiddenModels,
414 favoriteModels,
415 modelOrder,
416 onHiddenModelsChange,
417 onFavoriteModelsChange,
418 onModelOrderChange,
419 onRunUpdate,
420 isUpdating = false,
421}: ProviderInstanceCardProps) {
422 const [activeTab, setActiveTab] = useState<"configuration" | "models">("configuration");
423 const enabled = resolveProviderInstanceEnabled(instance);
424 // A locally disabled provider reads "Disabled" with a muted dot even if its
425 // last server status is stale. Enabled providers use the server status.
426 const statusKey: ProviderStatusKey = enabled
427 ? ((liveProvider?.status as ProviderStatusKey | undefined) ?? "warning")
428 : "disabled";
429 const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
430 const summary = enabled
431 ? getProviderSummary(liveProvider)
432 : { headline: "Disabled", detail: null };
433 const authEmail = liveProvider?.auth.email?.trim();
434 // The editor header folds the account email into the status line —
435 // "Authenticated as <email> · <plan>" — with the email redacted until its
436 // reveal toggle is clicked.
437 const isAuthenticated = enabled && liveProvider?.auth.status === "authenticated";
438 const authLabel =
439 enabled && liveProvider?.auth.status === "authenticated"
440 ? (liveProvider.auth.label ?? liveProvider.auth.type ?? null)
441 : null;
442 const versionLabel = getProviderVersionLabel(liveProvider?.version);
443 const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
444 const updateCommand = versionAdvisory?.updateCommand ?? null;
445 const FallbackIconComponent = driverOption?.icon;
446 const displayName =
447 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
448 const accentColor = normalizeProviderAccentColor(instance.accentColor);
449 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
450 onCopy: ({ providerName }) => {
451 toastManager.add({
452 type: "success",
453 title: `${providerName} update command copied`,
454 description: "Run it in a terminal when you are ready to update.",
455 });
456 },
457 onError: (error, { providerName }) => {
458 toastManager.add(
459 stackedThreadToast({
460 type: "error",
461 title: `Could not copy ${providerName} update command`,
462 description: error.message,
463 }),
464 );
465 },
466 });
467
468 // Narrow `instance.driver` for callers that key on the closed
469 // `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
470 // fork drivers pass through as `null` and those callers fall back to
471 // verbatim behaviour.
472 const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
473 ? instance.driver
474 : null;
475 const visibleTab = driverOption === undefined ? "configuration" : activeTab;
476
477 const customModels = readConfigStringArray(instance.config, "customModels");
478 // Server-returned models may lag behind settings writes. Treat probe
479 // models as the source for built-ins only; custom rows come directly
480 // from the current instance config so add/remove reflects immediately.
481 const modelsForDisplay = deriveProviderModelsForDisplay({
482 liveModels: liveProvider?.models,
483 customModels,
484 });
485 const hiddenModelCount = modelsForDisplay.filter(
486 (model) => !model.isCustom && hiddenModels.includes(model.slug),
487 ).length;
488
489 const updateDisplayName = (value: string) => {
490 const trimmed = value.trim();
491 const { displayName: _omit, ...rest } = instance;
492 onUpdate(
493 trimmed.length > 0
494 ? ({ ...rest, displayName: trimmed } as ProviderInstanceConfig)
495 : (rest as ProviderInstanceConfig),
496 );
497 };
498
499 const updateEnabled = (value: boolean) => {
500 onUpdate({ ...instance, enabled: value });
501 };
502
503 const updateAccentColor = (value: string) => {
504 const normalized = normalizeProviderAccentColor(value);
505 const { accentColor: _omit, ...rest } = instance;
506 onUpdate(
507 normalized
508 ? ({ ...rest, accentColor: normalized } as ProviderInstanceConfig)
509 : (rest as ProviderInstanceConfig),
510 );
511 };
512
513 const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
514 const { config: _omit, ...rest } = instance;
515 onUpdate(
516 nextConfig !== undefined
517 ? ({ ...rest, config: nextConfig } as ProviderInstanceConfig)
518 : (rest as ProviderInstanceConfig),
519 );
520 };
521
522 const updateCustomModels = (next: ReadonlyArray<string>) => {
523 const nextConfig = nextConfigBlobWithValue(instance.config, "customModels", [...next]);
524 const { config: _omit, ...rest } = instance;
525 onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
526 };
527
528 const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
529 const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
530 const { environment: _omit, ...rest } = instance;
531 onUpdate(
532 cleaned.length > 0
533 ? ({ ...rest, environment: cleaned } as ProviderInstanceConfig)
534 : (rest as ProviderInstanceConfig),
535 );
536 };
537
538 const titleIconNode = driverKind ? (
539 <ProviderInstanceIcon
540 driverKind={driverKind}
541 displayName={displayName}
542 accentColor={accentColor}
543 showBadge={Boolean(accentColor)}
544 className="size-5"
545 iconClassName="size-4 text-foreground/80"
546 badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-[7px]"
547 />
548 ) : FallbackIconComponent ? (
549 <span className="inline-flex size-5 shrink-0 items-center justify-center">
550 <FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
551 </span>
552 ) : (
553 <span
554 className="inline-flex size-5 shrink-0 items-center justify-center text-[10px] font-semibold leading-none text-foreground/80"
555 aria-hidden
556 >
557 {providerInstanceInitials(displayName)}
558 </span>
559 );
560
561 const titleHeadNode = (
562 <>
563 {titleIconNode}
564 <h3 className="truncate text-sm font-medium tracking-[-0.005em] text-foreground">
565 {displayName}
566 </h3>
567 {String(instanceId) !== String(instance.driver) ? (
568 <code className="truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
569 {instanceId}
570 </code>
571 ) : null}
572 {driverOption?.badgeLabel ? (
573 <Badge variant="warning" size="sm" className="shrink-0">
574 {driverOption.badgeLabel}
575 </Badge>
576 ) : null}
577 </>
578 );
579
580 const titleTailNode = headerAction ? (
581 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">{headerAction}</span>
582 ) : null;
583
584 const versionCodeNode = versionLabel ? (
585 <code className="text-xs text-muted-foreground">{versionLabel}</code>
586 ) : null;
587
588 // Healthy and disabled rows read fine from their text; only trouble gets a dot.
589 const statusDotNode =
590 statusKey === "warning" || statusKey === "error" ? (
591 <span className={cn("size-1.5 shrink-0 rounded-full", statusStyle.dot)} aria-hidden />
592 ) : null;
593 const statusHeadlineNode = <span>{summary.headline}</span>;
594 // Trouble states carry the server's explanation (a failed probe, a shadow
595 // home entry that is not a symlink, a missing binary). Show it wherever the
596 // headline shows so the user can act without opening the editor.
597 const needsAttention = statusKey === "warning" || statusKey === "error";
598 const statusLineClassName =
599 "flex min-w-0 flex-wrap items-center gap-x-1.5 text-[13px] leading-[1.45] text-muted-foreground/80";
600
601 if (mode === "list") {
602 return (
603 <div
604 className={cn(
605 // Sidebar-style selection with a fixed row height so the list stays
606 // even; the status line clamps to two lines instead of growing.
607 "group flex min-h-19 items-start gap-3 rounded-md px-3 py-2 transition-colors",
608 // Foreground-alpha tint so the fill reads the same in light and dark themes.
609 selected ? "bg-foreground/8" : "hover:bg-foreground/4",
610 )}
611 >
612 <button
613 type="button"
614 className={cn(
615 "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",
616 !enabled && !selected && "opacity-60 group-hover:opacity-100",
617 )}
618 onClick={onSelect}
619 aria-pressed={selected}
620 >
621 {titleIconNode}
622 <span className="min-w-0 flex-1">
623 <span className="flex min-w-0 items-center gap-2">
624 <span className="truncate text-sm font-medium text-foreground">{displayName}</span>
625 {String(instanceId) !== String(instance.driver) ? (
626 <code className="min-w-0 truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
627 {instanceId}
628 </code>
629 ) : null}
630 {versionCodeNode}
631 {versionAdvisory ? (
632 <span role="img" aria-label="Update available" className="inline-flex shrink-0">
633 <ArrowUpCircleIcon className="size-3.5 text-muted-foreground" />
634 </span>
635 ) : null}
636 </span>
637 <span className="mt-0.5 flex items-start gap-1.5 text-[13px] leading-[1.45] text-muted-foreground/80">
638 {statusDotNode ? (
639 <span className="flex h-[1.45em] shrink-0 items-center">{statusDotNode}</span>
640 ) : null}
641 <span className="line-clamp-2 [overflow-wrap:anywhere]">
642 {summary.headline}
643 {needsAttention && summary.detail ? ` · ${summary.detail}` : null}
644 </span>
645 </span>
646 </span>
647 </button>
648 <span className="flex h-5 shrink-0 items-center">
649 <Switch
650 checked={enabled}
651 disabled={readOnly}
652 onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
653 aria-label={`Enable ${displayName}`}
654 />
655 </span>
656 </div>
657 );
658 }
659
660 return (
661 <div className="min-w-0 lg:flex lg:h-full lg:min-h-0 lg:flex-col">
662 <div className="flex min-h-16 shrink-0 items-start justify-between gap-3 border-b border-border/70 px-4 py-3">
663 <div className="min-w-0 flex-1 space-y-1">
664 <div className="flex min-w-0 flex-wrap items-center gap-2">
665 {titleHeadNode}
666 {versionCodeNode}
667 {/*
668 Only the write actions go inert on read-only sessions; the
669 status line below keeps its email reveal clickable.
670 */}
671 <span
672 inert={readOnly}
673 aria-disabled={readOnly || undefined}
674 className={cn("inline-flex items-center gap-2", readOnly && "opacity-50")}
675 >
676 {versionAdvisory ? (
677 <Popover>
678 <PopoverTrigger
679 render={
680 <Button
681 type="button"
682 size="icon-micro"
683 variant="ghost"
684 className={cn(
685 "[--control-icon-color:currentColor]",
686 versionAdvisory.emphasis === "strong"
687 ? "text-warning hover:text-warning"
688 : "text-muted-foreground hover:text-foreground",
689 )}
690 aria-label="Update available — view details"
691 >
692 <ArrowUpCircleIcon className="size-3.5" />
693 </Button>
694 }
695 />
696 <PopoverPopup
697 side="bottom"
698 align="start"
699 className="w-[min(21rem,calc(100vw-1.5rem))] [--popup-width:min(21rem,calc(100vw-1.5rem))]"
700 >
701 <div className="grid min-w-0 gap-3">
702 <div className="grid gap-0.5">
703 <p className="text-[13px] font-semibold leading-tight text-foreground">
704 Update available
705 </p>
706 <p
707 className={cn(
708 "text-xs leading-snug",
709 versionAdvisory.emphasis === "strong"
710 ? "text-warning"
711 : "text-muted-foreground",
712 )}
713 >
714 {versionAdvisory.detail}
715 </p>
716 </div>
717 {onRunUpdate ? (
718 <Button
719 type="button"
720 size="xs"
721 variant="outline"
722 className="w-full"
723 disabled={isUpdating}
724 onClick={onRunUpdate}
725 >
726 {isUpdating ? <LoaderIcon className="animate-spin" /> : <DownloadIcon />}
727 {isUpdating ? "Updating" : "Update now"}
728 </Button>
729 ) : null}
730 {onRunUpdate && updateCommand ? (
731 <div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
732 <span aria-hidden className="h-px flex-1 bg-border" />
733 or, update manually using
734 <span aria-hidden className="h-px flex-1 bg-border" />
735 </div>
736 ) : null}
737 {updateCommand ? (
738 <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">
739 <ScrollArea scrollFade className="h-8 min-w-0 flex-1 rounded-none">
740 <code className="flex h-full w-max items-center whitespace-nowrap pr-3 font-mono text-[11px] text-foreground">
741 {updateCommand}
742 </code>
743 </ScrollArea>
744 <Tooltip>
745 <TooltipTrigger
746 render={
747 <Button
748 type="button"
749 size="icon-xs"
750 variant="ghost"
751 className="shrink-0 text-muted-foreground hover:text-foreground"
752 onClick={() =>
753 copyToClipboard(updateCommand, {
754 providerName: displayName,
755 })
756 }
757 aria-label="Copy update command"
758 >
759 <CopyIcon className="size-3" />
760 </Button>
761 }
762 />
763 <TooltipPopup side="top">Copy command</TooltipPopup>
764 </Tooltip>
765 </div>
766 ) : null}
767 </div>
768 </PopoverPopup>
769 </Popover>
770 ) : null}
771 {titleTailNode}
772 </span>
773 </div>
774 <p className={statusLineClassName}>
775 {statusDotNode}
776 {isAuthenticated && authEmail ? (
777 <>
778 <span>Authenticated as</span>
779 <ProviderAuthEmail email={authEmail} />
780 {authLabel ? <span>· {authLabel}</span> : null}
781 </>
782 ) : (
783 statusHeadlineNode
784 )}
785 {summary.detail && !needsAttention ? <span>· {summary.detail}</span> : null}
786 </p>
787 {summary.detail && needsAttention ? (
788 <p className="text-[13px] leading-[1.45] text-muted-foreground/80 [overflow-wrap:anywhere]">
789 {summary.detail}
790 </p>
791 ) : null}
792 </div>
793 {onDelete ? (
794 <span
795 inert={readOnly}
796 aria-disabled={readOnly || undefined}
797 className={cn("shrink-0", readOnly && "opacity-50")}
798 >
799 <Button
800 type="button"
801 size="xs"
802 variant="ghost"
803 className="[--control-icon-color:currentColor] text-muted-foreground hover:text-destructive"
804 onClick={onDelete}
805 aria-label={`Delete instance ${instanceId}`}
806 >
807 <Trash2Icon className="size-3" />
808 Delete instance
809 </Button>
810 </span>
811 ) : null}
812 </div>
813
814 <div className="flex h-11 shrink-0 border-b border-border/70 px-1">
815 <button
816 type="button"
817 aria-pressed={visibleTab === "configuration"}
818 className={providerSettingsTabClassName(visibleTab === "configuration")}
819 onClick={() => setActiveTab("configuration")}
820 >
821 Configuration
822 </button>
823 {driverOption !== undefined ? (
824 <button
825 type="button"
826 aria-pressed={visibleTab === "models"}
827 className={cn(providerSettingsTabClassName(visibleTab === "models"), "gap-1.5")}
828 onClick={() => setActiveTab("models")}
829 >
830 Models
831 <span className="font-normal text-muted-foreground/70">
832 {modelsForDisplay.length}
833 {hiddenModelCount > 0 ? ` · ${hiddenModelCount} hidden` : ""}
834 </span>
835 </button>
836 ) : null}
837 </div>
838
839 <div className="lg:min-h-0 lg:flex-1">
840 <ScrollArea
841 scrollFade
842 chainVerticalScroll
843 className="lg:h-full"
844 hidden={visibleTab !== "configuration"}
845 >
846 <div
847 inert={readOnly}
848 aria-disabled={readOnly || undefined}
849 className={cn("px-4 py-4", readOnly && "opacity-50 select-none")}
850 >
851 <div className={PROVIDER_FIELD_GRID_CLASS_NAME}>
852 <label
853 htmlFor={`provider-instance-${instanceId}-display-name`}
854 className="pt-1.5 text-xs font-medium text-foreground"
855 >
856 Display name
857 </label>
858 <div className="flex min-w-0 flex-wrap items-center gap-3">
859 <DraftInput
860 id={`provider-instance-${instanceId}-display-name`}
861 size="sm"
862 className="w-44"
863 value={instance.displayName ?? ""}
864 onCommit={updateDisplayName}
865 placeholder={driverOption?.label ?? "Instance label"}
866 spellCheck={false}
867 />
868 <ProviderAccentColorPicker
869 layout="inline"
870 displayName={displayName}
871 value={accentColor}
872 onCommit={updateAccentColor}
873 commitDelayMs={120}
874 />
875 </div>
876 <div className={PROVIDER_FIELD_GROUP_LABEL_CLASS_NAME}>Runtime</div>
877 {driverOption ? (
878 <ProviderSettingsForm
879 definition={driverOption}
880 value={instance.config}
881 idPrefix={`provider-instance-${instanceId}`}
882 variant="grid"
883 onChange={updateConfig}
884 />
885 ) : (
886 <>
887 <span className="pt-1.5 text-xs font-medium text-foreground">Driver</span>
888 <p className="text-xs text-muted-foreground">
889 This instance uses a driver (
890 <code className="text-foreground">{String(instance.driver)}</code>) that is not
891 shipped with the current build. Configuration values are preserved but cannot be
892 edited from this surface.
893 </p>
894 </>
895 )}
896 <div className={PROVIDER_FIELD_GROUP_LABEL_CLASS_NAME}>Environment</div>
897 <div className="col-span-full">
898 <ProviderEnvironmentSection
899 environment={instance.environment ?? []}
900 onChange={updateEnvironment}
901 />
902 </div>
903 </div>
904 </div>
905 </ScrollArea>
906 {driverOption !== undefined ? (
907 <div
908 inert={readOnly}
909 aria-disabled={readOnly || undefined}
910 className={cn("px-4 py-5 lg:h-full lg:min-h-0", readOnly && "opacity-50 select-none")}
911 hidden={visibleTab !== "models"}
912 >
913 <ProviderModelsSection
914 instanceId={instanceId}
915 driverKind={driverKind}
916 models={modelsForDisplay}
917 customModels={customModels}
918 hiddenModels={hiddenModels}
919 favoriteModels={favoriteModels}
920 modelOrder={modelOrder}
921 onChange={updateCustomModels}
922 onHiddenModelsChange={onHiddenModelsChange}
923 onFavoriteModelsChange={onFavoriteModelsChange}
924 onModelOrderChange={onModelOrderChange}
925 />
926 </div>
927 ) : null}
928 </div>
929 </div>
930 );
931}