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

ProviderInstanceCard.tsx

919 lines33.0 KB

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