Refactor provider settings to declarative metadata (#2452)

Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
Julius MarmingeandJulius Marminge authored and GitHub committed 2026-05-02 14:14:34 -07:00
1 parent cb8015a34d
commit 460d9c3eb9
7 files changed
+738 -296

No files matched your search

@@ -13,7 +13,7 @@ import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
import { cn } from "../../lib/utils";
import { normalizeProviderAccentColor } from "../../providerInstances";
import { Button } from "../ui/button";
import { ACPRegistryIcon, Gemini, GithubCopilotIcon, PiAgentIcon } from "../Icons";
import { ACPRegistryIcon, Gemini, GithubCopilotIcon, PiAgentIcon, type Icon } from "../Icons";
import {
Dialog,
DialogDescription,
@@ -26,7 +26,8 @@ import { Badge } from "../ui/badge";
import { Input } from "../ui/input";
import { RadioGroup } from "../ui/radio-group";
import { toastManager } from "../ui/toast";
import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS, type DriverOption } from "./providerDriverMeta";
import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS } from "./providerDriverMeta";
import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSettingsForm";
const PROVIDER_ACCENT_SWATCHES = [
"#2563eb",
@@ -61,30 +62,33 @@ function deriveInstanceId(driver: ProviderDriverKind, label: string): string {
const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex");
const DEFAULT_DRIVER_OPTION = DRIVER_OPTIONS[0]!;
const COMING_SOON_DRIVER_OPTIONS: readonly DriverOption[] = [
const EMPTY_CONFIG_DRAFT: Record<string, unknown> = {};
interface ComingSoonDriverOption {
readonly value: ProviderDriverKind;
readonly label: string;
readonly icon: Icon;
}
const COMING_SOON_DRIVER_OPTIONS: readonly ComingSoonDriverOption[] = [
{
value: ProviderDriverKind.make("githubCopilot"),
label: "Github Copilot",
icon: GithubCopilotIcon,
fields: [],
},
{
value: ProviderDriverKind.make("gemini"),
label: "Gemini",
icon: Gemini,
fields: [],
},
{
value: ProviderDriverKind.make("acpRegistry"),
label: "ACP Registry",
icon: ACPRegistryIcon,
fields: [],
},
{
value: ProviderDriverKind.make("piAgent"),
label: "Pi Agent",
icon: PiAgentIcon,
fields: [],
},
];
@@ -118,10 +122,9 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
const [accentColor, setAccentColor] = useState<string>("");
const [instanceId, setInstanceId] = useState("");
const [instanceIdDirty, setInstanceIdDirty] = useState(false);
// Driver-specific field values keyed by `${driver}:${fieldKey}` so toggling
// between drivers during the same dialog session doesn't lose in-progress
// input. Only the active driver's values are persisted on save.
const [fieldValues, setFieldValues] = useState<Record<string, string>>({});
// Driver-specific config drafts keyed by driver so toggling between drivers
// during the same dialog session does not lose in-progress input.
const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
// Errors are suppressed until the user has tried to submit once. After that
// they update live so fixing the problem clears the message in place.
const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
@@ -141,7 +144,7 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
setInstanceId("");
setWizardStep(0);
setInstanceIdDirty(false);
setFieldValues({});
setConfigByDriver({});
setHasAttemptedSubmit(false);
}, [open]);
@@ -153,23 +156,28 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
}, [driver, label, instanceIdDirty]);
const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
const driverSettingsFields = useMemo(
() => deriveProviderSettingsFields(driverOption),
[driverOption],
);
const instanceIdError = validateInstanceId(instanceId, existingIds);
const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
const previewLabel = label.trim() || `${driverOption.label} Workspace`;
const wizardSteps = ["Driver", "Identity", "Config"] as const;
const wizardStepSummaries = [driverOption.label, previewLabel, null] as const;
const getFieldValue = useCallback(
(fieldKey: string) => fieldValues[`${driver}:${fieldKey}`] ?? "",
[driver, fieldValues],
);
const setFieldValue = useCallback(
(fieldKey: string, value: string) => {
setFieldValues((existing) => ({
...existing,
[`${driver}:${fieldKey}`]: value,
}));
const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT;
const setConfigDraft = useCallback(
(config: Record<string, unknown> | undefined) => {
setConfigByDriver((existing) => {
const next = { ...existing };
if (config === undefined || Object.keys(config).length === 0) {
delete next[driver];
} else {
next[driver] = config;
}
return next;
});
},
[driver],
);
@@ -178,13 +186,7 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
setHasAttemptedSubmit(true);
if (instanceIdError !== null) return;
// Build the config blob from non-empty driver-specific field values.
// Empty strings are dropped so defaults remain in effect on the server.
const config: Record<string, string> = {};
for (const field of driverOption.fields) {
const value = (fieldValues[`${driver}:${field.key}`] ?? "").trim();
if (value.length > 0) config[field.key] = value;
}
const config = configByDriver[driver] ?? {};
const hasConfig = Object.keys(config).length > 0;
const normalizedAccentColor = normalizeProviderAccentColor(accentColor);
@@ -222,7 +224,7 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
}, [
driver,
driverOption,
fieldValues,
configByDriver,
instanceId,
instanceIdError,
label,
@@ -433,25 +435,15 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
</span>
</div>
{driverOption.fields.length > 0 ? (
{driverSettingsFields.length > 0 ? (
<div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
{driverOption.fields.map((field) => (
<label key={field.key} className="grid gap-1.5">
<span className="text-xs font-medium text-foreground">{field.label}</span>
<Input
className="bg-background"
type={field.type === "password" ? "password" : undefined}
autoComplete={field.type === "password" ? "off" : undefined}
placeholder={field.placeholder}
value={getFieldValue(field.key)}
onChange={(event) => setFieldValue(field.key, event.target.value)}
spellCheck={false}
/>
{field.description ? (
<span className="text-[11px] text-muted-foreground">{field.description}</span>
) : null}
</label>
))}
<ProviderSettingsForm
definition={driverOption}
value={configDraft}
idPrefix={`add-provider-${driver}`}
variant="dialog"
onChange={setConfigDraft}
/>
</div>
) : wizardStep === 2 ? (
<div className="grid gap-2">
@@ -1,7 +1,7 @@
"use client";
import { ChevronDownIcon, PlusIcon, Trash2Icon, XIcon } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useState, type ReactNode } from "react";
import {
isProviderDriverKind,
type ProviderInstanceConfig,
@@ -21,6 +21,7 @@ import { DraftInput } from "../ui/draft-input";
import { Switch } from "../ui/switch";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import type { DriverOption } from "./providerDriverMeta";
import { ProviderSettingsForm } from "./ProviderSettingsForm";
import { ProviderModelsSection } from "./ProviderModelsSection";
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
import {
@@ -86,20 +87,6 @@ function redactedEmailPlaceholder(email: string): string {
}).join("");
}
/**
* Read a string value at `key` from the opaque per-driver config blob.
* Returns an empty string when the key is missing or the stored value is
* not a string. The permissive shape reflects that `config` is
* `Schema.Unknown` at the contract boundary — forks may populate it with
* non-string values that the built-in UI should round-trip without
* throwing.
*/
function readConfigString(config: unknown, key: string): string {
if (config === null || typeof config !== "object") return "";
const value = (config as Record<string, unknown>)[key];
return typeof value === "string" ? value : "";
}
/**
* Read a string[] at `key` from the opaque config blob, filtering out
* non-string entries. Used for `customModels`, which is always typed as
@@ -113,35 +100,9 @@ function readConfigStringArray(config: unknown, key: string): ReadonlyArray<stri
return value.filter((entry): entry is string => typeof entry === "string");
}
/**
* Produce the next config blob after setting `key` to `value`. Empty
* strings drop the key so server defaults stay in effect, mirroring the
* save-time normalization in `AddProviderInstanceDialog`. Returns
* `undefined` when the resulting blob has no keys, which matches
* `ProviderInstanceConfig.config` being optional.
*
* Non-string values already stored in the blob are carried through
* verbatim so fork-owned fields survive edits made through this UI.
*/
function nextConfigBlobWithString(
config: unknown,
key: string,
value: string,
): Record<string, unknown> | undefined {
const base: Record<string, unknown> =
config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
const trimmed = value.trim();
if (trimmed.length > 0) {
base[key] = value;
} else {
delete base[key];
}
return Object.keys(base).length > 0 ? base : undefined;
}
/**
* Set `key` to an arbitrary value on the opaque config blob. Unlike
* `nextConfigBlobWithString`, does not drop empty-looking values — the
* provider settings field updates, does not drop empty-looking values — the
* caller is responsible for deciding whether an empty array / empty
* object should be stored explicitly (e.g. `customModels: []` is a
* meaningful "user cleared their custom list" state distinct from
@@ -473,7 +434,7 @@ interface ProviderInstanceCardProps {
* default slots supply a reset-to-factory control here; custom instances
* omit it.
*/
readonly headerAction?: React.ReactNode | undefined;
readonly headerAction?: ReactNode | undefined;
readonly hiddenModels: ReadonlyArray<string>;
readonly favoriteModels: ReadonlyArray<string>;
readonly modelOrder: ReadonlyArray<string>;
@@ -585,8 +546,7 @@ export function ProviderInstanceCard({
);
};
const updateConfigField = (key: string, value: string) => {
const nextConfig = nextConfigBlobWithString(instance.config, key, value);
const updateConfig = (nextConfig: Record<string, unknown> | undefined) => {
const { config: _omit, ...rest } = instance;
onUpdate(
nextConfig !== undefined
@@ -759,28 +719,15 @@ export function ProviderInstanceCard({
/>
</div>
{driverOption?.fields.map((field) => (
<div key={field.key} className="border-t border-border/60 px-4 py-3 sm:px-5">
<label htmlFor={`provider-instance-${instanceId}-${field.key}`} className="block">
<span className="text-xs font-medium text-foreground">{field.label}</span>
<DraftInput
id={`provider-instance-${instanceId}-${field.key}`}
className="mt-1.5"
type={field.type === "password" ? "password" : undefined}
autoComplete={field.type === "password" ? "off" : undefined}
value={readConfigString(instance.config, field.key)}
onCommit={(next) => updateConfigField(field.key, next)}
placeholder={field.placeholder}
spellCheck={false}
/>
{field.description ? (
<span className="mt-1 block text-xs text-muted-foreground">
{field.description}
</span>
) : null}
</label>
</div>
))}
{driverOption ? (
<ProviderSettingsForm
definition={driverOption}
value={instance.config}
idPrefix={`provider-instance-${instanceId}`}
variant="card"
onChange={updateConfig}
/>
) : null}
{driverOption !== undefined ? (
<ProviderModelsSection
@@ -0,0 +1,131 @@
import { describe, expect, it } from "vitest";
import { ProviderDriverKind } from "@t3tools/contracts";
import { DRIVER_OPTION_BY_VALUE } from "./providerDriverMeta";
import {
deriveProviderSettingsFields,
nextProviderConfigWithFieldValue,
readProviderConfigBoolean,
readProviderConfigString,
} from "./ProviderSettingsForm";
describe("ProviderSettingsForm helpers", () => {
it("derives visible provider config fields from the client definition schema", () => {
const codex = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("codex")];
expect(codex).toBeDefined();
expect(deriveProviderSettingsFields(codex!).map((field) => field.key)).toEqual([
"binaryPath",
"homePath",
"shadowHomePath",
]);
});
it("sources labels and descriptions from schema annotations", () => {
const opencode = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("opencode")];
expect(opencode).toBeDefined();
const serverPassword = deriveProviderSettingsFields(opencode!).find(
(field) => field.key === "serverPassword",
);
expect(serverPassword).toMatchObject({
label: "Server password",
description: "Stored in plain text on disk.",
control: "password",
});
});
it("preserves unknown config keys while omitting empty configurable fields", () => {
const opencode = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("opencode")];
expect(opencode).toBeDefined();
const serverUrl = deriveProviderSettingsFields(opencode!).find(
(field) => field.key === "serverUrl",
);
expect(serverUrl).toBeDefined();
const next = nextProviderConfigWithFieldValue(
{ forkOwned: 1, serverUrl: "http://127.0.0.1:4096" },
serverUrl!,
"",
);
expect(next).toEqual({ forkOwned: 1 });
});
it("reads non-string config values as blank strings", () => {
expect(readProviderConfigString({ binaryPath: 123 }, "binaryPath")).toBe("");
});
it("omits false boolean fields when clearWhenEmpty is omit", () => {
const next = nextProviderConfigWithFieldValue(
{ forkOwned: 1, experimental: true },
{
key: "experimental",
control: "switch",
label: "Experimental",
clearWhenEmpty: "omit",
defaultBooleanValue: false,
},
false,
);
expect(next).toEqual({ forkOwned: 1 });
});
it("omits true boolean fields when true is the default", () => {
const next = nextProviderConfigWithFieldValue(
{ forkOwned: 1, experimental: false },
{
key: "experimental",
control: "switch",
label: "Experimental",
clearWhenEmpty: "omit",
defaultBooleanValue: true,
},
true,
);
expect(next).toEqual({ forkOwned: 1 });
});
it("stores false boolean fields when true is the default", () => {
const next = nextProviderConfigWithFieldValue(
undefined,
{
key: "experimental",
control: "switch",
label: "Experimental",
clearWhenEmpty: "omit",
defaultBooleanValue: true,
},
false,
);
expect(next).toEqual({ experimental: false });
});
it("preserves false boolean fields when clearWhenEmpty is persist", () => {
const next = nextProviderConfigWithFieldValue(
undefined,
{
key: "experimental",
control: "switch",
label: "Experimental",
clearWhenEmpty: "persist",
},
false,
);
expect(next).toEqual({ experimental: false });
});
it("reads non-boolean config values as false booleans", () => {
expect(readProviderConfigBoolean({ experimental: "true" }, "experimental")).toBe(false);
});
it("reads missing boolean config values from the supplied default", () => {
expect(readProviderConfigBoolean({}, "experimental", true)).toBe(true);
});
});
@@ -0,0 +1,306 @@
"use client";
import { useMemo, type ReactNode } from "react";
import { Schema } from "effect";
import type {
ProviderSettingsFormAnnotation,
ProviderSettingsFormControl,
ProviderSettingsFormSchemaAnnotation,
} from "@t3tools/contracts";
import { cn } from "../../lib/utils";
import { DraftInput } from "../ui/draft-input";
import { Input } from "../ui/input";
import { Switch } from "../ui/switch";
import { Textarea } from "../ui/textarea";
import type { ProviderClientDefinition } from "./providerDriverMeta";
export interface ProviderSettingsFieldModel {
readonly key: string;
readonly control: ProviderSettingsFormControl;
readonly label: string;
readonly description?: string | undefined;
readonly placeholder?: string | undefined;
readonly clearWhenEmpty: "omit" | "persist";
readonly defaultBooleanValue?: boolean | undefined;
}
function titleizeFieldKey(key: string): string {
return key
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[-_]+/g, " ")
.replace(/^./, (char) => char.toUpperCase());
}
function readFieldAnnotations(
fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
) {
return Schema.resolveAnnotationsKey(fieldSchema) ?? Schema.resolveAnnotations(fieldSchema);
}
function readFieldAnnotationString(
fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
key: "title" | "description",
): string | undefined {
const annotations = readFieldAnnotations(fieldSchema);
const value = annotations?.[key];
return typeof value === "string" ? value : undefined;
}
function readProviderSettingsFormAnnotation(
fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
): ProviderSettingsFormAnnotation {
const annotation = readFieldAnnotations(fieldSchema)?.providerSettingsForm;
return annotation ?? {};
}
function readProviderSettingsFormSchemaAnnotation(
definition: ProviderClientDefinition,
): ProviderSettingsFormSchemaAnnotation {
return Schema.resolveAnnotations(definition.settingsSchema)?.providerSettingsFormSchema ?? {};
}
function readFieldBooleanDefault(
fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
): boolean | undefined {
try {
const decoded = Schema.decodeUnknownSync(fieldSchema as Schema.Decoder<unknown>)(undefined);
return typeof decoded === "boolean" ? decoded : undefined;
} catch {
return undefined;
}
}
export function deriveProviderSettingsFields(
definition: ProviderClientDefinition,
): ReadonlyArray<ProviderSettingsFieldModel> {
const schemaAnnotation = readProviderSettingsFormSchemaAnnotation(definition);
const orderedKeys = new Map(
(schemaAnnotation.order ?? []).map((key, index) => [key, index] as const),
);
const orderFallbackOffset = orderedKeys.size;
return Object.keys(definition.settingsSchema.fields)
.map((key, index) => ({ key, index }))
.toSorted((left, right) => {
return (
(orderedKeys.get(left.key) ?? orderFallbackOffset + left.index) -
(orderedKeys.get(right.key) ?? orderFallbackOffset + right.index)
);
})
.flatMap(({ key }) => {
const fieldSchema = definition.settingsSchema.fields[key]!;
const formAnnotation = readProviderSettingsFormAnnotation(fieldSchema);
if (formAnnotation.hidden) return [];
const annotatedTitle = readFieldAnnotationString(fieldSchema, "title");
const annotatedDescription = readFieldAnnotationString(fieldSchema, "description");
return [
{
key,
control: formAnnotation.control ?? "text",
label: annotatedTitle ?? titleizeFieldKey(key),
...(annotatedDescription !== undefined ? { description: annotatedDescription } : {}),
...(formAnnotation.placeholder !== undefined
? { placeholder: formAnnotation.placeholder }
: {}),
clearWhenEmpty: formAnnotation.clearWhenEmpty ?? "omit",
...(formAnnotation.control === "switch"
? { defaultBooleanValue: readFieldBooleanDefault(fieldSchema) }
: {}),
} satisfies ProviderSettingsFieldModel,
];
});
}
export function readProviderConfigString(config: unknown, key: string): string {
if (config === null || typeof config !== "object") return "";
const value = (config as Record<string, unknown>)[key];
return typeof value === "string" ? value : "";
}
export function readProviderConfigBoolean(
config: unknown,
key: string,
defaultValue = false,
): boolean {
if (config === null || typeof config !== "object") return defaultValue;
const value = (config as Record<string, unknown>)[key];
return typeof value === "boolean" ? value : defaultValue;
}
export function nextProviderConfigWithFieldValue(
config: unknown,
field: ProviderSettingsFieldModel,
value: string | boolean,
): Record<string, unknown> | undefined {
const base: Record<string, unknown> =
config !== null && typeof config === "object" ? { ...(config as Record<string, unknown>) } : {};
if (typeof value === "boolean") {
const emptyBooleanValue = field.defaultBooleanValue ?? false;
if (field.clearWhenEmpty === "omit" && value === emptyBooleanValue) {
delete base[field.key];
} else {
base[field.key] = value;
}
return Object.keys(base).length > 0 ? base : undefined;
}
const trimmed = value.trim();
if (field.clearWhenEmpty === "omit" && trimmed.length === 0) {
delete base[field.key];
} else {
base[field.key] = value;
}
return Object.keys(base).length > 0 ? base : undefined;
}
interface ProviderSettingsFormProps {
readonly definition: ProviderClientDefinition;
readonly value: unknown;
readonly idPrefix: string;
readonly variant: "card" | "dialog";
readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
}
function FieldFrame(props: {
readonly variant: ProviderSettingsFormProps["variant"];
readonly children: ReactNode;
}) {
if (props.variant === "card") {
return <div className="border-t border-border/60 px-4 py-3 sm:px-5">{props.children}</div>;
}
return <div className="grid gap-1.5">{props.children}</div>;
}
interface ProviderSettingsFieldRowProps {
readonly field: ProviderSettingsFieldModel;
readonly value: unknown;
readonly idPrefix: string;
readonly variant: ProviderSettingsFormProps["variant"];
readonly onChange: ProviderSettingsFormProps["onChange"];
}
function ProviderSettingsFieldRow({
field,
value,
idPrefix,
variant,
onChange,
}: ProviderSettingsFieldRowProps) {
const inputId = `${idPrefix}-${field.key}`;
const descriptionClassName =
variant === "card"
? "mt-1 block text-xs text-muted-foreground"
: "text-[11px] text-muted-foreground";
const label = <span className="text-xs font-medium text-foreground">{field.label}</span>;
const description = field.description ? (
<span className={descriptionClassName}>{field.description}</span>
) : null;
if (field.control === "switch") {
return (
<FieldFrame variant={variant}>
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
{label}
{description}
</div>
<Switch
checked={readProviderConfigBoolean(value, field.key, field.defaultBooleanValue)}
onCheckedChange={(checked) =>
onChange(nextProviderConfigWithFieldValue(value, field, Boolean(checked)))
}
aria-label={field.label}
/>
</div>
</FieldFrame>
);
}
if (field.control === "textarea") {
return (
<FieldFrame variant={variant}>
<label htmlFor={inputId} className={cn(variant === "card" && "block")}>
{label}
<Textarea
id={inputId}
className={cn(variant === "card" && "mt-1.5")}
value={readProviderConfigString(value, field.key)}
onChange={(event) =>
onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
}
placeholder={field.placeholder}
spellCheck={false}
/>
{description}
</label>
</FieldFrame>
);
}
const type = field.control === "password" ? "password" : undefined;
return (
<FieldFrame variant={variant}>
<label htmlFor={inputId} className={cn(variant === "card" && "block")}>
{label}
{variant === "card" ? (
<DraftInput
id={inputId}
className="mt-1.5"
type={type}
autoComplete={field.control === "password" ? "off" : undefined}
value={readProviderConfigString(value, field.key)}
onCommit={(next) => onChange(nextProviderConfigWithFieldValue(value, field, next))}
placeholder={field.placeholder}
spellCheck={false}
/>
) : (
<Input
id={inputId}
className="bg-background"
type={type}
autoComplete={field.control === "password" ? "off" : undefined}
value={readProviderConfigString(value, field.key)}
onChange={(event) =>
onChange(nextProviderConfigWithFieldValue(value, field, event.target.value))
}
placeholder={field.placeholder}
spellCheck={false}
/>
)}
{description}
</label>
</FieldFrame>
);
}
export function ProviderSettingsForm({
definition,
value,
idPrefix,
variant,
onChange,
}: ProviderSettingsFormProps) {
const fields = useMemo(() => deriveProviderSettingsFields(definition), [definition]);
if (fields.length === 0) {
return null;
}
return (
<>
{fields.map((field) => (
<ProviderSettingsFieldRow
key={field.key}
field={field}
value={value}
idPrefix={idPrefix}
variant={variant}
onChange={onChange}
/>
))}
</>
);
}
@@ -1,6 +1,6 @@
import { ArchiveIcon, ArchiveX, LoaderIcon, PlusIcon, RefreshCwIcon } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";
import { useCallback, useMemo, useRef, useState } from "react";
import {
defaultInstanceIdForDriver,
type DesktopUpdateChannel,
@@ -57,7 +57,7 @@ import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
import { ProviderInstanceCard } from "./ProviderInstanceCard";
import { getDriverOption } from "./providerDriverMeta";
import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
import { buildProviderInstanceUpdatePatch } from "./SettingsPanels.logic";
import {
SettingResetButton,
@@ -113,56 +113,9 @@ function withoutProviderInstanceFavorites(
return favorites.filter((favorite) => favorite.provider !== instanceId);
}
type InstallProviderSettings = {
provider: ProviderDriverKind;
title: string;
badgeLabel?: string;
binaryPlaceholder: string;
binaryDescription: ReactNode;
serverUrlPlaceholder?: string;
serverUrlDescription?: ReactNode;
serverPasswordPlaceholder?: string;
serverPasswordDescription?: ReactNode;
homePathKey?: "codexHomePath";
homePlaceholder?: string;
homeDescription?: ReactNode;
};
const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [
{
provider: ProviderDriverKind.make("codex"),
title: "Codex",
binaryPlaceholder: "Codex binary path",
binaryDescription: "Path to the Codex binary",
homePathKey: "codexHomePath",
homePlaceholder: "CODEX_HOME",
homeDescription: "Optional custom Codex home and config directory.",
},
{
provider: ProviderDriverKind.make("claudeAgent"),
title: "Claude",
binaryPlaceholder: "Claude binary path",
binaryDescription: "Path to the Claude binary",
},
{
provider: ProviderDriverKind.make("cursor"),
title: "Cursor",
badgeLabel: "Early Access",
binaryPlaceholder: "Cursor agent binary path",
binaryDescription: "Path to the Cursor agent binary",
},
{
provider: ProviderDriverKind.make("opencode"),
title: "OpenCode",
binaryPlaceholder: "OpenCode binary path",
binaryDescription: "Path to the OpenCode binary",
serverUrlPlaceholder: "http://127.0.0.1:4096",
serverUrlDescription: "Leave blank to let T3 Code spawn the server when needed",
serverPasswordPlaceholder: "Server password (optional)",
serverPasswordDescription:
"If your OpenCode server requires authentication, enter the password here. NOTE: Stored in plain text on disk",
},
] as const;
const PROVIDER_SETTINGS = DRIVER_OPTIONS.map((definition) => ({
provider: definition.value,
}));
function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
useRelativeTimeTick();
@@ -1,31 +1,28 @@
import { ProviderDriverKind } from "@t3tools/contracts";
import {
ClaudeSettings,
CodexSettings,
CursorSettings,
OpenCodeSettings,
ProviderDriverKind,
} from "@t3tools/contracts";
import type { Schema } from "effect";
import { ClaudeAI, CursorIcon, type Icon, OpenAI, OpenCodeIcon } from "../Icons";
/**
* A single editable field exposed on a provider instance. `key` must match
* the corresponding driver config schema in
* `packages/contracts/src/settings.ts` — values are merged into the saved
* `ProviderInstanceConfig.config` blob (or the legacy
* `ServerSettings.providers[kind]` struct) under this key verbatim.
*/
export interface DriverFieldDef {
readonly key: string;
readonly label: string;
readonly placeholder?: string;
readonly description?: string;
readonly type?: "text" | "password";
}
type ProviderSettingsSchema = {
readonly fields: Readonly<Record<string, Schema.Top>>;
} & Schema.Top;
/**
* Presentation + editable-field metadata for a registered driver. Shared
* between the Add-Instance dialog and the per-instance settings card so
* both surfaces offer the same keys for the same driver.
* Browser-safe provider definition. This is deliberately shaped like the
* future provider package client export: the core web app gets a schema with
* field annotations plus provider-level presentation metadata, then renders
* settings generically.
*/
export interface DriverOption {
export interface ProviderClientDefinition {
readonly value: ProviderDriverKind;
readonly label: string;
readonly icon: Icon;
readonly fields: readonly DriverFieldDef[];
readonly settingsSchema: ProviderSettingsSchema;
/**
* Optional short label rendered as a `variant="warning"` badge next to
* the instance title. Used to flag drivers that still ship under an
@@ -36,109 +33,43 @@ export interface DriverOption {
readonly badgeLabel?: string;
}
export const DRIVER_OPTIONS: readonly DriverOption[] = [
export const PROVIDER_CLIENT_DEFINITIONS: readonly ProviderClientDefinition[] = [
{
value: ProviderDriverKind.make("codex"),
label: "Codex",
icon: OpenAI,
fields: [
{
key: "binaryPath",
label: "Binary path",
placeholder: "codex",
description: "Path to the Codex binary used by this instance.",
},
{
key: "homePath",
label: "CODEX_HOME path",
placeholder: "~/.codex",
description: "Custom Codex home and config directory.",
},
{
key: "shadowHomePath",
label: "Shadow home path",
placeholder: "~/.codex-t3/personal",
description:
"Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.",
},
],
settingsSchema: CodexSettings,
},
{
value: ProviderDriverKind.make("claudeAgent"),
label: "Claude",
icon: ClaudeAI,
fields: [
{
key: "binaryPath",
label: "Binary path",
placeholder: "claude",
description: "Path to the Claude binary used by this instance.",
},
{
key: "homePath",
label: "Claude HOME path",
placeholder: "~",
description:
"Custom HOME used when running this Claude instance. Keeps .claude.json and .claude separate.",
},
{
key: "launchArgs",
label: "Launch arguments",
placeholder: "e.g. --chrome",
description: "Additional CLI arguments passed on session start.",
},
],
settingsSchema: ClaudeSettings,
},
{
value: ProviderDriverKind.make("cursor"),
label: "Cursor",
icon: CursorIcon,
badgeLabel: "Early Access",
fields: [
{
key: "binaryPath",
label: "Binary path",
placeholder: "agent",
description: "Path to the Cursor agent binary.",
},
{
key: "apiEndpoint",
label: "API endpoint",
placeholder: "https://…",
description: "Override the Cursor API endpoint for this instance.",
},
],
settingsSchema: CursorSettings,
},
{
value: ProviderDriverKind.make("opencode"),
label: "OpenCode",
icon: OpenCodeIcon,
fields: [
{
key: "binaryPath",
label: "Binary path",
placeholder: "opencode",
description: "Path to the OpenCode binary.",
},
{
key: "serverUrl",
label: "Server URL",
placeholder: "http://127.0.0.1:4096",
description: "Leave blank to let T3 Code spawn the server when needed.",
},
{
key: "serverPassword",
label: "Server password",
placeholder: "Optional",
type: "password",
description: "Stored in plain text on disk.",
},
],
settingsSchema: OpenCodeSettings,
},
];
export const DRIVER_OPTION_BY_VALUE: Partial<Record<ProviderDriverKind, DriverOption>> =
Object.fromEntries(DRIVER_OPTIONS.map((option) => [option.value, option]));
export const PROVIDER_CLIENT_DEFINITION_BY_VALUE: Partial<
Record<ProviderDriverKind, ProviderClientDefinition>
> = Object.fromEntries(
PROVIDER_CLIENT_DEFINITIONS.map((definition) => [definition.value, definition]),
);
export const DRIVER_OPTIONS = PROVIDER_CLIENT_DEFINITIONS;
export const DRIVER_OPTION_BY_VALUE = PROVIDER_CLIENT_DEFINITION_BY_VALUE;
export type DriverOption = ProviderClientDefinition;
/**
* Look up the driver metadata for an instance's `driver` field. Accepts
@@ -147,5 +78,5 @@ export const DRIVER_OPTION_BY_VALUE: Partial<Record<ProviderDriverKind, DriverOp
*/
export function getDriverOption(driver: ProviderDriverKind | undefined): DriverOption | undefined {
if (driver === undefined) return undefined;
return DRIVER_OPTION_BY_VALUE[driver];
return PROVIDER_CLIENT_DEFINITION_BY_VALUE[driver];
}
+209 -27
View File
@@ -96,38 +96,220 @@ const makeBinaryPathSetting = (fallback: string) =>
Schema.withDecodingDefault(Effect.succeed(fallback)),
);
export const CodexSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
binaryPath: makeBinaryPathSetting("codex"),
homePath: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
shadowHomePath: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
});
export type ProviderSettingsFormControl = "text" | "password" | "textarea" | "switch";
export interface ProviderSettingsFormAnnotation {
readonly control?: ProviderSettingsFormControl | undefined;
readonly placeholder?: string | undefined;
readonly hidden?: boolean | undefined;
readonly clearWhenEmpty?: "omit" | "persist" | undefined;
}
export interface ProviderSettingsFormSchemaAnnotation {
readonly order?: readonly string[] | undefined;
}
declare module "effect/Schema" {
namespace Annotations {
interface Annotations {
readonly providerSettingsForm?: ProviderSettingsFormAnnotation | undefined;
readonly providerSettingsFormSchema?: ProviderSettingsFormSchemaAnnotation | undefined;
}
}
}
export type ProviderSettingsOrder<Fields extends Schema.Struct.Fields> = readonly Extract<
keyof Fields,
string
>[];
export function makeProviderSettingsSchema<const Fields extends Schema.Struct.Fields>(
fields: Fields,
options?: {
readonly order?: ProviderSettingsOrder<Fields> | undefined;
},
): Schema.Struct<Fields> {
return Schema.Struct(fields).pipe(
Schema.annotate({
providerSettingsFormSchema:
options?.order === undefined ? undefined : { order: options.order },
}),
);
}
export const CodexSettings = makeProviderSettingsSchema(
{
enabled: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(true)),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
binaryPath: makeBinaryPathSetting("codex").pipe(
Schema.annotateKey({
title: "Binary path",
description: "Path to the Codex binary used by this instance.",
providerSettingsForm: { placeholder: "codex", clearWhenEmpty: "omit" },
}),
),
homePath: TrimmedString.pipe(
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "CODEX_HOME path",
description: "Custom Codex home and config directory.",
providerSettingsForm: {
placeholder: "~/.codex",
clearWhenEmpty: "omit",
},
}),
),
shadowHomePath: TrimmedString.pipe(
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "Shadow home path",
description:
"Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.",
providerSettingsForm: {
placeholder: "~/.codex-t3/personal",
clearWhenEmpty: "omit",
},
}),
),
customModels: Schema.Array(Schema.String).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
},
{
order: ["binaryPath", "homePath", "shadowHomePath"],
},
);
export type CodexSettings = typeof CodexSettings.Type;
export const ClaudeSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
binaryPath: makeBinaryPathSetting("claude"),
homePath: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
launchArgs: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
});
export const ClaudeSettings = makeProviderSettingsSchema(
{
enabled: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(true)),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
binaryPath: makeBinaryPathSetting("claude").pipe(
Schema.annotateKey({
title: "Binary path",
description: "Path to the Claude binary used by this instance.",
providerSettingsForm: { placeholder: "claude", clearWhenEmpty: "omit" },
}),
),
homePath: TrimmedString.pipe(
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "Claude HOME path",
description:
"Custom HOME used when running this Claude instance. Keeps .claude.json and .claude separate.",
providerSettingsForm: { placeholder: "~", clearWhenEmpty: "omit" },
}),
),
customModels: Schema.Array(Schema.String).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
launchArgs: Schema.String.pipe(
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "Launch arguments",
description: "Additional CLI arguments passed on session start.",
providerSettingsForm: {
placeholder: "e.g. --chrome",
clearWhenEmpty: "omit",
},
}),
),
},
{
order: ["binaryPath", "homePath", "launchArgs"],
},
);
export type ClaudeSettings = typeof ClaudeSettings.Type;
export const CursorSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
binaryPath: makeBinaryPathSetting("agent"),
apiEndpoint: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
});
export const CursorSettings = makeProviderSettingsSchema(
{
enabled: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
binaryPath: makeBinaryPathSetting("agent").pipe(
Schema.annotateKey({
title: "Binary path",
description: "Path to the Cursor agent binary.",
providerSettingsForm: { placeholder: "agent", clearWhenEmpty: "omit" },
}),
),
apiEndpoint: TrimmedString.pipe(
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "API endpoint",
description: "Override the Cursor API endpoint for this instance.",
providerSettingsForm: {
placeholder: "https://...",
clearWhenEmpty: "omit",
},
}),
),
customModels: Schema.Array(Schema.String).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
},
{
order: ["binaryPath", "apiEndpoint"],
},
);
export type CursorSettings = typeof CursorSettings.Type;
export const OpenCodeSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
binaryPath: makeBinaryPathSetting("opencode"),
serverUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
serverPassword: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
});
export const OpenCodeSettings = makeProviderSettingsSchema(
{
enabled: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(true)),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
binaryPath: makeBinaryPathSetting("opencode").pipe(
Schema.annotateKey({
title: "Binary path",
description: "Path to the OpenCode binary.",
providerSettingsForm: {
placeholder: "opencode",
clearWhenEmpty: "omit",
},
}),
),
serverUrl: TrimmedString.pipe(
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "Server URL",
description: "Leave blank to let T3 Code spawn the server when needed.",
providerSettingsForm: {
placeholder: "http://127.0.0.1:4096",
clearWhenEmpty: "omit",
},
}),
),
serverPassword: TrimmedString.pipe(
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "Server password",
description: "Stored in plain text on disk.",
providerSettingsForm: {
control: "password",
placeholder: "Optional",
clearWhenEmpty: "omit",
},
}),
),
customModels: Schema.Array(Schema.String).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
},
{
order: ["binaryPath", "serverUrl", "serverPassword"],
},
);
export type OpenCodeSettings = typeof OpenCodeSettings.Type;
export const ObservabilitySettings = Schema.Struct({