feat: add custom model names and option descriptors (#9807)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-04 16:11:20 -07:00
1 parent dd7bc147f7
commit 5a433244d0
19 files changed
+1423 -150

No files matched your search

@@ -7,9 +7,11 @@ import {
formatClaudeVersionUpgradeMessage,
normalizeClaudeCatalogEffort,
resolveClaudeCatalogApiModelId,
resolveClaudeCatalogEffort,
resolveClaudeModelCatalog,
resolveClaudeModelsForVersion,
resolveClaudeModelSlug,
scopeClaudeModelCatalog,
} from "./ClaudeModelCatalog.ts";
/**
@@ -134,4 +136,58 @@ describe("Claude model catalog", () => {
};
assert.isFalse(hasValidClaudeManifestAdapters(malformed));
});
it("appends custom models with their own descriptors and keeps bare slugs opaque", () => {
const catalog = scopeClaudeModelCatalog(resolveClaudeModelCatalog(manifest()), [
"synthetic",
{
slug: "claude-custom-tuned",
name: "Tuned",
capabilities: {
optionDescriptors: [
{
id: "effort",
label: "Reasoning",
type: "select",
options: [
{ id: "gentle", label: "Gentle", isDefault: true },
{ id: "brutal", label: "Brutal" },
],
},
],
},
},
]);
// The bare custom slug shadows the built-in alias, so it no longer resolves to it.
assert.strictEqual(resolveClaudeModelSlug(catalog, "synthetic"), "synthetic");
assert.strictEqual(resolveClaudeCatalogEffort(catalog, "synthetic", "extreme"), undefined);
// The entry with descriptors resolves user-defined effort ids and passes
// them through untouched (no effortMap, no model suffix).
assert.strictEqual(
resolveClaudeCatalogEffort(catalog, "claude-custom-tuned", "brutal"),
"brutal",
);
assert.strictEqual(
resolveClaudeCatalogEffort(catalog, "claude-custom-tuned", "bogus"),
"gentle",
);
assert.strictEqual(
normalizeClaudeCatalogEffort(catalog, "brutal", "claude-custom-tuned"),
"brutal",
);
assert.strictEqual(
resolveClaudeCatalogApiModelId(catalog, {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-custom-tuned",
options: [{ id: "effort", value: "brutal" }],
}),
"claude-custom-tuned",
);
assert.deepStrictEqual(
resolveClaudeModelsForVersion(catalog, "3.2.0").map((model) => model.slug),
["claude-synthetic-next", "claude-custom-tuned"],
);
});
});
+43 -24
View File
@@ -1,4 +1,5 @@
import {
type CustomModelSetting,
type ModelCapabilities,
type ModelSelection,
ProviderDriverKind,
@@ -9,7 +10,7 @@ import {
getModelSelectionStringOptionValue,
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
normalizeCustomModelSlug,
readCustomModelEntries,
} from "@t3tools/shared/model";
import { compareSemverVersions } from "@t3tools/shared/semver";
@@ -70,33 +71,51 @@ export function resolveClaudeModelCatalog(manifest: ModelManifestData): ClaudeMo
export const BUNDLED_CLAUDE_MODEL_CATALOG = resolveClaudeModelCatalog(BUNDLED_MODEL_MANIFEST);
/** Keeps custom model aliases opaque while preserving canonical built-in models and capabilities. */
/**
* Scope the catalog to one instance's settings: custom model slugs stay opaque
* (a built-in alias they shadow is dropped, canonical slugs and capabilities
* are preserved), and custom entries that declare their own capabilities are
* appended so the adapter resolves effort / fast mode / thinking against the
* user's descriptors instead of the empty default. Custom entries carry no
* runtime profile, so option values pass through to Claude Code verbatim.
*/
export function scopeClaudeModelCatalog(
catalog: ClaudeModelCatalog,
customModels: ReadonlyArray<string>,
customModels: ReadonlyArray<CustomModelSetting>,
): ClaudeModelCatalog {
const customAliases = new Set(
customModels.flatMap((model) => {
const slug = normalizeCustomModelSlug(model);
return slug ? [slug.toLowerCase()] : [];
}),
);
if (customAliases.size === 0) return catalog;
const customEntries = readCustomModelEntries(customModels);
if (customEntries.length === 0) return catalog;
const customAliases = new Set(customEntries.map((entry) => entry.slug.toLowerCase()));
return {
models: catalog.models.map((entry) => {
if (!entry.model.aliases?.some((alias) => customAliases.has(alias.toLowerCase()))) {
return entry;
}
return {
...entry,
model: {
...entry.model,
aliases: entry.model.aliases.filter((alias) => !customAliases.has(alias.toLowerCase())),
},
};
}),
};
const builtInModels = catalog.models.map((entry) => {
if (!entry.model.aliases?.some((alias) => customAliases.has(alias.toLowerCase()))) {
return entry;
}
return {
...entry,
model: {
...entry.model,
aliases: entry.model.aliases.filter((alias) => !customAliases.has(alias.toLowerCase())),
},
};
});
const builtInSlugs = new Set(builtInModels.map((entry) => entry.model.slug));
const customCatalogModels: Array<ClaudeCatalogModel> = [];
for (const entry of customEntries) {
if (!entry.capabilities || builtInSlugs.has(entry.slug)) continue;
customCatalogModels.push({
model: {
slug: entry.slug,
name: entry.name,
isCustom: true,
capabilities: entry.capabilities,
},
runtime: {},
compatibility: {},
});
}
return { models: [...builtInModels, ...customCatalogModels] };
}
export function resolveClaudeCatalogModel(
@@ -15,6 +15,7 @@ import * as CodexErrors from "effect-codex-app-server/errors";
import type {
CodexSettings,
CustomModelSetting,
ServerProvider,
ServerProviderState,
ModelCapabilities,
@@ -24,7 +25,7 @@ import type {
} from "@t3tools/contracts";
import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { createModelCapabilities, readCustomModelEntries } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts";
import {
@@ -244,9 +245,14 @@ export function applyPreferredCodexDefaultModel(
});
}
/**
* Codex has no static default capability set, so a bare custom slug borrows
* the first built-in's descriptors; an entry with its own capabilities keeps
* them.
*/
function appendCustomCodexModels(
models: ReadonlyArray<ServerProviderModel>,
customModels: ReadonlyArray<string>,
customModels: ReadonlyArray<CustomModelSetting>,
): ReadonlyArray<ServerProviderModel> {
if (customModels.length === 0) {
return models;
@@ -255,17 +261,16 @@ function appendCustomCodexModels(
const seen = new Set(models.map((model) => model.slug));
const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;
const customEntries: ServerProviderModel[] = [];
for (const rawModel of customModels) {
const slug = rawModel.trim();
if (!slug || seen.has(slug)) {
for (const entry of readCustomModelEntries(customModels)) {
if (seen.has(entry.slug)) {
continue;
}
seen.add(slug);
seen.add(entry.slug);
customEntries.push({
slug,
name: slug,
slug: entry.slug,
name: entry.name,
isCustom: true,
capabilities: fallbackCapabilities,
capabilities: entry.capabilities ?? fallbackCapabilities,
});
}
return customEntries.length === 0 ? models : [...models, ...customEntries];
@@ -399,7 +404,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
readonly homePath?: string;
readonly launchArgs?: string;
readonly cwd: string;
readonly customModels?: ReadonlyArray<string>;
readonly customModels?: ReadonlyArray<CustomModelSetting>;
readonly environment?: NodeJS.ProcessEnv;
}) {
const { client, initialize } = yield* withCodexAppServerClient(input);
@@ -470,21 +475,8 @@ export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(functi
return parseCodexSkillsListResponse(skillsResponse, input.cwd);
});
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => {
const models = new Set<string>();
for (const model of codexSettings.customModels) {
const trimmed = model.trim();
if (trimmed.length > 0) {
models.add(trimmed);
}
}
return Array.from(models, (model) => ({
slug: model,
name: model,
isCustom: true,
capabilities: null,
}));
};
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
appendCustomCodexModels([], codexSettings.customModels);
const makePendingCodexProvider = (
codexSettings: CodexSettings,
@@ -562,7 +554,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
readonly homePath?: string;
readonly launchArgs?: string;
readonly cwd: string;
readonly customModels: ReadonlyArray<string>;
readonly customModels: ReadonlyArray<CustomModelSetting>;
readonly environment?: NodeJS.ProcessEnv;
}) => Effect.Effect<
CodexAppServerProviderSnapshot,
@@ -1,4 +1,5 @@
import {
type CustomModelSetting,
type GrokSettings,
type ModelCapabilities,
type ServerProvider,
@@ -104,7 +105,7 @@ export function buildInitialGrokProviderSnapshot(
}
function grokModelsFromSettings(
customModels: ReadonlyArray<string> | undefined,
customModels: ReadonlyArray<CustomModelSetting> | undefined,
builtInModels: ReadonlyArray<ServerProviderModel> = GROK_BUILT_IN_MODELS,
): ReadonlyArray<ServerProviderModel> {
return providerModelsFromSettings(builtInModels, customModels ?? [], EMPTY_CAPABILITIES);
@@ -52,6 +52,27 @@ describe("providerModelsFromSettings", () => {
]);
});
it("keeps an entry's own name and capabilities over the driver default", () => {
const capabilities = createModelCapabilities({
optionDescriptors: [{ id: "fastMode", label: "Fast Mode", type: "boolean" }],
});
const models = providerModelsFromSettings(
[],
["bare", { slug: "named", name: "Named", capabilities }],
OPENCODE_CUSTOM_MODEL_CAPABILITIES,
);
expect(models).toEqual([
{
slug: "bare",
name: "bare",
isCustom: true,
capabilities: OPENCODE_CUSTOM_MODEL_CAPABILITIES,
},
{ slug: "named", name: "Named", isCustom: true, capabilities },
]);
});
it("preserves a custom slug that collides with a provider alias", () => {
const capabilities = createModelCapabilities({ optionDescriptors: [] });
const models = providerModelsFromSettings(
+14 -9
View File
@@ -1,4 +1,5 @@
import type {
CustomModelSetting,
ProviderDriverKind,
ModelCapabilities,
ServerProvider,
@@ -14,7 +15,7 @@ import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { normalizeCustomModelSlug } from "@t3tools/shared/model";
import { readCustomModelEntries } from "@t3tools/shared/model";
import { isWindowsCommandNotFound } from "../processRunner.ts";
import { createProviderVersionAdvisory } from "./providerMaintenance.ts";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
@@ -145,26 +146,30 @@ export function parseGenericCliVersion(output: string): string | null {
return match?.[1] ?? null;
}
/**
* Append the user's custom models after the built-ins. A custom entry that
* declares its own capabilities keeps them; a bare slug gets the driver's
* default set. Slugs that collide with a built-in are dropped.
*/
export function providerModelsFromSettings(
builtInModels: ReadonlyArray<ServerProviderModel>,
customModels: ReadonlyArray<string>,
customModels: ReadonlyArray<CustomModelSetting>,
customModelCapabilities: ModelCapabilities,
): ReadonlyArray<ServerProviderModel> {
const resolvedBuiltInModels = [...builtInModels];
const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
const customEntries: ServerProviderModel[] = [];
for (const candidate of customModels) {
const normalized = normalizeCustomModelSlug(candidate);
if (!normalized || seen.has(normalized)) {
for (const entry of readCustomModelEntries(customModels)) {
if (seen.has(entry.slug)) {
continue;
}
seen.add(normalized);
seen.add(entry.slug);
customEntries.push({
slug: normalized,
name: normalized,
slug: entry.slug,
name: entry.name,
isCustom: true,
capabilities: customModelCapabilities,
capabilities: entry.capabilities ?? customModelCapabilities,
});
}
@@ -0,0 +1,387 @@
"use client";
import { PlusIcon, XIcon } from "lucide-react";
import { useMemo, useState } from "react";
import type { ProviderDriverKind, ServerProviderModel } from "@t3tools/contracts";
import type { CustomModelDefinition } from "@t3tools/shared/model";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
import {
DESCRIPTOR_PRESETS_BY_KIND,
type CustomModelDraft,
type EditorChoice,
type EditorDescriptor,
choiceFromPreset,
definitionFromDraft,
descriptorFromPreset,
descriptorsFromCapabilities,
draftFromDefinition,
emptyEditorChoice,
emptyEditorDescriptor,
validateDraft,
} from "./customModelEditor.logic";
const CUSTOM_ID_VALUE = "__custom__";
const START_FROM_NONE = "__none__";
interface CustomModelEditorProps {
readonly instanceId: string;
readonly driverKind: ProviderDriverKind | null;
readonly entry: CustomModelDefinition;
/** Built-in models whose descriptors can be copied as a starting point. */
readonly builtInModels: ReadonlyArray<ServerProviderModel>;
readonly onSave: (next: CustomModelDefinition) => void;
readonly onCancel: () => void;
}
/**
* Inline editor for one custom model: display name plus the option
* descriptors the composer should offer for it (Reasoning effort, Fast
* mode, ...). Draft state is local; nothing is persisted until Save.
*/
export function CustomModelEditor({
instanceId,
driverKind,
entry,
builtInModels,
onSave,
onCancel,
}: CustomModelEditorProps) {
const [draft, setDraft] = useState<CustomModelDraft>(() => draftFromDefinition(entry));
const [error, setError] = useState<string | null>(null);
const presets = useMemo(
() => (driverKind ? (DESCRIPTOR_PRESETS_BY_KIND[driverKind] ?? []) : []),
[driverKind],
);
const startFromCandidates = useMemo(
() => builtInModels.filter((model) => (model.capabilities?.optionDescriptors?.length ?? 0) > 0),
[builtInModels],
);
const domId = (suffix: string) => `provider-instance-${instanceId}-custom-model-${suffix}`;
const updateDescriptor = (key: string, patch: Partial<EditorDescriptor>) => {
setError(null);
setDraft((current) => ({
...current,
descriptors: current.descriptors.map((descriptor) =>
descriptor.key === key ? { ...descriptor, ...patch } : descriptor,
),
}));
};
const updateChoice = (descriptorKey: string, choiceKey: string, patch: Partial<EditorChoice>) => {
setError(null);
setDraft((current) => ({
...current,
descriptors: current.descriptors.map((descriptor) => {
if (descriptor.key !== descriptorKey) return descriptor;
return {
...descriptor,
choices: descriptor.choices.map((choice) => {
if (choice.key === choiceKey) return { ...choice, ...patch };
// Only one choice can be the default.
return patch.isDefault ? { ...choice, isDefault: false } : choice;
}),
};
}),
}));
};
const removeDescriptor = (key: string) => {
setError(null);
setDraft((current) => ({
...current,
descriptors: current.descriptors.filter((descriptor) => descriptor.key !== key),
}));
};
const addDescriptor = (descriptor: EditorDescriptor) => {
setError(null);
setDraft((current) => ({ ...current, descriptors: [...current.descriptors, descriptor] }));
};
// Selecting a preset id replaces the descriptor's label/type/choices so the
// usual values are one click away; "Custom…" leaves the row blank to type into.
const applyPresetId = (descriptor: EditorDescriptor, value: string | null) => {
if (value === null) return;
if (value === CUSTOM_ID_VALUE) {
updateDescriptor(descriptor.key, { id: "" });
return;
}
const preset = presets.find((candidate) => candidate.id === value);
if (!preset) return;
updateDescriptor(descriptor.key, {
id: preset.id,
label: preset.label,
type: preset.type,
choices: (preset.choices ?? []).map(choiceFromPreset),
currentBooleanValue: undefined,
description: undefined,
});
};
const handleStartFrom = (slug: string | null) => {
if (slug === null || slug === START_FROM_NONE) return;
const model = startFromCandidates.find((candidate) => candidate.slug === slug);
if (!model) return;
setError(null);
setDraft((current) => ({
...current,
descriptors: descriptorsFromCapabilities(model.capabilities, driverKind),
}));
};
const handleSave = () => {
const problem = validateDraft(draft);
if (problem) {
setError(problem);
return;
}
onSave(definitionFromDraft(draft));
};
const idSelectValue = (descriptor: EditorDescriptor) =>
presets.some((preset) => preset.id === descriptor.id) ? descriptor.id : CUSTOM_ID_VALUE;
const renderChoice = (descriptor: EditorDescriptor, choice: EditorChoice) => (
<div key={choice.key} className="flex items-center gap-2">
<Input
size="compact"
value={choice.id}
onChange={(event) => updateChoice(descriptor.key, choice.key, { id: event.target.value })}
placeholder="value"
className="w-28 font-mono"
spellCheck={false}
aria-label="Choice value"
/>
<Input
size="compact"
value={choice.label}
onChange={(event) =>
updateChoice(descriptor.key, choice.key, { label: event.target.value })
}
placeholder="Label"
className="min-w-0 flex-1"
aria-label="Choice label"
/>
<label className="flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground">
<Switch
size="sm"
checked={choice.isDefault}
onCheckedChange={(checked) =>
updateChoice(descriptor.key, choice.key, { isDefault: checked })
}
aria-label="Default choice"
/>
Default
</label>
<Button
size="icon-micro"
variant="ghost-muted"
aria-label="Remove choice"
onClick={() =>
updateDescriptor(descriptor.key, {
choices: descriptor.choices.filter((candidate) => candidate.key !== choice.key),
})
}
>
<XIcon className="size-3" />
</Button>
</div>
);
const renderDescriptor = (descriptor: EditorDescriptor, index: number) => (
<div
key={descriptor.key}
className="flex flex-col gap-2 rounded-md border border-border/60 bg-background/40 p-2.5"
>
<div className="flex flex-wrap items-center gap-2">
<span className="w-14 shrink-0 text-[11px] text-muted-foreground">Option {index + 1}</span>
{presets.length > 0 ? (
<Select
value={idSelectValue(descriptor)}
onValueChange={(value) => applyPresetId(descriptor, value)}
>
<SelectTrigger size="compact" className="w-40" aria-label="Option id">
<SelectValue>
{idSelectValue(descriptor) === CUSTOM_ID_VALUE ? "Custom…" : descriptor.id}
</SelectValue>
</SelectTrigger>
<SelectPopup align="start" alignItemWithTrigger={false}>
{presets.map((preset) => (
<SelectItem key={preset.id} value={preset.id}>
<span className="flex items-baseline gap-2">
<code className="font-mono text-xs">{preset.id}</code>
<span className="text-muted-foreground">{preset.label}</span>
</span>
</SelectItem>
))}
<SelectItem value={CUSTOM_ID_VALUE}>Custom…</SelectItem>
</SelectPopup>
</Select>
) : null}
{idSelectValue(descriptor) === CUSTOM_ID_VALUE ? (
<Input
size="compact"
value={descriptor.id}
onChange={(event) => updateDescriptor(descriptor.key, { id: event.target.value })}
placeholder="optionId"
className="w-36 font-mono"
spellCheck={false}
aria-label="Option id"
/>
) : null}
<Input
size="compact"
value={descriptor.label}
onChange={(event) => updateDescriptor(descriptor.key, { label: event.target.value })}
placeholder="Label"
className="min-w-0 flex-1"
aria-label="Option label"
/>
<Select
value={descriptor.type}
onValueChange={(value) =>
updateDescriptor(descriptor.key, { type: value === "boolean" ? "boolean" : "select" })
}
>
<SelectTrigger size="compact" className="w-24" aria-label="Option type">
<SelectValue>{descriptor.type === "boolean" ? "Toggle" : "Choices"}</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem value="select">Choices</SelectItem>
<SelectItem value="boolean">Toggle</SelectItem>
</SelectPopup>
</Select>
<Button
size="icon-micro"
variant="ghost-muted"
aria-label={`Remove option ${index + 1}`}
onClick={() => removeDescriptor(descriptor.key)}
>
<XIcon className="size-3" />
</Button>
</div>
{descriptor.type === "select" ? (
<div className="flex flex-col gap-1.5 pl-16">
{descriptor.choices.map((choice) => renderChoice(descriptor, choice))}
<Button
type="button"
size="xs"
variant="ghost-muted"
className="-ml-2 self-start"
onClick={() =>
updateDescriptor(descriptor.key, {
choices: [...descriptor.choices, emptyEditorChoice()],
})
}
>
<PlusIcon className="size-3" />
Add choice
</Button>
</div>
) : null}
</div>
);
return (
<div
className="mx-2 mt-1 mb-2 flex flex-col gap-3 rounded-md border border-border bg-muted/20 p-3"
onKeyDown={(event) => {
if (event.key === "Escape") {
event.preventDefault();
onCancel();
}
}}
>
<div className="flex flex-col gap-1">
<label htmlFor={domId("name")} className="text-xs text-muted-foreground">
Display name
</label>
<Input
id={domId("name")}
size="sm"
autoFocus
value={draft.name}
onChange={(event) => setDraft((current) => ({ ...current, name: event.target.value }))}
placeholder={draft.slug}
className="sm:w-72"
spellCheck={false}
/>
</div>
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-xs text-muted-foreground">Options shown in the composer</span>
{startFromCandidates.length > 0 ? (
<Select value={START_FROM_NONE} onValueChange={handleStartFrom}>
<SelectTrigger
size="compact"
className="w-44"
aria-label="Copy options from a built-in model"
>
<SelectValue>Copy from…</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{startFromCandidates.map((model) => (
<SelectItem key={model.slug} value={model.slug}>
{model.name}
</SelectItem>
))}
</SelectPopup>
</Select>
) : null}
</div>
{draft.descriptors.length === 0 ? (
<p className="text-xs text-muted-foreground/70">
No custom options. The composer uses the provider's default options.
</p>
) : null}
{draft.descriptors.map(renderDescriptor)}
<div className="flex flex-wrap gap-1">
{presets
.filter(
(preset) => !draft.descriptors.some((descriptor) => descriptor.id === preset.id),
)
.map((preset) => (
<Button
key={preset.id}
type="button"
size="xs"
variant="ghost-muted"
className={cn("-ml-2 first:ml-0")}
onClick={() => addDescriptor(descriptorFromPreset(preset))}
>
<PlusIcon className="size-3" />
{preset.label}
</Button>
))}
<Button
type="button"
size="xs"
variant="ghost-muted"
onClick={() => addDescriptor(emptyEditorDescriptor())}
>
<PlusIcon className="size-3" />
Custom option
</Button>
</div>
</div>
{error ? <p className="text-xs text-destructive">{error}</p> : null}
<div className="flex gap-2">
<Button size="sm" variant="outline" onClick={handleSave}>
Save
</Button>
<Button size="sm" variant="ghost" onClick={onCancel}>
Cancel
</Button>
</div>
</div>
);
}
@@ -36,11 +36,52 @@ describe("deriveProviderModelsForDisplay", () => {
expect(
deriveProviderModelsForDisplay({
liveModels,
customModels: ["kept-custom"],
customModels: [{ slug: "kept-custom", name: "kept-custom", capabilities: null }],
}).map((model) => model.slug),
).toEqual(["server-model", "kept-custom"]);
});
it("prefers the entry's name and capabilities over the stale live custom row", () => {
const liveCapabilities = { optionDescriptors: [] };
const customCapabilities = {
optionDescriptors: [
{
id: "reasoningEffort",
label: "Reasoning",
type: "select" as const,
options: [{ id: "high", label: "High", isDefault: true }],
currentValue: "high",
},
],
};
const liveModels: ReadonlyArray<ServerProviderModel> = [
{ slug: "bare", name: "bare", isCustom: true, capabilities: liveCapabilities },
{ slug: "named", name: "named", isCustom: true, capabilities: liveCapabilities },
];
const display = deriveProviderModelsForDisplay({
liveModels,
customModels: [
{ slug: "bare", name: "bare", capabilities: null },
{ slug: "named", name: "My Model", capabilities: customCapabilities },
],
});
// A bare entry keeps the driver default the server filled in.
expect(display[0]).toEqual({
slug: "bare",
name: "bare",
isCustom: true,
capabilities: liveCapabilities,
});
expect(display[1]).toEqual({
slug: "named",
name: "My Model",
isCustom: true,
capabilities: customCapabilities,
});
});
it("shows a redacted provider email in the editor header status line", () => {
const instanceId = ProviderInstanceId.make("codex");
const driver = ProviderDriverKind.make("codex");
@@ -25,6 +25,11 @@ import {
type ServerProviderModel,
} from "@t3tools/contracts";
import {
type CustomModelDefinition,
readCustomModelEntries,
toCustomModelSetting,
} from "@t3tools/shared/model";
import { cn } from "../../lib/utils";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { normalizeProviderAccentColor } from "../../providerInstances";
@@ -96,16 +101,13 @@ function providerEnvironmentsEqual(
}
/**
* Read a string[] at `key` from the opaque config blob, filtering out
* non-string entries. Used for `customModels`, which is always typed as
* `string[]` by the concrete driver schemas but arrives here as
* `Schema.Unknown`.
* Read `customModels` from the opaque config blob. The concrete driver
* schemas type it as `CustomModelSetting[]`, but it arrives here as
* `Schema.Unknown`, so the shared reader does the shape checking.
*/
function readConfigStringArray(config: unknown, key: string): ReadonlyArray<string> {
function readConfigCustomModels(config: unknown): ReadonlyArray<CustomModelDefinition> {
if (config === null || typeof config !== "object") return [];
const value = (config as Record<string, unknown>)[key];
if (!Array.isArray(value)) return [];
return value.filter((entry): entry is string => typeof entry === "string");
return readCustomModelEntries((config as Record<string, unknown>).customModels);
}
/**
@@ -127,9 +129,14 @@ function nextConfigBlobWithValue(
return base;
}
/**
* Custom rows come from current settings so name/descriptor edits show
* instantly; a bare entry falls back to the live row's driver-default
* capabilities (the server fills those in on its next probe).
*/
export function deriveProviderModelsForDisplay(input: {
readonly liveModels: ReadonlyArray<ServerProviderModel> | undefined;
readonly customModels: ReadonlyArray<string>;
readonly customModels: ReadonlyArray<CustomModelDefinition>;
}): ReadonlyArray<ServerProviderModel> {
const liveCustomModelsBySlug = new Map(
Arr.filterMap(input.liveModels ?? [], (model) =>
@@ -137,15 +144,13 @@ export function deriveProviderModelsForDisplay(input: {
),
);
const serverModels = input.liveModels?.filter((model) => !model.isCustom) ?? [];
const customModels = input.customModels.map(
(slug) =>
liveCustomModelsBySlug.get(slug) ?? {
slug,
name: slug,
isCustom: true,
capabilities: null,
},
);
const customModels = input.customModels.map((entry) => ({
slug: entry.slug,
name: entry.name,
isCustom: true,
capabilities:
entry.capabilities ?? liveCustomModelsBySlug.get(entry.slug)?.capabilities ?? null,
}));
return [...serverModels, ...customModels];
}
@@ -463,7 +468,7 @@ export function ProviderInstanceCard({
? instance.driver
: null;
const customModels =
instance.driver === "antigravity" ? [] : readConfigStringArray(instance.config, "customModels");
instance.driver === "antigravity" ? [] : readConfigCustomModels(instance.config);
// 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.
@@ -504,8 +509,12 @@ export function ProviderInstanceCard({
);
};
const updateCustomModels = (next: ReadonlyArray<string>) => {
const nextConfig = nextConfigBlobWithValue(instance.config, "customModels", [...next]);
const updateCustomModels = (next: ReadonlyArray<CustomModelDefinition>) => {
const nextConfig = nextConfigBlobWithValue(
instance.config,
"customModels",
next.map(toCustomModelSetting),
);
const { config: _omit, ...rest } = instance;
onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig);
};
@@ -1,13 +1,13 @@
"use client";
import { ArrowDownIcon, ArrowUpIcon, PlusIcon, StarIcon, XIcon } from "lucide-react";
import { ArrowDownIcon, ArrowUpIcon, PencilIcon, PlusIcon, StarIcon, XIcon } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import {
ProviderDriverKind,
type ProviderInstanceId,
type ServerProviderModel,
} from "@t3tools/contracts";
import { normalizeCustomModelSlug } from "@t3tools/shared/model";
import { type CustomModelDefinition, normalizeCustomModelSlug } from "@t3tools/shared/model";
import { cn } from "../../lib/utils";
import { sortModelsForProviderInstance } from "../../modelOrdering";
@@ -16,6 +16,7 @@ import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Switch } from "../ui/switch";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { CustomModelEditor } from "./CustomModelEditor";
/**
* Placeholder text for the "add a custom model" input, keyed by driver
@@ -109,11 +110,11 @@ interface ProviderModelsSectionProps {
*/
readonly models: ReadonlyArray<ServerProviderModel>;
/**
* The persisted custom-model slug list for this instance. Drives dedup,
* and is the array we hand back verbatim (with the new slug appended /
* The persisted custom-model list for this instance, resolved. Drives
* dedup, and is the list we hand back (with an entry appended / replaced /
* removed) via `onChange`.
*/
readonly customModels: ReadonlyArray<string>;
readonly customModels: ReadonlyArray<CustomModelDefinition>;
/** Server-returned model slugs hidden from the model picker. */
readonly hiddenModels: ReadonlyArray<string>;
/** Model slugs favorited for this provider instance. */
@@ -125,7 +126,7 @@ interface ProviderModelsSectionProps {
* write to the correct storage (legacy `settings.providers[kind]` vs.
* `providerInstances[id].config`).
*/
readonly onChange: (next: ReadonlyArray<string>) => void;
readonly onChange: (next: ReadonlyArray<CustomModelDefinition>) => void;
readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
@@ -159,6 +160,8 @@ export function ProviderModelsSection({
const [isAdding, setIsAdding] = useState(false);
const [filter, setFilter] = useState("");
const [error, setError] = useState<string | null>(null);
// Slug of the custom model whose inline editor is open, if any.
const [editingSlug, setEditingSlug] = useState<string | null>(null);
const listRef = useRef<HTMLDivElement>(null);
// Slug of a just-added custom model, scrolled into view once its row exists.
const scrollToSlugRef = useRef<string | null>(null);
@@ -177,6 +180,7 @@ export function ProviderModelsSection({
const hiddenCount = displayModels.filter(
(model) => !model.isCustom && hiddenModelSet.has(model.slug),
).length;
const builtInModels = useMemo(() => models.filter((model) => !model.isCustom), [models]);
const showFilter = models.length > FILTER_THRESHOLD;
const normalizedFilter = filter.trim().toLowerCase();
const isFiltering = showFilter && normalizedFilter.length > 0;
@@ -216,7 +220,7 @@ export function ProviderModelsSection({
setError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);
return;
}
if (customModels.includes(normalized)) {
if (customModels.some((entry) => entry.slug === normalized)) {
setError("That custom model is already saved.");
return;
}
@@ -225,7 +229,7 @@ export function ProviderModelsSection({
// which is also what lets the pending scroll target resolve and clear.
scrollToSlugRef.current = normalized;
setFilter("");
onChange([...customModels, normalized]);
onChange([...customModels, { slug: normalized, name: normalized, capabilities: null }]);
setInput("");
setError(null);
setIsAdding(false);
@@ -238,12 +242,18 @@ export function ProviderModelsSection({
};
const handleRemove = (slug: string) => {
onChange(customModels.filter((model) => model !== slug));
if (editingSlug === slug) setEditingSlug(null);
onChange(customModels.filter((entry) => entry.slug !== slug));
onModelOrderChange(modelOrder.filter((model) => model !== slug));
onFavoriteModelsChange(favoriteModels.filter((model) => model !== slug));
setError(null);
};
const handleSaveEdit = (next: CustomModelDefinition) => {
onChange(customModels.map((entry) => (entry.slug === next.slug ? next : entry)));
setEditingSlug(null);
};
const setHidden = (slug: string, hidden: boolean) => {
if (hidden === hiddenModelSet.has(slug)) return;
onHiddenModelsChange(
@@ -355,21 +365,40 @@ export function ProviderModelsSection({
</>
) : null}
{model.isCustom ? (
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-micro"
variant="ghost-muted"
aria-label={`Remove ${model.slug}`}
onClick={() => handleRemove(model.slug)}
/>
}
>
<XIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">Remove custom model</TooltipPopup>
</Tooltip>
<>
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-micro"
variant="ghost-muted"
aria-label={`Edit ${model.slug}`}
onClick={() =>
setEditingSlug((current) => (current === model.slug ? null : model.slug))
}
/>
}
>
<PencilIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">Edit name and options</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-micro"
variant="ghost-muted"
aria-label={`Remove ${model.slug}`}
onClick={() => handleRemove(model.slug)}
/>
}
>
<XIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">Remove custom model</TooltipPopup>
</Tooltip>
</>
) : null}
</span>
);
@@ -420,20 +449,23 @@ export function ProviderModelsSection({
key={`${instanceId}:${model.slug}`}
data-model-slug={model.slug}
className={cn(
"grid h-7 grid-cols-[1.5rem_minmax(0,1fr)_auto_4rem_auto] items-center gap-2 rounded-md px-2 transition-colors hover:bg-muted/30",
// Actions column is at least wide enough for the four custom-row
// buttons so capability labels line up across built-in and custom rows.
"grid h-7 grid-cols-[1.5rem_minmax(0,1fr)_auto_minmax(5.5rem,auto)_auto] items-center gap-2 rounded-md px-2 transition-colors hover:bg-muted/30",
isHidden && "opacity-50",
)}
>
{starButton(model, isFavorite)}
<span className="flex min-w-0 items-baseline gap-2">
<span className={cn(nameClassName, "truncate")}>{model.name}</span>
{model.isCustom ? (
<span className="text-[11px] text-muted-foreground/70">custom</span>
) : model.name !== model.slug ? (
{model.name !== model.slug ? (
<code className="truncate font-mono text-[11px] text-muted-foreground/70">
{model.slug}
</code>
) : null}
{model.isCustom ? (
<span className="text-[11px] text-muted-foreground/70">custom</span>
) : null}
</span>
{/*
Always a grid item so the columns line up across rows; the text
@@ -489,6 +521,10 @@ export function ProviderModelsSection({
const group = groupOf(model);
const previous = visibleModels[index - 1];
const startsGroup = previous === undefined || groupOf(previous) !== group;
const editingEntry =
model.isCustom && editingSlug === model.slug
? customModels.find((entry) => entry.slug === model.slug)
: undefined;
return (
<div key={`${instanceId}:${model.slug}:group`}>
{startsGroup && favoriteCount > 0 && group === "favorite"
@@ -501,6 +537,17 @@ export function ProviderModelsSection({
? groupLabel("Hidden from picker", index === 0)
: null}
{renderRow(model)}
{editingEntry ? (
<CustomModelEditor
key={`${instanceId}:${model.slug}:editor`}
instanceId={instanceId}
driverKind={driverKind}
entry={editingEntry}
builtInModels={builtInModels}
onSave={handleSaveEdit}
onCancel={() => setEditingSlug(null)}
/>
) : null}
</div>
);
})}
@@ -0,0 +1,259 @@
import { describe, expect, it } from "vite-plus/test";
import { ProviderDriverKind, type ModelCapabilities } from "@t3tools/contracts";
import {
DESCRIPTOR_PRESETS_BY_KIND,
descriptorFromPreset,
definitionFromDraft,
descriptorsFromCapabilities,
draftFromDefinition,
validateDraft,
type CustomModelDraft,
} from "./customModelEditor.logic";
const draft = (overrides: Partial<CustomModelDraft>): CustomModelDraft => ({
slug: "my-model",
name: "",
descriptors: [],
...overrides,
});
describe("customModelEditor.logic", () => {
it("round-trips a definition through the draft, marking the current value as default", () => {
const definition = definitionFromDraft(
draft({
name: " My Model ",
descriptors: [
{
key: "a",
type: "select",
id: "reasoningEffort",
label: "Reasoning",
choices: [
{ key: "a1", id: "low", label: "Low", isDefault: false },
{ key: "a2", id: "high", label: "", isDefault: true },
],
},
{ key: "b", type: "boolean", id: "fastMode", label: "Fast Mode", choices: [] },
],
}),
);
expect(definition).toEqual({
slug: "my-model",
name: "My Model",
capabilities: {
optionDescriptors: [
{
id: "reasoningEffort",
label: "Reasoning",
type: "select",
options: [
{ id: "low", label: "Low" },
{ id: "high", label: "high", isDefault: true },
],
currentValue: "high",
},
{ id: "fastMode", label: "Fast Mode", type: "boolean" },
],
},
});
const reopened = draftFromDefinition(definition);
expect(reopened.name).toBe("My Model");
expect(reopened.descriptors.map((descriptor) => descriptor.id)).toEqual([
"reasoningEffort",
"fastMode",
]);
expect(reopened.descriptors[0]!.choices.map((choice) => choice.isDefault)).toEqual([
false,
true,
]);
});
it("preserves the current choice when it differs from the built-in default", () => {
const descriptors = descriptorsFromCapabilities(
{
optionDescriptors: [
{
id: "effort",
label: "Reasoning",
type: "select",
currentValue: "high",
options: [
{ id: "low", label: "Low", isDefault: true },
{ id: "high", label: "High" },
],
},
],
},
ProviderDriverKind.make("claudeAgent"),
);
expect(descriptors[0]!.choices.map((choice) => choice.isDefault)).toEqual([false, true]);
expect(
definitionFromDraft(draft({ descriptors })).capabilities?.optionDescriptors?.[0],
).toMatchObject({ currentValue: "high" });
});
it("drops prompt-injected choices when copying a built-in's descriptors", () => {
const [copied] = descriptorsFromCapabilities(
{
optionDescriptors: [
{
id: "effort",
label: "Reasoning",
type: "select",
options: [
{ id: "high", label: "High", isDefault: true },
{ id: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
},
],
},
ProviderDriverKind.make("claudeAgent"),
);
expect(copied!.choices.map((choice) => choice.id)).toEqual(["high"]);
});
it.each([true, false, undefined])(
"preserves boolean values through copy and edit: %s",
(currentValue) => {
const capabilities: ModelCapabilities = {
optionDescriptors: [
{
id: "thinking",
label: "Thinking",
type: "boolean",
...(currentValue !== undefined ? { currentValue } : {}),
},
],
};
const copied = definitionFromDraft(
draft({
descriptors: descriptorsFromCapabilities(capabilities, ProviderDriverKind.make("cursor")),
}),
);
expect(copied.capabilities).toEqual(capabilities);
const reopened = draftFromDefinition(copied);
expect(definitionFromDraft({ ...reopened, name: "Renamed" }).capabilities).toEqual(
capabilities,
);
},
);
it("excludes Claude context choices from presets and copies without changing other providers or authored entries", () => {
const capabilities: ModelCapabilities = {
optionDescriptors: [
{
id: "contextWindow",
label: "Context",
type: "select",
options: [{ id: "1m", label: "1M", isDefault: true }],
},
{ id: "thinking", label: "Thinking", type: "boolean", currentValue: true },
],
};
const claude = ProviderDriverKind.make("claudeAgent");
const copied = definitionFromDraft(
draft({ descriptors: descriptorsFromCapabilities(capabilities, claude) }),
);
expect(copied.capabilities?.optionDescriptors).toEqual([capabilities.optionDescriptors![1]]);
const presets = definitionFromDraft(
draft({
descriptors: (DESCRIPTOR_PRESETS_BY_KIND[claude] ?? []).map(descriptorFromPreset),
}),
);
expect(
presets.capabilities?.optionDescriptors?.some((option) => option.id === "contextWindow"),
).toBe(false);
const cursorCopy = descriptorsFromCapabilities(capabilities, ProviderDriverKind.make("cursor"));
expect(cursorCopy.map((option) => option.id)).toEqual(["contextWindow", "thinking"]);
const authored = { slug: "custom", name: "Custom", capabilities };
expect(
definitionFromDraft(draftFromDefinition(authored)).capabilities?.optionDescriptors?.[0],
).toMatchObject(capabilities.optionDescriptors![0]!);
});
it("preserves choice descriptions when copying, renaming, and saving", () => {
const capabilities: ModelCapabilities = {
optionDescriptors: [
{
id: "effort",
label: "Reasoning",
description: "Choose a reasoning level.",
type: "select",
options: [
{ id: "high", label: "High", isDefault: true },
{ id: "ultracode", label: "Ultracode", description: "Uses additional reasoning." },
],
},
],
};
const copied = definitionFromDraft(
draft({
descriptors: descriptorsFromCapabilities(
capabilities,
ProviderDriverKind.make("claudeAgent"),
),
}),
);
const reopened = draftFromDefinition(copied);
const saved = definitionFromDraft({ ...reopened, name: "Renamed" });
expect(saved.capabilities?.optionDescriptors?.[0]).toMatchObject(
capabilities.optionDescriptors![0]!,
);
expect(copied.capabilities?.optionDescriptors?.[0]).toMatchObject(
capabilities.optionDescriptors![0]!,
);
});
it.each(Object.entries(DESCRIPTOR_PRESETS_BY_KIND))(
"offers saveable presets for %s",
(_driver, presets) => {
expect(
validateDraft(draft({ descriptors: (presets ?? []).map(descriptorFromPreset) })),
).toBeNull();
},
);
it("collapses a blank name and no options back to a bare definition", () => {
expect(definitionFromDraft(draft({ name: " " }))).toEqual({
slug: "my-model",
name: "my-model",
capabilities: null,
});
expect(draftFromDefinition({ slug: "x", name: "x", capabilities: null }).name).toBe("");
});
it("rejects duplicate ids, blank ids, and selects without choices", () => {
const select = (id: string, choices: Array<{ id: string }>) => ({
key: id,
type: "select" as const,
id,
label: "Label",
choices: choices.map((choice) => ({
key: choice.id,
label: "",
isDefault: false,
...choice,
})),
});
expect(validateDraft(draft({ descriptors: [select("", [{ id: "a" }])] }))).toBe(
"Option 1 needs an id.",
);
expect(
validateDraft(
draft({ descriptors: [select("effort", [{ id: "a" }]), select("effort", [{ id: "b" }])] }),
),
).toBe('Option 2: id "effort" is used twice.');
expect(validateDraft(draft({ descriptors: [select("effort", [])] }))).toBe(
"Option 1 needs at least one choice.",
);
expect(
validateDraft(draft({ descriptors: [select("effort", [{ id: "a" }, { id: "a" }])] })),
).toBe('Option 1: choice "a" is used twice.');
expect(validateDraft(draft({ descriptors: [select("effort", [{ id: "a" }])] }))).toBeNull();
});
});
@@ -0,0 +1,258 @@
import {
type ModelCapabilities,
ProviderDriverKind,
type ProviderOptionDescriptor,
} from "@t3tools/contracts";
import { type CustomModelDefinition, createModelCapabilities } from "@t3tools/shared/model";
/** Editable mirror of a `ProviderOptionChoice`. `key` is only a React key. */
export interface EditorChoice {
readonly key: string;
readonly id: string;
readonly label: string;
readonly isDefault: boolean;
readonly description?: string;
}
/** Editable mirror of a `ProviderOptionDescriptor`. `key` is only a React key. */
export interface EditorDescriptor {
readonly key: string;
readonly type: "select" | "boolean";
readonly id: string;
readonly label: string;
readonly choices: ReadonlyArray<EditorChoice>;
readonly currentBooleanValue?: boolean | undefined;
readonly description?: string | undefined;
}
export interface CustomModelDraft {
readonly slug: string;
readonly name: string;
readonly descriptors: ReadonlyArray<EditorDescriptor>;
}
export interface DescriptorPreset {
readonly id: string;
readonly label: string;
readonly type: "select" | "boolean";
readonly choices?: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>;
}
const EFFORT_CHOICES = [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium", isDefault: true },
{ id: "high", label: "High" },
{ id: "xhigh", label: "Extra High" },
] as const;
/**
* Option ids each adapter actually reads off a turn's model selection, with
* the usual choices pre-filled. Anything else the user types is stored
* verbatim but will be ignored by the driver.
*/
export const DESCRIPTOR_PRESETS_BY_KIND: Partial<
Record<ProviderDriverKind, ReadonlyArray<DescriptorPreset>>
> = {
[ProviderDriverKind.make("codex")]: [
{ id: "reasoningEffort", label: "Reasoning", type: "select", choices: EFFORT_CHOICES },
{
id: "serviceTier",
label: "Speed",
type: "select",
choices: [
{ id: "default", label: "Standard", isDefault: true },
{ id: "fast", label: "Fast" },
],
},
],
[ProviderDriverKind.make("claudeAgent")]: [
{
id: "effort",
label: "Reasoning",
type: "select",
choices: [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High", isDefault: true },
{ id: "xhigh", label: "Extra High" },
{ id: "max", label: "Max" },
],
},
{ id: "fastMode", label: "Fast Mode", type: "boolean" },
{ id: "thinking", label: "Thinking", type: "boolean" },
],
[ProviderDriverKind.make("cursor")]: [
{ id: "reasoning", label: "Reasoning", type: "select", choices: EFFORT_CHOICES },
{ id: "fastMode", label: "Fast Mode", type: "boolean" },
{ id: "thinking", label: "Thinking", type: "boolean" },
],
[ProviderDriverKind.make("grok")]: [
{ id: "reasoningEffort", label: "Reasoning", type: "select", choices: EFFORT_CHOICES },
],
[ProviderDriverKind.make("opencode")]: [
{ id: "variant", label: "Reasoning", type: "select", choices: EFFORT_CHOICES },
{
id: "agent",
label: "Agent",
type: "select",
choices: [
{ id: "build", label: "Build", isDefault: true },
{ id: "plan", label: "Plan" },
],
},
],
};
let nextKey = 0;
export function newEditorKey(): string {
nextKey += 1;
return `k${nextKey}`;
}
export function choiceFromPreset(choice: {
id: string;
label: string;
isDefault?: boolean;
}): EditorChoice {
return { key: newEditorKey(), id: choice.id, label: choice.label, isDefault: !!choice.isDefault };
}
export function descriptorFromPreset(preset: DescriptorPreset): EditorDescriptor {
return {
key: newEditorKey(),
type: preset.type,
id: preset.id,
label: preset.label,
choices: (preset.choices ?? []).map(choiceFromPreset),
};
}
export function emptyEditorDescriptor(): EditorDescriptor {
return { key: newEditorKey(), type: "select", id: "", label: "", choices: [] };
}
export function emptyEditorChoice(): EditorChoice {
return { key: newEditorKey(), id: "", label: "", isDefault: false };
}
/**
* Prompt-injected choices (Claude's `ultrathink`) are delivered as prompt text
* by built-in runtime profiles a custom entry does not have, so they are
* dropped rather than stored as a plain option value.
*/
export function descriptorToEditor(descriptor: ProviderOptionDescriptor): EditorDescriptor {
const promptInjected = new Set(
descriptor.type === "select" ? (descriptor.promptInjectedValues ?? []) : [],
);
const choices =
descriptor.type === "select"
? descriptor.options.filter((option) => !promptInjected.has(option.id))
: [];
const defaultChoice =
choices.find((option) => option.id === descriptor.currentValue) ??
choices.find((option) => option.isDefault);
return {
key: newEditorKey(),
type: descriptor.type,
id: descriptor.id,
label: descriptor.label,
...(descriptor.description !== undefined ? { description: descriptor.description } : {}),
...(descriptor.type === "boolean" && descriptor.currentValue !== undefined
? { currentBooleanValue: descriptor.currentValue }
: {}),
choices: choices.map((option) => ({
key: newEditorKey(),
id: option.id,
label: option.label,
...(option.description !== undefined ? { description: option.description } : {}),
isDefault: option === defaultChoice,
})),
};
}
export function draftFromDefinition(entry: CustomModelDefinition): CustomModelDraft {
return {
slug: entry.slug,
name: entry.name === entry.slug ? "" : entry.name,
descriptors: (entry.capabilities?.optionDescriptors ?? []).map(descriptorToEditor),
};
}
/** Claude context choices require runtime suffix mappings that custom entries do not carry. */
export function descriptorsFromCapabilities(
capabilities: ModelCapabilities | null | undefined,
driverKind: ProviderDriverKind | null,
): EditorDescriptor[] {
return (capabilities?.optionDescriptors ?? [])
.filter((descriptor) => driverKind !== "claudeAgent" || descriptor.id !== "contextWindow")
.map(descriptorToEditor);
}
/**
* Validate the draft before saving. Returns the first problem in reading
* order so the message is actionable, or `null` when the draft is sound.
*/
export function validateDraft(draft: CustomModelDraft): string | null {
const seenIds = new Set<string>();
for (const [index, descriptor] of draft.descriptors.entries()) {
const position = `Option ${index + 1}`;
const id = descriptor.id.trim();
if (!id) return `${position} needs an id.`;
if (seenIds.has(id)) return `${position}: id "${id}" is used twice.`;
seenIds.add(id);
if (!descriptor.label.trim()) return `${position} needs a label.`;
if (descriptor.type !== "select") continue;
if (descriptor.choices.length === 0) return `${position} needs at least one choice.`;
const seenChoices = new Set<string>();
for (const choice of descriptor.choices) {
const choiceId = choice.id.trim();
if (!choiceId) return `${position} has a choice without a value.`;
if (seenChoices.has(choiceId)) {
return `${position}: choice "${choiceId}" is used twice.`;
}
seenChoices.add(choiceId);
}
}
return null;
}
/** Convert a validated draft back into a definition. Blank name → slug. */
export function definitionFromDraft(draft: CustomModelDraft): CustomModelDefinition {
const descriptors: ProviderOptionDescriptor[] = draft.descriptors.map((descriptor) => {
const id = descriptor.id.trim();
const label = descriptor.label.trim();
if (descriptor.type === "boolean") {
return {
id,
label,
type: "boolean",
...(descriptor.description !== undefined ? { description: descriptor.description } : {}),
...(descriptor.currentBooleanValue !== undefined
? { currentValue: descriptor.currentBooleanValue }
: {}),
};
}
const options = descriptor.choices.map((choice) => ({
id: choice.id.trim(),
label: choice.label.trim() || choice.id.trim(),
...(choice.description !== undefined ? { description: choice.description } : {}),
...(choice.isDefault ? { isDefault: true } : {}),
}));
const currentValue = options.find((option) => option.isDefault)?.id;
return {
id,
label,
type: "select",
...(descriptor.description !== undefined ? { description: descriptor.description } : {}),
options,
...(currentValue ? { currentValue } : {}),
};
});
const name = draft.name.trim();
return {
slug: draft.slug,
name: name || draft.slug,
capabilities:
descriptors.length > 0 ? createModelCapabilities({ optionDescriptors: descriptors }) : null,
};
}
+23 -27
View File
@@ -10,8 +10,10 @@ import {
type ServerSettingsPatch,
} from "@t3tools/contracts";
import {
type CustomModelDefinition,
createModelSelection,
normalizeCustomModelSlug,
readCustomModelEntries,
resolveSelectableModel,
} from "@t3tools/shared/model";
import { getComposerProviderState } from "./components/chat/composerProviderState";
@@ -55,14 +57,14 @@ function readInstanceCustomModels(
settings: UnifiedSettings,
instanceId: ProviderInstanceId,
driverKind: ProviderDriverKind,
): ReadonlyArray<string> {
): ReadonlyArray<CustomModelDefinition> {
if (driverKind === "antigravity") return [];
const instance = settings.providerInstances?.[instanceId];
const config = instance?.config;
if (config !== null && typeof config === "object") {
const value = (config as Record<string, unknown>).customModels;
if (Array.isArray(value)) {
return value.filter((entry): entry is string => typeof entry === "string");
return readCustomModelEntries(value);
}
}
const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
@@ -71,9 +73,9 @@ function readInstanceCustomModels(
}
const legacyProviders = settings.providers as Record<
string,
{ readonly customModels: ReadonlyArray<string> } | undefined
{ readonly customModels: ReadonlyArray<unknown> } | undefined
>;
return legacyProviders[driverKind]?.customModels ?? [];
return readCustomModelEntries(legacyProviders[driverKind]?.customModels ?? []);
}
export interface AppModelOption {
@@ -151,26 +153,24 @@ function applyInstanceModelPreferences(
);
}
export function normalizeCustomModelSlugs(
models: Iterable<string | null | undefined>,
export function normalizeCustomModelEntries(
models: ReadonlyArray<CustomModelDefinition>,
builtInModelSlugs: ReadonlySet<string>,
): string[] {
const normalizedModels: string[] = [];
): CustomModelDefinition[] {
const normalizedModels: CustomModelDefinition[] = [];
const seen = new Set<string>();
for (const candidate of models) {
const normalized = normalizeCustomModelSlug(candidate);
if (
!normalized ||
normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
builtInModelSlugs.has(normalized) ||
seen.has(normalized)
candidate.slug.length > MAX_CUSTOM_MODEL_LENGTH ||
builtInModelSlugs.has(candidate.slug) ||
seen.has(candidate.slug)
) {
continue;
}
seen.add(normalized);
normalizedModels.push(normalized);
seen.add(candidate.slug);
normalizedModels.push(candidate);
if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
break;
}
@@ -205,17 +205,13 @@ export function getAppModelOptions(
// see the user's authored custom models.
const defaultInstanceId = defaultInstanceIdForDriver(provider);
const customModels = readInstanceCustomModels(settings, defaultInstanceId, provider);
for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs)) {
if (seen.has(slug)) {
for (const entry of normalizeCustomModelEntries(customModels, builtInModelSlugs)) {
if (seen.has(entry.slug)) {
continue;
}
seen.add(slug);
options.push({
slug,
name: slug,
isCustom: true,
});
seen.add(entry.slug);
options.push({ slug: entry.slug, name: entry.name, isCustom: true });
}
const preferences = readInstanceModelPreferences(settings, defaultInstanceId);
@@ -257,13 +253,13 @@ export function getAppModelOptionsForInstance(
);
const customModels = readInstanceCustomModels(settings, entry.instanceId, entry.driverKind);
for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs)) {
if (seen.has(slug)) {
for (const custom of normalizeCustomModelEntries(customModels, builtInModelSlugs)) {
if (seen.has(custom.slug)) {
continue;
}
seen.add(slug);
options.push({ slug, name: slug, isCustom: true });
seen.add(custom.slug);
options.push({ slug: custom.slug, name: custom.name, isCustom: true });
}
const preferences = readInstanceModelPreferences(settings, entry.instanceId);