Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
"use client";
import type { ProviderConfig } from "./providerConfig";
import {
ArrowUpCircleIcon,
ChevronDownIcon,
CopyIcon,
DownloadIcon,
LoaderIcon,
Trash2Icon,
} from "lucide-react";
import { type ReactNode } from "react";
import {
isProviderDriverKind,
resolveProviderInstanceEnabled,
type ProviderInstanceConfig,
type ProviderInstanceEnvironmentVariable,
type ProviderInstanceId,
ProviderDriverKind,
type ServerProvider,
} from "@akeru/contracts";
import { cn } from "../../lib/utils";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { normalizeProviderAccentColor } from "../../providerInstances";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Collapsible, CollapsibleContent } from "../ui/collapsible";
import { DraftInput } from "../ui/draft-input";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { ScrollArea } from "../ui/scroll-area";
import { Switch } from "../ui/switch";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import type { DriverOption } from "./providerDriverMeta";
import { ProviderSettingsForm, readProviderConfigString } from "./ProviderSettingsForm";
import { ProviderModelsSection } from "./ProviderModelsSection";
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
import {
getProviderVersionAdvisoryPresentation,
PROVIDER_STATUS_STYLES,
getProviderSummary,
getProviderVersionLabel,
type ProviderStatusKey,
} from "./providerStatus";
import { ProviderEnvironmentSection } from "./ProviderEnvironmentSection";
import { CustomApiKeyField } from "./CustomApiKeyField";
import {
customApiKeyHint,
customApiKeyLeavesEndpoint,
customApiPresetForBaseUrl,
readCustomApiKey,
withCustomApiKey,
withoutCustomApiKey,
withStoredCustomApiKey,
} from "./customApiPresets";
import { ProviderAuthEmail } from "./ProviderAuthEmail";
import {
readConfigStringArray,
nextConfigBlobWithValue,
deriveProviderModelsForDisplay,
} from "./providerInstanceCard.logic";
interface ProviderInstanceCardProps {
readonly instanceId: ProviderInstanceId;
readonly instance: ProviderInstanceConfig;
readonly driverOption: DriverOption | undefined;
readonly liveProvider: ServerProvider | undefined;
readonly isExpanded: boolean;
readonly onExpandedChange: (open: boolean) => void;
readonly onUpdate: (nextInstance: ProviderInstanceConfig) => void;
/**
* Pass `undefined` to hide the delete button entirely. Built-in default
* instance slots use `undefined` — they can't be deleted without losing
* the slot, and their "reset to defaults" affordance lives on an outer
* reset button instead. Explicit `| undefined` in the type accommodates
* `exactOptionalPropertyTypes: true`, where an absent key and
* `{ onDelete: undefined }` are treated as distinct shapes.
*/
readonly onDelete?: (() => void) | undefined;
/**
* Optional outer reset button rendered next to the driver icon. Built-in
* default slots supply a reset-to-factory control here; custom instances
* omit it.
*/
readonly headerAction?: ReactNode | undefined;
readonly accountContent?: ReactNode;
readonly hiddenModels: ReadonlyArray<string>;
readonly favoriteModels: ReadonlyArray<string>;
readonly modelOrder: ReadonlyArray<string>;
readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
readonly onRunUpdate?: (() => void) | undefined;
readonly isUpdating?: boolean | undefined;
}
/**
* A single configured provider-instance row in the Providers settings
* section. Used for every row — both the built-in default instance for a
* driver (rendered with `onDelete` omitted) and user-authored custom
* instances (`onDelete` supplied). The only UI difference between the two
* is whether the trash button is visible; every other field (display
* name, config fields, models) behaves identically.
*
* Behavior notes:
* - `liveProvider` is matched by the caller via `instanceId`; when no
* match is available (e.g. the server hasn't probed yet, or the
* driver is not shipped by the current build) the card still renders
* with a neutral "checking" summary.
* - Unknown drivers (`driverOption === undefined`) get a read-only
* notice instead of editable fields, so fork instances round-trip
* without accidentally destroying their config.
* - The enabled Switch writes to the envelope's `instance.enabled`
* field, which is the single enabled flag: the server folds any legacy
* driver-specific `config.enabled` into the envelope on load and both
* sides resolve through `resolveProviderInstanceEnabled` (an explicit
* false wins, then envelope, then config, then the driver default).
*/
export function ProviderInstanceCard({
instanceId,
instance,
driverOption,
liveProvider,
isExpanded,
onExpandedChange,
onUpdate,
onDelete,
headerAction,
accountContent,
hiddenModels,
favoriteModels,
modelOrder,
onHiddenModelsChange,
onFavoriteModelsChange,
onModelOrderChange,
onRunUpdate,
isUpdating = false,
}: ProviderInstanceCardProps) {
const enabled = resolveProviderInstanceEnabled(instance);
// The server-reported status wins when present; otherwise fall back to
// "disabled"/"warning" based on the local `enabled` flag so the dot
// reflects the persisted intent even before the first probe completes.
const statusKey: ProviderStatusKey = liveProvider?.status ?? (enabled ? "warning" : "disabled");
const statusStyle = PROVIDER_STATUS_STYLES[statusKey];
const rawSummary = getProviderSummary(liveProvider);
const authEmail = liveProvider?.auth.email;
const hasAuthenticatedEmail =
liveProvider?.auth.status === "authenticated" && Boolean(authEmail?.trim());
const authenticatedDetail = hasAuthenticatedEmail
? (liveProvider?.auth.label ?? liveProvider?.auth.type ?? null)
: null;
const summary = rawSummary;
const versionLabel = getProviderVersionLabel(liveProvider?.version);
const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
const updateCommand = versionAdvisory?.updateCommand ?? null;
const FallbackIconComponent = driverOption?.icon;
const displayName =
instance.displayName?.trim() || driverOption?.label || String(instance.driver);
const accentColor = normalizeProviderAccentColor(instance.accentColor);
const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
onCopy: ({ providerName }) => {
toastManager.add({
type: "success",
title: `${providerName} update command copied`,
description: "Run it in a terminal when you are ready to update.",
});
},
onError: (error, { providerName }) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: `Could not copy ${providerName} update command`,
description: error.message,
}),
);
},
});
// Narrow `instance.driver` for callers that key on the closed
// `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
// fork drivers pass through as `null` and those callers fall back to
// verbatim behaviour.
const driverKind: ProviderDriverKind | null = isProviderDriverKind(instance.driver)
? instance.driver
: null;
const customModels = readConfigStringArray(instance.config, "customModels");
// Server-returned models may lag behind settings writes. Treat probe
// models as the source for built-ins only; custom rows come directly
// from the current instance config so add/remove reflects immediately.
const modelsForDisplay = deriveProviderModelsForDisplay({
liveModels: liveProvider?.models,
customModels,
});
const updateDisplayName = (value: string) => {
const trimmed = value.trim();
const { displayName: _omit, ...rest } = instance;
onUpdate(trimmed.length > 0 ? { ...rest, displayName: trimmed } : rest);
};
const updateEnabled = (value: boolean) => {
onUpdate({ ...instance, enabled: value });
};
const updateAccentColor = (value: string) => {
const normalized = normalizeProviderAccentColor(value);
const { accentColor: _omit, ...rest } = instance;
onUpdate(normalized ? { ...rest, accentColor: normalized } : rest);
};
// Every edit that can move a Custom API endpoint goes through here, so a
// stored key is never probed against a host it was not saved for.
const commitEndpointEdit = (next: ProviderInstanceConfig) => {
const dropsCustomApiKey =
instance.driver === ProviderDriverKind.make("customOpenai") &&
readCustomApiKey(next.environment ?? []) !== undefined &&
customApiKeyLeavesEndpoint(
{
baseUrl: readProviderConfigString(instance.config, "baseUrl"),
environment: instance.environment ?? [],
},
{
baseUrl: readProviderConfigString(next.config, "baseUrl"),
environment: next.environment ?? [],
},
);
if (!dropsCustomApiKey) {
onUpdate(next);
return;
}
// Save the new address and drop the old key together.
const environment = withoutCustomApiKey(next.environment ?? []);
const { environment: _omitEnvironment, ...withoutEnvironment } = next;
onUpdate(environment.length > 0 ? { ...next, environment } : withoutEnvironment);
toastManager.add({
type: "info",
title: "API key removed",
description: "The new address is a different service. Paste its key to connect.",
});
};
const updateConfig = (nextConfig: ProviderConfig | undefined) => {
const { config: _omit, ...rest } = instance;
commitEndpointEdit(nextConfig !== undefined ? { ...rest, config: nextConfig } : rest);
};
const updateCustomModels = (next: ReadonlyArray<string>) => {
const nextConfig = nextConfigBlobWithValue(instance.config, "customModels", [...next]);
const { config: _omit, ...rest } = instance;
onUpdate({ ...rest, config: nextConfig });
};
const withEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => {
const cleaned = environment.filter((variable) => variable.name.trim().length > 0);
const { environment: _omit, ...rest } = instance;
return cleaned.length > 0 ? { ...rest, environment: cleaned } : rest;
};
const updateEnvironment = (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) =>
onUpdate(withEnvironment(environment));
// Custom API keeps its key in a dedicated field, so the generic variable
// table hides it and merges it back on edit.
const isCustomApi = instance.driver === ProviderDriverKind.make("customOpenai");
const environment = instance.environment ?? [];
const customApiKey = isCustomApi ? readCustomApiKey(environment) : undefined;
const customApiPreset = customApiPresetForBaseUrl(
readProviderConfigString(instance.config, "baseUrl"),
);
const titleIconNode = driverKind ? (
<ProviderInstanceIcon
driverKind={driverKind}
displayName={displayName}
accentColor={accentColor}
showBadge={Boolean(accentColor)}
statusDotClassName={statusStyle.dot}
indicatorBackground="var(--card)"
className="size-5"
iconClassName="size-4 text-foreground/80"
badgeClassName="-right-0.5 -bottom-0.5 h-3 min-w-3 px-0.5 text-7px"
/>
) : FallbackIconComponent ? (
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
<FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
<span
className={cn(
"pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-card",
statusStyle.dot,
)}
aria-hidden
/>
</span>
) : (
<span className={cn("size-2 shrink-0 rounded-full", statusStyle.dot)} />
);
const titleHeadNode = (
<>
{titleIconNode}
<h3 className="truncate text-sm font-medium tracking-title-xs text-foreground">
{displayName}
</h3>
{String(instanceId) !== String(instance.driver) ? (
<code className="truncate rounded bg-muted/60 px-1 py-0.5 text-10px text-muted-foreground">
{instanceId}
</code>
) : null}
{driverOption?.badgeLabel ? (
<Badge variant="warning" size="sm" className="shrink-0">
{driverOption.badgeLabel}
</Badge>
) : null}
</>
);
const titleTailNode = (
<>
{headerAction ? (
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
{headerAction}
</span>
) : null}
{onDelete ? (
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-micro"
variant="ghost"
presentation="provider-remove"
onClick={onDelete}
aria-label={`Delete account ${instanceId}`}
>
<Trash2Icon className="size-3" />
</Button>
}
/>
<TooltipPopup side="top">Delete account</TooltipPopup>
</Tooltip>
</span>
) : null}
</>
);
const authRowNode = (
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-13px leading-copy text-muted-foreground/80">
{hasAuthenticatedEmail ? (
<>
<span>Authenticated as</span>
<ProviderAuthEmail email={authEmail} />
{authenticatedDetail ? <span>· {authenticatedDetail}</span> : null}
</>
) : (
<>
<span>{summary.headline}</span>
<ProviderAuthEmail email={authEmail} separator prefix="Email" />
</>
)}
{summary.detail ? <span>- {summary.detail}</span> : null}
</p>
);
const versionCodeNode = versionLabel ? (
<code className="text-xs text-muted-foreground">{versionLabel}</code>
) : null;
return (
<div data-settings-row="" className="rounded-xl">
<div className="px-3 py-3 sm:px-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 flex-1 space-y-1">
<div className="flex min-w-0 flex-wrap items-center gap-2">
{titleHeadNode}
{versionCodeNode}
{versionAdvisory ? (
<Popover>
<PopoverTrigger
render={
<Button
type="button"
size="icon-xs"
variant="ghost"
presentation={
versionAdvisory.emphasis === "strong"
? "provider-update-strong"
: "provider-update"
}
aria-label="Update available, view details"
>
<ArrowUpCircleIcon className="size-3.5" />
</Button>
}
/>
<PopoverPopup side="bottom" align="start" variant="provider-update">
<div className="grid min-w-0 gap-3">
<div className="grid gap-0.5">
<p className="text-13px font-semibold leading-tight text-foreground">
Update available
</p>
<p
className={cn(
"text-xs leading-snug",
versionAdvisory.emphasis === "strong"
? "text-warning"
: "text-muted-foreground",
)}
>
{versionAdvisory.detail}
</p>
</div>
{onRunUpdate ? (
<Button
type="button"
size="xs"
variant="outline"
className="w-full"
disabled={isUpdating}
onClick={onRunUpdate}
>
{isUpdating ? <LoaderIcon className="animate-spin" /> : <DownloadIcon />}
{isUpdating ? "Updating" : "Update now"}
</Button>
) : null}
{onRunUpdate && updateCommand ? (
<div className="flex items-center gap-2 text-10px font-medium uppercase tracking-wider text-muted-foreground">
<span aria-hidden className="h-px flex-1 bg-border" />
or, update manually using
<span aria-hidden className="h-px flex-1 bg-border" />
</div>
) : null}
{updateCommand ? (
<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">
<ScrollArea scrollFade variant="provider-email">
<code className="flex h-full w-max items-center whitespace-nowrap pr-3 font-mono text-11px text-foreground">
{updateCommand}
</code>
</ScrollArea>
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
size="icon-xs"
variant="ghost"
presentation="provider-email-copy"
onClick={() =>
copyToClipboard(updateCommand, {
providerName: displayName,
})
}
aria-label="Copy update command"
>
<CopyIcon className="size-3" />
</Button>
}
/>
<TooltipPopup side="top">Copy command</TooltipPopup>
</Tooltip>
</div>
) : null}
</div>
</PopoverPopup>
</Popover>
) : null}
{titleTailNode}
</div>
{authRowNode}
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
<Button
size="compact"
variant="ghost-muted"
onClick={() => onExpandedChange(!isExpanded)}
aria-label={`Toggle ${displayName} details`}
>
<ChevronDownIcon
className={cn("size-3.5 transition-transform", isExpanded && "rotate-180")}
/>
</Button>
<Switch
checked={enabled}
onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
aria-label={`Enable ${displayName}`}
/>
</div>
</div>
</div>
<Collapsible open={isExpanded} onOpenChange={onExpandedChange}>
<CollapsibleContent>
<div className="space-y-5 px-3 pb-4 pt-2 sm:px-4">
{accountContent}
<div>
<label htmlFor={`provider-instance-${instanceId}-display-name`} className="block">
<span className="text-xs font-medium text-foreground">Display name</span>
<DraftInput
id={`provider-instance-${instanceId}-display-name`}
className="mt-1.5"
value={instance.displayName ?? ""}
onCommit={updateDisplayName}
placeholder={driverOption?.label ?? "Account name"}
spellCheck={false}
/>
<span className="mt-1 block text-xs text-muted-foreground">
Optional label shown in the provider list.
</span>
</label>
</div>
<div>
<ProviderAccentColorPicker
displayName={displayName}
value={accentColor}
onCommit={updateAccentColor}
commitDelayMs={120}
description="Tells this account apart in the model picker."
/>
</div>
<div>
<ProviderEnvironmentSection
environment={isCustomApi ? withoutCustomApiKey(environment) : environment}
onChange={(next) =>
commitEndpointEdit(
withEnvironment(
isCustomApi ? withStoredCustomApiKey(next, customApiKey) : next,
),
)
}
/>
</div>
{driverOption ? (
<ProviderSettingsForm
definition={driverOption}
value={instance.config}
idPrefix={`provider-instance-${instanceId}`}
variant="card"
onChange={updateConfig}
/>
) : null}
{isCustomApi ? (
<CustomApiKeyField
id={`provider-instance-${instanceId}-api-key`}
variable={customApiKey}
required={customApiPreset.key.kind === "required"}
hint={customApiKeyHint(customApiPreset)}
onCommit={(value) => updateEnvironment(withCustomApiKey(environment, value))}
onRemove={() => updateEnvironment(withCustomApiKey(environment, ""))}
/>
) : null}
{driverOption !== undefined ? (
<ProviderModelsSection
instanceId={instanceId}
driverKind={driverKind}
models={modelsForDisplay}
customModels={customModels}
hiddenModels={hiddenModels}
favoriteModels={favoriteModels}
modelOrder={modelOrder}
onChange={updateCustomModels}
onHiddenModelsChange={onHiddenModelsChange}
onFavoriteModelsChange={onFavoriteModelsChange}
onModelOrderChange={onModelOrderChange}
/>
) : (
<div>
<p className="text-xs text-muted-foreground">
This instance uses a driver (
<code className="text-foreground">{String(instance.driver)}</code>) that is not
shipped with the current build. Configuration values are preserved but cannot be
edited from this surface.
</p>
</div>
)}
</div>
</CollapsibleContent>
</Collapsible>
</div>
);
}
export { deriveProviderModelsForDisplay } from "./providerInstanceCard.logic";