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