Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Custom API accounts in the app: add a server, see its status, pin bots to its models
Lin (kwant bot)d723e1f932a7
diff --git a/frontend/src/components/EngineAccounts.tsx b/frontend/src/components/EngineAccounts.tsxindex 2c925f09..88929b20 100644--- a/frontend/src/components/EngineAccounts.tsx+++ b/frontend/src/components/EngineAccounts.tsx@@ -1,8 +1,23 @@import React, { useEffect, useRef, useState } from 'react';-import { Check, ChevronDown, ChevronRight, Copy, ExternalLink, KeyRound, Loader2, LogIn, LogOut, Pencil, Plus, Star, Trash2 } from 'lucide-react';+import { Check, ChevronDown, ChevronRight, Copy, ExternalLink, KeyRound, Loader2, LogIn, LogOut, Pencil, Plus, RefreshCw, Server, Star, Trash2, Wrench } from 'lucide-react';import { playSfx } from '../audio/chiptune';import type { EngineInfo, Tone } from '../engines';-import { KIND_LABELS, Login, Profile, accountState, isLoginDone, isThirdPartyLabel, newAccountFor, profilesApi, safeExternalUrl } from '../profiles';+import {+ CUSTOM_PRESETS,+ CustomProtocol,+ KIND_LABELS,+ Login,+ NewAccountSpec,+ PROTOCOLS,+ Profile,+ accountState,+ isLoginDone,+ isThirdPartyLabel,+ newAccountFor,+ profilesApi,+ protocolLabel,+ safeExternalUrl,+} from '../profiles';const input ='w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors';@@ -117,7 +132,9 @@ export const AccountList: React.FC<{))}</ul>) : (- <p className="text-[11px] text-zinc-500">{spec?.kind === 'api_key' ? 'No accounts with a key yet.' : 'No accounts yet.'}</p>+ <p className="text-[11px] text-zinc-500">+ {spec?.kind === 'custom_api' ? 'No servers yet.' : spec?.kind === 'api_key' ? 'No accounts with a key yet.' : 'No accounts yet.'}+ </p>)}{spec &&(adding ? (@@ -143,7 +160,8 @@ export const AccountList: React.FC<{}}className={quietBtn}>- <Plus size={12} aria-hidden="true" /> {spec.kind === 'api_key' ? 'Add an account with a key' : 'Add account'}+ <Plus size={12} aria-hidden="true" />{' '}+ {spec.kind === 'custom_api' ? 'Add a custom server' : spec.kind === 'api_key' ? 'Add an account with a key' : 'Add account'}</button>))}</div>@@ -151,7 +169,16 @@ export const AccountList: React.FC<{};const AddAccountForm: React.FC<{- spec: { engine: Profile['engine']; kind: 'cli_home' | 'api_key' };+ spec: NewAccountSpec;+ onCancel: () => void;+ onCreated: () => void;+}> = ({ spec, onCancel, onCreated }) =>+ spec.kind === 'custom_api' ? <CustomServerForm onCancel={onCancel} onSaved={onCreated} /> : <KeyOrLoginForm spec={spec as KeyOrLoginSpec} onCancel={onCancel} onCreated={onCreated} />;++type KeyOrLoginSpec = { engine: Profile['engine']; kind: 'cli_home' | 'api_key' };++const KeyOrLoginForm: React.FC<{+ spec: KeyOrLoginSpec;onCancel: () => void;onCreated: () => void;}> = ({ spec, onCancel, onCreated }) => {@@ -242,6 +269,229 @@ const AddAccountForm: React.FC<{);};+const OTHER_MODEL = '\u0000other';++/** Adds a Custom API account, or edits its server (`account`): format, address, model, and its key when new. */+export const CustomServerForm: React.FC<{+ account?: Profile;+ onCancel: () => void;+ onSaved: () => void;+}> = ({ account, onCancel, onSaved }) => {+ const editing = !!account;+ const c = account?.custom ?? null;+ const [name, setName] = useState('');+ const [protocol, setProtocol] = useState<CustomProtocol>(c?.protocol ?? 'openai-chat');+ const [baseUrl, setBaseUrl] = useState(c?.base_url ?? '');+ const [apiKey, setApiKey] = useState('');+ const [model, setModel] = useState(c?.model ?? '');+ const [isDefault, setIsDefault] = useState(false);+ const [preset, setPreset] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const id = account ? `custom-${account.id}` : 'new-custom';+ const listed = c?.status === 'ready' ? c.models : [];+ const [typing, setTyping] = useState(!!c?.model && !listed.some((m) => m.id === c.model));+ const active = CUSTOM_PRESETS.find((p) => p.id === preset);++ const applyPreset = (id: string) => {+ const p = CUSTOM_PRESETS.find((x) => x.id === id);+ if (!p) return;+ playSfx('click');+ const proto = p.urls[protocol] ? protocol : 'openai-chat';+ setPreset(id);+ setProtocol(proto);+ setBaseUrl(p.urls[proto] ?? '');+ if (!editing && !name.trim()) setName(p.name);+ };+ // Switching format keeps a preset's address in step (Agent Maestro serves both at different paths).+ const changeProtocol = (next: CustomProtocol) => {+ setProtocol(next);+ const from = CUSTOM_PRESETS.find((p) => p.urls[protocol] === baseUrl.trim());+ if (from?.urls[next]) setBaseUrl(from.urls[next]!);+ };++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ const url = baseUrl.trim();+ if (!url || (!editing && !name.trim())) return;+ setBusy(true);+ setError(null);+ try {+ if (account) {+ const body: { protocol?: CustomProtocol; base_url?: string; model?: string } = {};+ if (protocol !== c?.protocol) body.protocol = protocol;+ if (url !== c?.base_url) body.base_url = url;+ if (model.trim() !== (c?.model ?? '')) body.model = model.trim();+ await (Object.keys(body).length ? profilesApi.update(account.id, body) : profilesApi.check(account.id));+ } else {+ await profilesApi.create({+ engine: 'custom',+ kind: 'custom_api',+ name: name.trim(),+ protocol,+ base_url: url,+ is_default: isDefault,+ ...(apiKey.trim() ? { api_key: apiKey.trim() } : {}),+ ...(model.trim() ? { model: model.trim() } : {}),+ });+ }+ setApiKey('');+ onSaved();+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Could not save the server.');+ } finally {+ setBusy(false);+ }+ };++ return (+ <form+ onSubmit={submit}+ onKeyDown={(e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ onCancel();+ }+ }}+ data-custom-form={editing ? 'edit' : 'new'}+ className="bg-zinc-950/60 border border-sky-500/30 rounded-lg p-3 space-y-3"+ aria-label={editing ? `Server for ${account!.name}` : 'New custom server'}+ >+ <div>+ <p className="text-[11px] font-medium text-zinc-400 mb-1">Fill in for</p>+ <div className="flex flex-wrap gap-1.5">+ {CUSTOM_PRESETS.map((p) => (+ <button key={p.id} type="button" aria-pressed={preset === p.id} onClick={() => applyPreset(p.id)} className={preset === p.id ? primaryBtn : quietBtn}>+ {p.id === 'maestro' ? `Use ${p.label}` : p.label}+ </button>+ ))}+ </div>+ {active && <p className="mt-1 text-[11px] text-zinc-500">{active.note}</p>}+ </div>++ {!editing && (+ <div>+ <label htmlFor={`${id}-name`} className="block text-[11px] font-medium text-zinc-400 mb-1">+ Name <span className="text-zinc-600 font-normal">· shown on replies as “ran on …”</span>+ </label>+ <input id={`${id}-name`} autoFocus required maxLength={60} value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Copilot" className={input} />+ </div>+ )}++ <fieldset>+ <legend className="block text-[11px] font-medium text-zinc-400 mb-1">Format</legend>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5">+ {PROTOCOLS.map((p) => (+ <label+ key={p.id}+ className={`flex items-start gap-2 rounded-lg border px-2.5 py-2 text-[11px] cursor-pointer ${+ protocol === p.id ? 'border-sky-500/50 bg-sky-500/10 text-zinc-100' : 'border-zinc-800 text-zinc-300 hover:border-zinc-700'+ }`}+ >+ <input type="radio" name={`${id}-protocol`} value={p.id} checked={protocol === p.id} onChange={() => changeProtocol(p.id)} className="mt-0.5 accent-sky-500" />+ <span>+ <span className="block font-medium">{p.label}</span>+ <span className="block text-zinc-500">{p.hint}</span>+ </span>+ </label>+ ))}+ </div>+ </fieldset>++ <div>+ <label htmlFor={`${id}-url`} className="block text-[11px] font-medium text-zinc-400 mb-1">+ Server address+ </label>+ <input+ id={`${id}-url`}+ required+ inputMode="url"+ autoComplete="off"+ spellCheck={false}+ value={baseUrl}+ onChange={(e) => setBaseUrl(e.target.value)}+ placeholder={protocol === 'anthropic-messages' ? 'http://localhost:23333/api/anthropic' : 'http://localhost:23333/api/openai/v1'}+ aria-describedby={`${id}-url-hint`}+ className={`${input} font-mono`}+ />+ <p id={`${id}-url-hint`} className="mt-1 text-[11px] text-zinc-500">+ The API’s root. A pasted …/chat/completions or …/messages address works too.+ </p>+ </div>++ {!editing && (+ <div>+ <label htmlFor={`${id}-key`} className="block text-[11px] font-medium text-zinc-400 mb-1">+ API key <span className="text-zinc-600 font-normal">· optional, never shown again</span>+ </label>+ <input id={`${id}-key`} type="password" autoComplete="off" spellCheck={false} value={apiKey} onChange={(e) => setApiKey(e.target.value)} className={input} />+ </div>+ )}++ <div>+ <label htmlFor={`${id}-model`} className="block text-[11px] font-medium text-zinc-400 mb-1">+ Model <span className="text-zinc-600 font-normal">· optional; bots can pick their own</span>+ </label>+ {listed.length > 0 && !typing ? (+ <select+ id={`${id}-model`}+ value={model}+ onChange={(e) => {+ if (e.target.value === OTHER_MODEL) {+ setTyping(true);+ setModel('');+ } else setModel(e.target.value);+ }}+ className={input}+ >+ <option value="">Let the server’s list decide</option>+ {listed.map((m) => (+ <option key={m.id} value={m.id}>+ {m.label === m.id ? m.id : `${m.label} (${m.id})`}+ </option>+ ))}+ <option value={OTHER_MODEL}>Another model id…</option>+ </select>+ ) : (+ <input+ id={`${id}-model`}+ autoComplete="off"+ spellCheck={false}+ value={model}+ onChange={(e) => setModel(e.target.value)}+ placeholder="e.g. gpt-4.1"+ className={`${input} font-mono`}+ />+ )}+ <p className="mt-1 text-[11px] text-zinc-500">+ {editing && listed.length > 0 ? `${listed.length === 1 ? '1 model' : `${listed.length} models`} on this server.` : 'Needed only if the server doesn’t list its models.'}+ </p>+ </div>++ {!editing && (+ <label className="flex items-center gap-2 text-[11px] text-zinc-300">+ <input type="checkbox" checked={isDefault} onChange={(e) => setIsDefault(e.target.checked)} className="accent-sky-500" />+ Make it the default+ </label>+ )}+ {error && (+ <p className="text-[11px] text-rose-300" role="alert">+ {error}+ </p>+ )}+ <div className="flex flex-wrap items-center justify-end gap-2">+ {busy && <span className="text-[11px] text-zinc-500 mr-auto">Checking the server…</span>}+ <button type="button" onClick={onCancel} className={quietBtn}>+ Cancel+ </button>+ <button type="submit" disabled={busy || !baseUrl.trim() || (!editing && !name.trim())} className={primaryBtn}>+ {busy && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />} {editing ? 'Save and check' : 'Add server'}+ </button>+ </div>+ </form>+ );+};+const AccountRow: React.FC<{profile: Profile;engine: EngineInfo;@@ -259,7 +509,10 @@ const AccountRow: React.FC<{const [keyValue, setKeyValue] = useState('');const [login, setLogin] = useState<Login | null>(null);const [detailsOpen, setDetailsOpen] = useState(false);+ const [editingServer, setEditingServer] = useState(false);const status = accountStatus(p, engine);+ const isCustom = p.kind === 'custom_api';+ const hasKeySlot = p.kind === 'api_key' || isCustom;const isSystem = p.kind === 'system';const nameId = `account-${p.id}-name`;@@ -301,7 +554,14 @@ const AccountRow: React.FC<{const off = status.label === 'Off';const isClaude = p.engine === 'claude';- const kindText = isSystem ? `The ${engine.name.replace(/ CLI$/, '')} login on this computer` : p.kind === 'api_key' ? 'API key' : `${engine.name.replace(/ CLI$/, '')} subscription`;+ const kindText = isSystem+ ? `The ${engine.name.replace(/ CLI$/, '')} login on this computer`+ : isCustom+ ? `${protocolLabel(p.custom?.protocol ?? '')}${p.has_key ? ' · key saved' : ''}`+ : p.kind === 'api_key'+ ? 'API key'+ : `${engine.name.replace(/ CLI$/, '')} subscription`;+ const statusText = status.tone === 'error' ? 'text-rose-300' : status.tone === 'warn' ? 'text-amber-200' : status.tone === 'ok' ? 'text-zinc-200' : '';const needsSignIn = p.kind === 'cli_home' && !p.signed_in && !login;return (@@ -371,10 +631,28 @@ const AccountRow: React.FC<{{inUse && <span className="px-1.5 py-0.5 rounded-md bg-emerald-500/15 text-[10px] font-medium text-emerald-200">In use</span>}</div><p className="text-[11px] leading-snug text-zinc-400 break-words">- {status.detail && <span className={status.tone === 'warn' || status.tone === 'error' ? 'text-amber-200' : status.tone === 'ok' ? 'text-zinc-200' : ''}>{status.detail}</span>}+ {status.detail && <span className={isCustom ? statusText : status.tone === 'warn' || status.tone === 'error' ? 'text-amber-200' : status.tone === 'ok' ? 'text-zinc-200' : ''}>{status.detail}</span>}{status.detail && <span className="text-zinc-600"> · </span>}<span className="text-zinc-500">{kindText}</span></p>+ {isCustom && p.custom && (+ <div className="space-y-1 pt-0.5">+ <p className="flex items-center gap-1 text-[11px] text-zinc-500 min-w-0">+ <Server size={11} className="shrink-0" aria-hidden="true" />+ <span className="font-mono text-zinc-400 break-all select-text" data-custom-url>+ {p.custom.base_url}+ </span>+ </p>+ <p className="text-[11px] text-zinc-500">+ Model: <span className="text-zinc-300">{p.custom.model ?? (p.custom.models.length ? 'each bot’s pick, else the server’s first' : 'none set')}</span>+ </p>+ {!p.custom.supports_tools && (+ <p data-no-tools className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-amber-500/10 border border-amber-500/25 text-[10.5px] text-amber-200">+ <Wrench size={10} aria-hidden="true" /> No tools (Anthropic format)+ </p>+ )}+ </div>+ )}</div><StatusPill tone={status.tone} className="mt-px">{status.label}@@ -411,12 +689,34 @@ const AccountRow: React.FC<{<LogOut size={11} aria-hidden="true" /> Sign out</button>)}- {p.kind === 'api_key' && (- <button type="button" disabled={busy} onClick={() => setKeyOpen((v) => !v)} className={p.has_key ? quietBtn : primaryBtn} aria-expanded={keyOpen}>+ {isCustom && (+ <>+ <button+ type="button"+ disabled={busy}+ onClick={() => run(() => profilesApi.check(p.id))}+ className={p.custom?.status && p.custom.status !== 'ready' ? primaryBtn : quietBtn}+ >+ <RefreshCw size={11} aria-hidden="true" /> Check again+ </button>+ <button type="button" disabled={busy} onClick={() => setEditingServer((v) => !v)} className={quietBtn} aria-expanded={editingServer}>+ <Pencil size={11} aria-hidden="true" /> Edit server+ </button>+ </>+ )}+ {hasKeySlot && (+ <button+ type="button"+ disabled={busy}+ onClick={() => setKeyOpen((v) => !v)}+ // A key is optional on a custom server, unless its server just refused the one it has.+ className={p.custom?.status === 'key_rejected' || (!isCustom && !p.has_key) ? primaryBtn : quietBtn}+ aria-expanded={keyOpen}+ ><KeyRound size={11} aria-hidden="true" /> {p.has_key ? 'Replace key' : 'Add key'}</button>)}- {p.kind === 'api_key' && p.has_key && (+ {hasKeySlot && p.has_key && (<button type="button" disabled={busy} onClick={() => run(() => profilesApi.removeKey(p.id))} className={quietBtn}>Remove key</button>@@ -492,9 +792,24 @@ const AccountRow: React.FC<{</div>)}- {confirmDelete && <p className="text-[11px] text-zinc-500">Bots pinned to it go back to the default. Its folder stays on disk.</p>}+ {confirmDelete && (+ <p className="text-[11px] text-zinc-500">+ {isCustom ? 'Bots pinned to it go back to the default. Its server settings and key are removed.' : 'Bots pinned to it go back to the default. Its folder stays on disk.'}+ </p>+ )}++ {editingServer && isCustom && (+ <CustomServerForm+ account={p}+ onCancel={() => setEditingServer(false)}+ onSaved={async () => {+ setEditingServer(false);+ await onChanged();+ }}+ />+ )}- {keyOpen && p.kind === 'api_key' && (+ {keyOpen && hasKeySlot && (<formclassName="flex items-center gap-1.5"onSubmit={(e) => {diff --git a/frontend/src/components/ModelPicker.tsx b/frontend/src/components/ModelPicker.tsxindex 02d3530b..c7b6ba8f 100644--- a/frontend/src/components/ModelPicker.tsx+++ b/frontend/src/components/ModelPicker.tsx@@ -1,8 +1,11 @@import React, { useId } from 'react';import { AlertTriangle, ChevronRight, Loader2 } from 'lucide-react';import { claudeNeedsSignIn } from '../claudeLogin';+import { Profile, readyCustomAccounts } from '../profiles';import {+ CustomSource,EngineInfo,+ EngineModel,FAMILIES,Family,FamilyOption,@@ -24,21 +27,39 @@ interface ModelPickerProps {onOpenSettings?: () => void;/** Opens Settings at "Sign in with Claude". */onSignInClaude?: () => void;+ /** The space's accounts: Custom API models come from each account's own server. */+ profiles?: Profile[];+ /** The bot's pinned account, and how to change it, so a Custom API model picks its account too. */+ profileId?: string | null;+ onPickAccount?: (profileId: string | null) => void;}+/** A ready Custom API account's models, with its own model first when its server doesn't list it. */+const customModels = (p: Profile): EngineModel[] => {+ const listed: EngineModel[] = (p.custom?.models ?? []).map((m) => ({ id: m.id, label: m.label, tier: m.tier, default: m.default }));+ const own = p.custom?.model;+ return own && !listed.some((m) => m.id === own) ? [{ id: own, label: own, default: true }, ...listed] : listed;+};++/** A Custom API option's value: the account and the model, so the same model on two servers stays apart. */+const SEP = '\n';+const SELECT ='w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none transition-colors disabled:opacity-50';/** One Engine → Model choice used wherever a kwant's model is set. Only engines that can run are offered. */-export const ModelPicker: React.FC<ModelPickerProps> = ({ value, onChange, engines, onOpenSettings, onSignInClaude }) => {+export const ModelPicker: React.FC<ModelPickerProps> = ({ value, onChange, engines, onOpenSettings, onSignInClaude, profiles, profileId, onPickAccount }) => {const id = useId();const pick = parsePick(value);+ const customAccounts = readyCustomAccounts(profiles);+ const custom: CustomSource[] = customAccounts.map((p) => ({ name: p.name, models: customModels(p) }));// A server without engine checks: offer every family, as before.const options: FamilyOption[] =engines && engines.length === 0- ? FAMILIES.map((f) => ({ id: f.id, label: f.label, via: [], models: [] }))- : familyOptions(engines ?? []);- const health = engines && engines.length === 0 ? ({ kind: 'ok' } as const) : pickHealth(value, engines);+ ? // An older server has no Custom API.+ FAMILIES.filter((f) => f.id !== 'custom').map((f) => ({ id: f.id, label: f.label, via: [], models: [] }))+ : familyOptions(engines ?? [], custom);+ const health = engines && engines.length === 0 ? ({ kind: 'ok' } as const) : pickHealth(value, engines, custom);const family = pick.family;const current = family && family !== 'auto' ? options.find((o) => o.id === family) : undefined;const staleFamily = family && family !== 'auto' && !current ? family : null;@@ -48,6 +69,19 @@ export const ModelPicker: React.FC<ModelPickerProps> = ({ value, onChange, enginconst pickFamily = (f: string) => onChange(f === 'auto' ? 'auto' : encodePick(f as Family, null));const pickModel = (m: string) => family && family !== 'auto' && onChange(encodePick(family, m || null));+ // Custom API: one group per account, and picking a model pins its account as well.+ const byAccount = family === 'custom' && customAccounts.length > 0;+ const owner = byAccount && pick.model+ ? customAccounts.find((p) => p.id === profileId && customModels(p).some((m) => m.id === pick.model)) ??+ customAccounts.find((p) => customModels(p).some((m) => m.id === pick.model))+ : undefined;+ const pickCustom = (v: string) => {+ if (!v) return onChange('custom');+ const [pid, ...rest] = v.split(SEP);+ onChange(encodePick('custom', rest.join(SEP)));+ onPickAccount?.(pid);+ };+const hintId = `${id}-hint`;const describedBy = health.kind !== 'ok' ? hintId : undefined;@@ -81,6 +115,27 @@ export const ModelPicker: React.FC<ModelPickerProps> = ({ value, onChange, engin<label htmlFor={`${id}-model`} className="block text-xs font-medium text-zinc-400 mb-1">Model</label>+ {byAccount ? (+ <select+ id={`${id}-model`}+ value={owner && pick.model ? `${owner.id}${SEP}${pick.model}` : pick.model ?? ''}+ onChange={(e) => pickCustom(e.target.value)}+ aria-describedby={describedBy}+ className={`${SELECT} ${health.kind === 'model_missing' ? 'border-amber-500/60' : ''}`}+ >+ <option value="">Each account’s own model</option>+ {customAccounts.map((p) => (+ <optgroup key={p.id} label={p.name}>+ {customModels(p).map((m) => (+ <option key={m.id} value={`${p.id}${SEP}${m.id}`}>+ {`${m.label} · ${p.name}`}+ </option>+ ))}+ </optgroup>+ ))}+ {pick.model && !owner && <option value={pick.model}>{`${pick.model} (not offered now)`}</option>}+ </select>+ ) : (<selectid={`${id}-model`}value={pick.model ?? ''}@@ -101,6 +156,7 @@ export const ModelPicker: React.FC<ModelPickerProps> = ({ value, onChange, engin))}{staleModel && <option value={staleModel}>{`${staleModel} (not offered now)`}</option>}</select>+ )}</div></div>diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsxindex ed158824..3bca16ba 100644--- a/frontend/src/components/NewAgentModal.tsx+++ b/frontend/src/components/NewAgentModal.tsx@@ -370,7 +370,16 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({</div></div>- <ModelPicker value={model} onChange={setModel} engines={engines.engines} onOpenSettings={onOpenSettings} onSignInClaude={onSignInClaude} />+ <ModelPicker+ value={model}+ onChange={setModel}+ engines={engines.engines}+ onOpenSettings={onOpenSettings}+ onSignInClaude={onSignInClaude}+ profiles={profiles}+ profileId={profileId}+ onPickAccount={setProfileId}+ />{engine && (<div>diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 0330c3a2..74f7c8bc 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -581,7 +581,11 @@ export const Sidebar: React.FC<SidebarProps> = ({<Pencil size={11} /></button>)}- <span className="text-[10px] text-zinc-500 font-mono uppercase bg-zinc-900 px-1 py-0.2 rounded border border-zinc-800">+ {/* Capped, so a long model id (Custom API) leaves room for the bot's name. */}+ <span+ className="max-w-[60%] truncate whitespace-nowrap text-[10px] text-zinc-500 font-mono uppercase bg-zinc-900 px-1 py-0.2 rounded border border-zinc-800"+ title={k.preferred_model === 'auto' ? 'Laya' : pickLabel(k.preferred_model)}+ >{k.preferred_model === 'auto' ? 'Laya' : pickLabel(k.preferred_model)}</span></div>diff --git a/frontend/src/engines.ts b/frontend/src/engines.tsindex e0778ab5..c3ba3971 100644--- a/frontend/src/engines.ts+++ b/frontend/src/engines.ts@@ -1,7 +1,7 @@// Engines: whether each way of running a model (a CLI, an API key, Ollama) can run right now, from// GET /api/engines, and the shared Engine → Model choice stored in a kwant's preferred_model.-export type EngineId = 'claude' | 'codex' | 'grok' | 'anthropic_api' | 'openai_api' | 'xai_api' | 'ollama';+export type EngineId = 'claude' | 'codex' | 'grok' | 'anthropic_api' | 'openai_api' | 'xai_api' | 'ollama' | 'custom_api';export type EngineKind = 'cli' | 'api' | 'local';export type EngineStatus = 'ready' | 'signed_out' | 'not_installed' | 'error' | 'checking' | 'disabled';export type Tier = 'fast' | 'balanced' | 'deep';@@ -32,7 +32,7 @@ export interface EngineInfo {}/** What a kwant picks: the model family, whichever of its engines (CLI or key) can run it. */-export type Family = 'claude' | 'codex' | 'grok' | 'ollama';+export type Family = 'claude' | 'codex' | 'grok' | 'ollama' | 'custom';export const FAMILY_OF: Record<EngineId, Family> = {claude: 'claude',@@ -42,6 +42,7 @@ export const FAMILY_OF: Record<EngineId, Family> = {grok: 'grok',xai_api: 'grok',ollama: 'ollama',+ custom_api: 'custom',};export const FAMILIES: Array<{ id: Family; label: string }> = [@@ -49,6 +50,7 @@ export const FAMILIES: Array<{ id: Family; label: string }> = [{ id: 'codex', label: 'Codex (OpenAI)' },{ id: 'grok', label: 'Grok (xAI)' },{ id: 'ollama', label: 'Ollama (local)' },+ { id: 'custom', label: 'Custom API' },];export const familyLabel = (f: Family) => FAMILIES.find((x) => x.id === f)?.label ?? f;@@ -59,7 +61,7 @@ export type Tone = 'ok' | 'warn' | 'error' | 'muted' | 'busy' | 'info';/** Whether kwants can run on it: the server's `ready` (which counts its accounts), else the host check. */export const isUsable = (e: Pick<EngineInfo, 'status' | 'enabled' | 'ready'>) => e.enabled !== false && (e.ready ?? e.status === 'ready');-export function statusView(e: Pick<EngineInfo, 'status' | 'enabled' | 'ready'> & { kind?: EngineKind }): { label: string; tone: Tone } {+export function statusView(e: Pick<EngineInfo, 'status' | 'enabled' | 'ready'> & { kind?: EngineKind; id?: EngineId }): { label: string; tone: Tone } {if (e.enabled === false || e.status === 'disabled') return { label: 'Off', tone: 'muted' };if (isUsable(e)) return { label: 'Ready', tone: 'ok' };switch (e.status) {@@ -69,7 +71,7 @@ export function statusView(e: Pick<EngineInfo, 'status' | 'enabled' | 'ready'> &return { label: 'Not signed in', tone: 'warn' };case 'not_installed':// An API engine without a key, or Ollama that isn't running, isn't "installed" either way.- return { label: e.kind === 'api' ? 'No key' : e.kind === 'local' ? 'Not running' : 'Not installed', tone: 'muted' };+ return { label: e.id === 'custom_api' ? 'No server' : e.kind === 'api' ? 'No key' : e.kind === 'local' ? 'Not running' : 'Not installed', tone: 'muted' };case 'error':return { label: 'Error', tone: 'error' };default:@@ -137,6 +139,8 @@ export function parsePick(value: string | null | undefined): KwantPick {const v = (value ?? '').trim();if (!v || v.toLowerCase() === 'auto') return { family: 'auto', model: null };if (v === 'local_ollama' || v === 'ollama') return { family: 'ollama', model: null };+ // "custom:<model>" (the server's form) or "custom/<model>"; model ids may hold either character.+ if (/^custom[:/]/.test(v)) return { family: 'custom', model: v.slice(7).trim() || null };const slash = v.indexOf('/');if (slash > 0) {const head = v.slice(0, slash);@@ -158,7 +162,7 @@ export function parsePick(value: string | null | undefined): KwantPick {export function encodePick(family: Family | 'auto', model: string | null): string {if (family === 'auto') return 'auto';if (!model) return family === 'ollama' ? 'local_ollama' : family;- return `${family}/${model}`;+ return family === 'custom' ? `custom:${model}` : `${family}/${model}`;}export interface FamilyOption {@@ -170,11 +174,24 @@ export interface FamilyOption {models: EngineModel[];}-/** Families with at least one engine that can run, in FAMILIES order. */-export function familyOptions(engines: EngineInfo[]): FamilyOption[] {- return FAMILIES.flatMap(({ id, label }) => {+/** A ready Custom API account's models, which the engine list doesn't carry (they're per account). */+export interface CustomSource {+ name: string;+ models: EngineModel[];+}++/** Families with at least one engine that can run, in FAMILIES order. Custom API lists its accounts+ * (`custom`) as its "via" and their models, since each account has its own server. */+export function familyOptions(engines: EngineInfo[], custom: CustomSource[] = []): FamilyOption[] {+ return FAMILIES.flatMap(({ id, label }): FamilyOption[] => {const usable = engines.filter((e) => FAMILY_OF[e.id] === id && isUsable(e));- if (usable.length === 0) return [];+ // A ready Custom API account is proof enough while the engine list catches up.+ if (usable.length === 0 && !(id === 'custom' && custom.length > 0)) return [];+ if (id === 'custom') {+ const seen = new Set<string>();+ const models = custom.flatMap((a) => a.models).filter((m) => !seen.has(m.id) && !!seen.add(m.id));+ return [{ id, label, via: custom.length ? custom.map((a) => a.name) : usable.map((e) => e.name), models }];+ }const seen = new Set<string>();let hasDefault = false;const models: EngineModel[] = [];@@ -202,9 +219,9 @@ export type PickHealth =| { kind: 'unknown'; value: string };/** Whether a saved pick can run with the engines as last checked. `engines` null while loading. */-export function pickHealth(value: string, engines: EngineInfo[] | null): PickHealth {+export function pickHealth(value: string, engines: EngineInfo[] | null, custom: CustomSource[] = []): PickHealth {if (!engines) return { kind: 'loading' };- const options = familyOptions(engines);+ const options = familyOptions(engines, custom);const pick = parsePick(value);if (pick.family === 'auto') return options.length ? { kind: 'ok' } : { kind: 'none_ready' };if (pick.family === null) return { kind: 'unknown', value };@@ -306,6 +323,10 @@ export function engineSummary(e: EngineInfo, accounts: SummaryAccount[] = []): {case 'checking':return { text: 'Checking…', tone: 'busy' };case 'not_installed':+ if (e.id === 'custom_api')+ return accounts.length+ ? { text: 'None of its servers answered · Check them below', tone: 'warn' }+ : { text: 'Add a server below: Agent Maestro (GitHub Copilot), OpenRouter, LM Studio or any OpenAI- or Anthropic-compatible one', tone: 'muted' };if (e.kind === 'api') return { text: 'No key yet · Add a key below to use it', tone: 'muted' };return { text: e.detail ?? (e.kind === 'local' ? 'Not running on this computer' : 'Not installed on this computer'), tone: 'muted' };case 'error':diff --git a/frontend/src/mcp.ts b/frontend/src/mcp.tsindex c8a5136d..f09baac3 100644--- a/frontend/src/mcp.ts+++ b/frontend/src/mcp.ts@@ -486,6 +486,10 @@ export interface EngineKeys {export const mcpSupportFor = (preferredModel: string, keys: EngineKeys): { supported: boolean; note: string | null } => {const model = (preferredModel || 'auto').toLowerCase();if (model === 'local_ollama' || model.startsWith('ollama/')) return { supported: true, note: null };+ // A Custom API pin, before the name checks: its model ids often say gpt or claude.+ if (model === 'custom' || /^custom[:/]/.test(model)) {+ return { supported: true, note: 'Tools work through an OpenAI-compatible server. An Anthropic-compatible one runs without them.' };+ }if (model.includes('claude')) {return keys.anthropic? { supported: false, note: 'With an Anthropic API key set, Claude runs through the Anthropic API, which can’t use MCP tools yet. Remove the key to use the Claude Code CLI instead.' }diff --git a/frontend/src/profiles.ts b/frontend/src/profiles.tsindex d21028ef..0c4ff741 100644--- a/frontend/src/profiles.ts+++ b/frontend/src/profiles.ts@@ -1,7 +1,27 @@// LLM profiles: one account per engine (a work and a personal Claude, say). Keys are write-only.-export type Engine = 'claude' | 'codex' | 'grok';-export type ProfileKind = 'system' | 'cli_home' | 'api_key';+export type Engine = 'claude' | 'codex' | 'grok' | 'custom';+export type ProfileKind = 'system' | 'cli_home' | 'api_key' | 'custom_api';++/** How a Custom API account's server talks: OpenAI chat completions or Anthropic Messages. */+export type CustomProtocol = 'openai-chat' | 'anthropic-messages';+export type CustomStatus = 'ready' | 'unreachable' | 'key_rejected' | 'error';++/** A Custom API account's server, as the server last checked it (GET {base}/models). */+export interface CustomServer {+ protocol: CustomProtocol;+ base_url: string;+ /** The model it runs when the bot doesn't pin one; null lets the server's list decide. */+ model: string | null;+ /** null: not checked yet. */+ status: CustomStatus | null;+ /** "Connected · 12 models", or the server's own words for what went wrong. */+ detail: string | null;+ models: Array<{ id: string; label: string; tier: 'fast' | 'balanced' | 'deep' | null; default: boolean }>;+ checked_at: string | null;+ /** MCP tools reach bots on it (OpenAI format only). */+ supports_tools: boolean;+}export interface Profile {id: string;@@ -18,6 +38,8 @@ export interface Profile {account_label: string | null;limited_until: string | null;last_error: 'quota' | 'auth' | null;+ /** Custom API accounts only. */+ custom?: CustomServer | null;}export type LoginStatus = 'starting' | 'waiting' | 'succeeded' | 'failed' | 'expired' | 'cancelled';@@ -37,17 +59,40 @@ export const ENGINES: Array<{ id: Engine; label: string }> = [{ id: 'claude', label: 'Claude' },{ id: 'codex', label: 'Codex (OpenAI)' },{ id: 'grok', label: 'Grok (xAI)' },+ { id: 'custom', label: 'Custom API' },];export const KIND_LABELS: Record<ProfileKind, string> = {system: 'This machine',cli_home: 'Subscription',api_key: 'API key',+ custom_api: 'Custom API',};+export const PROTOCOLS: Array<{ id: CustomProtocol; label: string; hint: string }> = [+ { id: 'openai-chat', label: 'OpenAI-compatible', hint: 'Bots can use tools' },+ { id: 'anthropic-messages', label: 'Anthropic-compatible', hint: 'No tools' },+];+export const protocolLabel = (p: CustomProtocol | string) => PROTOCOLS.find((x) => x.id === p)?.label ?? p;++/** Well-known servers, to fill the form. Agent Maestro serves GitHub Copilot's models from VS Code on the Mac. */+export const CUSTOM_PRESETS: Array<{ id: string; label: string; name: string; urls: Partial<Record<CustomProtocol, string>>; needsKey: boolean; note: string }> = [+ {+ id: 'maestro',+ label: 'Agent Maestro',+ name: 'Copilot',+ urls: { 'openai-chat': 'http://localhost:23333/api/openai/v1', 'anthropic-messages': 'http://localhost:23333/api/anthropic' },+ needsKey: false,+ note: 'GitHub Copilot models from VS Code. Keep VS Code open with Agent Maestro running.',+ },+ { id: 'openrouter', label: 'OpenRouter', name: 'OpenRouter', urls: { 'openai-chat': 'https://openrouter.ai/api/v1' }, needsKey: true, note: 'Needs an OpenRouter API key.' },+ { id: 'lmstudio', label: 'LM Studio', name: 'LM Studio', urls: { 'openai-chat': 'http://localhost:1234/v1' }, needsKey: false, note: 'Start LM Studio’s local server first.' },+];+/** The engine a kwant's model runs on, like the server's `Engine::from_model`; null for auto and Ollama. */export function engineOfModel(model: string | null | undefined): Engine | null {if (!model) return null;+ if (model === 'custom' || model.startsWith('custom:') || model.startsWith('custom/')) return 'custom';if (model.includes('claude')) return 'claude';if (model.includes('grok')) return 'grok';if (model.includes('codex') || model.includes('gpt') || model.includes('openai')) return 'codex';@@ -100,7 +145,7 @@ export type AccountTone = 'ok' | 'warn' | 'error' | 'muted' | 'info';/** An account's state in the words every screen uses: a one-word chip, and a line saying who or why. */export interface AccountState {- label: 'Ready' | 'Needs sign-in' | 'Off' | 'Out of usage' | 'Other provider' | 'No key' | 'Unknown';+ label: 'Ready' | 'Needs sign-in' | 'Off' | 'Out of usage' | 'Other provider' | 'No key' | 'Unknown' | 'Can’t connect' | 'Key rejected' | 'Error' | 'Not checked';tone: AccountTone;/** The email or provider when it's ready, else what to do; null when there's nothing to add. */detail: string | null;@@ -112,6 +157,7 @@ export function accountState(p: Profile, now = Date.now()): AccountState {const limit = activeLimit(p.limited_until, now);if (limit) return { label: 'Out of usage', tone: 'warn', detail: `Back ${formatUntil(limit, now)}` };if (p.last_error === 'auth') return { label: 'Needs sign-in', tone: 'error', detail: 'Its login stopped working. Sign in again.' };+ if (p.kind === 'custom_api') return customState(p.custom ?? null);if (p.kind === 'api_key') return p.has_key ? { label: 'Ready', tone: 'ok', detail: 'Key saved' } : { label: 'No key', tone: 'warn', detail: 'Add a key to use it' };if (p.signed_in === true) {if (isThirdPartyLabel(p.account_label)) {@@ -126,11 +172,27 @@ export function accountState(p: Profile, now = Date.now()): AccountState {return { label: 'Unknown', tone: 'muted', detail: p.kind === 'system' ? 'Uses this computer’s login' : 'Couldn’t check the sign-in (is the CLI installed?)' };}+/** A Custom API account's check, with the server's own words when it failed. */+function customState(c: CustomServer | null): AccountState {+ switch (c?.status) {+ case 'ready':+ return { label: 'Ready', tone: 'ok', detail: c.detail ?? 'Connected' };+ case 'unreachable':+ return { label: 'Can’t connect', tone: 'error', detail: c.detail ?? 'Nothing is answering at its address.' };+ case 'key_rejected':+ return { label: 'Key rejected', tone: 'error', detail: c.detail ?? 'The server refused the key. Replace it.' };+ case 'error':+ return { label: 'Error', tone: 'error', detail: c.detail ?? 'The check failed.' };+ default:+ return { label: 'Not checked', tone: 'muted', detail: 'Press Check again' };+ }+}+/** Short status for a profile, e.g. "Ready · [email protected]" or "Out of usage · Back in 45 min", for pickers. */export function profileStatus(p: Profile, now = Date.now()): { tone: AccountTone; text: string } {const s = accountState(p, now);// The email tells two ready accounts apart; Off and Needs sign-in say enough on their own.- const withDetail = s.label === 'Out of usage' || s.label === 'Other provider' || (s.label === 'Ready' && p.kind !== 'api_key');+ const withDetail = s.label === 'Out of usage' || s.label === 'Other provider' || (s.label === 'Ready' && p.kind !== 'api_key' && p.kind !== 'custom_api');return { tone: s.tone, text: withDetail && s.detail ? `${s.label} · ${s.detail}` : s.label };}@@ -162,15 +224,23 @@ export const profilesApi = {create: (body: {engine: Engine;name: string;- kind: 'cli_home' | 'api_key';+ kind: 'cli_home' | 'api_key' | 'custom_api';home_dir?: string;priority?: number;enabled?: boolean;is_default?: boolean;api_key?: string;+ protocol?: CustomProtocol;+ base_url?: string;+ model?: string;}) => request<Profile>('POST', '/api/profiles', body),- update: (id: string, body: { name?: string; priority?: number; enabled?: boolean; is_default?: boolean }) =>- request<Profile>('PATCH', `/api/profiles/${enc(id)}`, body),+ /** `protocol`, `base_url` and `model` ("" clears it) are for Custom API accounts, and re-check the server. */+ update: (+ id: string,+ body: { name?: string; priority?: number; enabled?: boolean; is_default?: boolean; protocol?: CustomProtocol; base_url?: string; model?: string },+ ) => request<Profile>('PATCH', `/api/profiles/${enc(id)}`, body),+ /** Checks a Custom API account's server again now. */+ check: (id: string) => request<Profile>('POST', `/api/profiles/${enc(id)}/check`),remove: (id: string) => request<void>('DELETE', `/api/profiles/${enc(id)}`),setKey: (id: string, apiKey: string) => request<void>('PUT', `/api/profiles/${enc(id)}/key`, { api_key: apiKey }),removeKey: (id: string) => request<void>('DELETE', `/api/profiles/${enc(id)}/key`),@@ -207,19 +277,28 @@ export function describeProfileSwitch(e: ProfileSwitchedEvent, kwantName: string// ---- Accounts on the "Engines & accounts" cards -----type EngineCardId = 'claude' | 'codex' | 'grok' | 'anthropic_api' | 'openai_api' | 'xai_api' | 'ollama';-const API_CARD: Record<Engine, EngineCardId> = { claude: 'anthropic_api', codex: 'openai_api', grok: 'xai_api' };+type EngineCardId = 'claude' | 'codex' | 'grok' | 'anthropic_api' | 'openai_api' | 'xai_api' | 'ollama' | 'custom_api';+type KeyedEngine = Exclude<Engine, 'custom'>;+const API_CARD: Record<KeyedEngine, EngineCardId> = { claude: 'anthropic_api', codex: 'openai_api', grok: 'xai_api' };++/** The engine card an account sits on: API-key accounts on the API engine, Custom API on its own, the rest on the CLI. */+export const cardOf = (p: Pick<Profile, 'engine' | 'kind'>): EngineCardId =>+ p.engine === 'custom' ? 'custom_api' : p.kind === 'api_key' ? API_CARD[p.engine] : p.engine;-/** The engine card an account sits on: API-key accounts on the API engine, the rest on the CLI. */-export const cardOf = (p: Pick<Profile, 'engine' | 'kind'>): EngineCardId => (p.kind === 'api_key' ? API_CARD[p.engine] : p.engine);+export type NewAccountSpec = { engine: Engine; kind: 'cli_home' | 'api_key' | 'custom_api' };/** The account family and kind a new account on this card gets; null where accounts can't be added. */-export function newAccountFor(card: string): { engine: Engine; kind: 'cli_home' | 'api_key' } | null {+export function newAccountFor(card: string): NewAccountSpec | null {if (card === 'claude' || card === 'codex' || card === 'grok') return { engine: card, kind: 'cli_home' };- const api = (Object.keys(API_CARD) as Engine[]).find((e) => API_CARD[e] === card);+ if (card === 'custom_api') return { engine: 'custom', kind: 'custom_api' };+ const api = (Object.keys(API_CARD) as KeyedEngine[]).find((e) => API_CARD[e] === card);return api ? { engine: api, kind: 'api_key' } : null;}+/** The space's Custom API accounts that answered their last check and are on, default first. */+export const readyCustomAccounts = (profiles: Profile[] | null | undefined): Profile[] =>+ profilesForEngine(profiles ?? [], 'custom').filter((p) => p.enabled && p.custom?.status === 'ready');+/** A card's accounts: "This machine" first, then the order turns try them (default, then priority). */export function accountsForCard(profiles: Profile[], card: string): Profile[] {return profiles@@ -237,8 +316,11 @@ export function accountsForCard(profiles: Profile[], card: string): Profile[] {* API-key account without its key, and not signed out on its last check. Not checked yet still counts,* so the server tries it; a refused turn's "auth" error doesn't matter until a check says signed out. */export const accountRoutable = (p: Profile, now = Date.now()) =>- !activeLimit(p.limited_until, now) && !(p.kind === 'api_key' && !p.has_key) && p.signed_in !== false;+ !activeLimit(p.limited_until, now) && !(p.kind === 'api_key' && !p.has_key) && p.signed_in !== false && (p.kind !== 'custom_api' || !p.custom?.status || p.custom.status === 'ready');/** Could run a turn as last checked: on, signed in (or keyed), not out of usage. */export const accountUsable = (p: Profile, now = Date.now()) =>- p.enabled && !activeLimit(p.limited_until, now) && p.last_error !== 'auth' && (p.kind === 'api_key' ? p.has_key : p.signed_in === true);+ p.enabled &&+ !activeLimit(p.limited_until, now) &&+ p.last_error !== 'auth' &&+ (p.kind === 'custom_api' ? p.custom?.status === 'ready' : p.kind === 'api_key' ? p.has_key : p.signed_in === true);diff --git a/frontend/src/routing.ts b/frontend/src/routing.tsindex d7dd62a5..1c742def 100644--- a/frontend/src/routing.ts+++ b/frontend/src/routing.ts@@ -39,9 +39,18 @@ const hostName = 'This machine';const accountName = (p: Profile) => (p.kind === 'system' ? hostName : p.name);const familyName = (f: Family) => FAMILIES.find((x) => x.id === f)!.label.replace(/ \(.*\)$/, '');+/** "localhost:23333" for a Custom API account, to tell its servers apart. */+const customHost = (p: Profile) => {+ try {+ return p.custom ? new URL(p.custom.base_url).host : 'Custom API';+ } catch {+ return 'Custom API';+ }+};+function describe(p: Profile): RouteAccount {const otherProvider = isThirdPartyLabel(p.account_label);- const detail = p.kind === 'api_key' ? 'API key' : otherProvider ? `via ${p.account_label === 'third_party' ? 'another provider' : p.account_label}` : p.account_label;+ const detail = p.kind === 'custom_api' ? customHost(p) : p.kind === 'api_key' ? 'API key' : otherProvider ? `via ${p.account_label === 'third_party' ? 'another provider' : p.account_label}` : p.account_label;return { name: accountName(p), detail, otherProvider };}@@ -61,6 +70,7 @@ export function tryOrder(profiles: Profile[], family: Family, now = Date.now()):/** Why a turn's first account may not run, or null when it was ready on its last check. */function startNote(p: Profile, now: number): string | null {if (activeLimit(p.limited_until, now)) return 'It’s out of usage and nothing else is ready, so bots will stop and say so.';+ if (p.kind === 'custom_api') return p.custom?.status && p.custom.status !== 'ready' ? 'Its server didn’t answer the last check and nothing else is ready, so bots will stop and say so.' : null;if (p.kind === 'api_key') return p.has_key ? null : 'It has no key and nothing else is ready, so bots will stop and say so.';if (p.signed_in === false) return 'It needs sign-in and nothing else is ready, so bots will stop and say so.';if (p.signed_in === null && p.kind !== 'system') return 'Its sign-in hasn’t been checked yet. Bots try it anyway.';diff --git a/frontend/tests/customApi.test.mjs b/frontend/tests/customApi.test.mjsnew file mode 100644index 00000000..bbb22307--- /dev/null+++ b/frontend/tests/customApi.test.mjs@@ -0,0 +1,134 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };++const m = await loadBundled(`+ export * from './src/engines';+ export { accountState, engineOfModel, readyCustomAccounts, accountUsable, CUSTOM_PRESETS } from './src/profiles';+ export { EnginesPanel } from './src/components/EnginesPanel';+ export { CustomServerForm } from './src/components/EngineAccounts';+ export { ModelPicker } from './src/components/ModelPicker';+ export { mcpSupportFor } from './src/mcp';+ export { renderToStaticMarkup } from 'react-dom/server.browser';+ export { createElement } from 'react';+`);+const h = m.createElement;++// Shaped like GET /api/engines for custom_api (f053aac): never installed, ready through accounts.+const customEngine = (over = {}) => ({+ id: 'custom_api', name: 'Custom API', kind: 'api', status: 'not_installed',+ detail: 'Runs on this space’s Custom API accounts: add one under Space settings → Accounts',+ version: null, models: [], checked_at: '2026-10-18T09:00:00Z', enabled: true, ready: false, uses: null, ...over,+});+const server = (over = {}) => ({+ protocol: 'openai-chat', base_url: 'http://localhost:23333/api/openai/v1', model: null, status: 'ready',+ detail: 'Connected · 2 models', checked_at: '2026-10-18T09:00:00Z', supports_tools: true,+ models: [{ id: 'gpt-4.1', label: 'gpt-4.1' }, { id: 'claude-sonnet-4', label: 'claude-sonnet-4' }], ...over,+});+const account = (over = {}, custom = {}) => ({+ id: 'prf_copilot', engine: 'custom', name: 'Copilot', kind: 'custom_api', enabled: true, is_default: false, priority: 100,+ home_dir: null, has_key: false, signed_in: true, account_label: null, limited_until: null, last_error: null,+ custom: server(custom), ...over,+});+const copilot = account();+const claudeFmt = account(+ { id: 'prf_anth', name: 'Copilot (Anthropic)' },+ { protocol: 'anthropic-messages', base_url: 'http://localhost:23333/api/anthropic/v1', supports_tools: false, models: [{ id: 'claude-sonnet-4', label: 'claude-sonnet-4' }], detail: 'Connected · 1 model' },+);+const down = account({ id: 'prf_down', name: 'Laptop', signed_in: false }, { status: 'unreachable', detail: 'Couldn’t reach http://localhost:9 (connection refused)', models: [] });+const badKey = account({ id: 'prf_bad', name: 'OpenRouter', has_key: true, signed_in: false }, { status: 'key_rejected', detail: 'The server refused the key (401 Unauthorized)', models: [] });++const api = (engines) => ({ engines, error: null, rechecking: false, recheck: async () => {}, reload: async () => {}, setEnabled: async () => {}, apply: () => {} });+const panel = (engines, profiles) =>+ m.renderToStaticMarkup(h(m.EnginesPanel, { api: api(engines), accounts: { profiles, error: null, reload: async () => {} }, now: Date.parse('2026-10-18T09:01:00Z') }));++test('custom pins parse and encode as custom:<model>', () => {+ assert.deepEqual(m.parsePick('custom:gpt-4.1'), { family: 'custom', model: 'gpt-4.1' });+ assert.deepEqual(m.parsePick('custom/gpt-4.1'), { family: 'custom', model: 'gpt-4.1' });+ assert.deepEqual(m.parsePick('custom'), { family: 'custom', model: null });+ assert.equal(m.encodePick('custom', 'gpt-4.1'), 'custom:gpt-4.1');+ assert.equal(m.encodePick('custom', null), 'custom');+ assert.equal(m.engineOfModel('custom:gpt-4.1'), 'custom');+ // A model id that merely starts with "custom" stays where it was.+ assert.notEqual(m.engineOfModel('customer-model'), 'custom');+});++test('each server status reads plainly, with the server detail verbatim', () => {+ assert.deepEqual([m.accountState(copilot).label, m.accountState(copilot).tone], ['Ready', 'ok']);+ assert.equal(m.accountState(copilot).detail, 'Connected · 2 models');+ assert.equal(m.accountState(down).label, 'Can’t connect');+ assert.equal(m.accountState(down).detail, 'Couldn’t reach http://localhost:9 (connection refused)');+ assert.equal(m.accountState(badKey).label, 'Key rejected');+ assert.equal(m.accountState(account({}, { status: 'error', detail: 'HTTP 500' })).label, 'Error');+ assert.equal(m.accountState(account({}, { status: null, detail: null })).label, 'Not checked');+ assert.ok(m.accountUsable(copilot));+ assert.ok(!m.accountUsable(down));+ assert.deepEqual(m.readyCustomAccounts([down, copilot, badKey, claudeFmt]).map((p) => p.id).sort(), ['prf_anth', 'prf_copilot']);+});++test('the Custom API card lists several servers with status, checks and the no-tools badge', () => {+ const html = panel([customEngine({ ready: true })], [copilot, claudeFmt, down, badKey]);+ assert.match(html, /data-engine="custom_api"/);+ assert.match(html, /Add a custom server/);+ assert.match(html, /Connected · 2 models/);+ assert.match(html, /Couldn’t reach http:\/\/localhost:9 \(connection refused\)/);+ assert.match(html, /The server refused the key \(401 Unauthorized\)/);+ assert.match(html, /Key rejected/);+ assert.match(html, /Can’t connect/);+ assert.equal((html.match(/Check again/g) ?? []).length, 4);+ // Only the Anthropic-format server says it has no tools.+ assert.equal((html.match(/data-no-tools/g) ?? []).length, 1);+ assert.match(html, /No tools \(Anthropic format\)/);+ assert.match(html, /data-custom-url="true"[^>]*>http:\/\/localhost:23333\/api\/anthropic\/v1</);+});++test('without servers the card invites one, naming Agent Maestro', () => {+ const html = panel([customEngine()], []);+ assert.match(html, /No servers yet\./);+ assert.match(html, /Agent Maestro \(GitHub Copilot\)/);+});++test('the form offers both formats, the Agent Maestro preset and a password key field', () => {+ const html = m.renderToStaticMarkup(h(m.CustomServerForm, { onCancel: () => {}, onSaved: () => {} }));+ assert.match(html, /data-custom-form="new"/);+ assert.match(html, /Use Agent Maestro/);+ assert.match(html, /OpenAI-compatible/);+ assert.match(html, /Anthropic-compatible/);+ assert.match(html, /type="password"/);+ assert.equal(m.CUSTOM_PRESETS.find((p) => p.id === 'maestro').urls['openai-chat'], 'http://localhost:23333/api/openai/v1');+ // Editing a ready server picks its model from the server's own list.+ const edit = m.renderToStaticMarkup(h(m.CustomServerForm, { account: copilot, onCancel: () => {}, onSaved: () => {} }));+ assert.match(edit, /data-custom-form="edit"/);+ assert.match(edit, /<option value="gpt-4.1">gpt-4.1<\/option>/);+ assert.doesNotMatch(edit, /type="password"/);+});++test('the bot editor offers custom models grouped and labelled by account', () => {+ const html = m.renderToStaticMarkup(h(m.ModelPicker, {+ value: 'custom:claude-sonnet-4', onChange: () => {}, engines: [customEngine({ ready: true })],+ profiles: [copilot, claudeFmt, down], profileId: 'prf_anth', onPickAccount: () => {},+ }));+ assert.match(html, /<optgroup label="Copilot">/);+ assert.match(html, /<optgroup label="Copilot \(Anthropic\)">/);+ assert.doesNotMatch(html, /label="Laptop"/);+ assert.match(html, /gpt-4.1 · Copilot</);+ // The pinned account's copy of a shared model is the one selected.+ assert.match(html, /value="prf_anth\nclaude-sonnet-4" selected=""/);+});++test('a custom pin never blames the Codex or Claude CLI for tools', () => {+ const keys = { anthropic: true, openai: false, xai: false };+ for (const pin of ['custom:gpt-4.1', 'custom:claude-sonnet-4', 'custom']) {+ const s = m.mcpSupportFor(pin, keys);+ assert.ok(s.supported, pin);+ assert.match(s.note, /OpenAI-compatible server/);+ }+});++test('ready accounts keep Custom API on offer while the engine list is still the old one', () => {+ const opts = m.familyOptions([customEngine({ ready: false })], [{ name: 'Copilot', models: [{ id: 'gpt-4.1', label: 'gpt-4.1' }] }]);+ assert.deepEqual(opts.map((o) => [o.id, o.via]), [['custom', ['Copilot']]]);+ assert.deepEqual(m.familyOptions([customEngine({ ready: false })]), []);+});diff --git a/frontend/tests/wording.test.mjs b/frontend/tests/wording.test.mjsindex 00873835..8f5a8721 100644--- a/frontend/tests/wording.test.mjs+++ b/frontend/tests/wording.test.mjs@@ -17,8 +17,10 @@ const files = (dir) =>);const BAD = /\b(kwants?|kwnt|agents?)\b/i;-// The product term (headings, tagline) and the CLI commands shown on the sign-in screen.+// The product term (headings, tagline), the CLI commands shown on the sign-in screen, and+// Agent Maestro, the VS Code extension's own name (a Custom API preset).const ALLOWED = /\bkwant bots?\b|\b(?:exec kwnt )?kwnt token\b/gi;+const MAESTRO = /\bAgent Maestro\b/g;/** Whether a literal reads like text a person sees (a sentence, or a capitalised word). */const looksVisible = (text, node) => {@@ -47,7 +49,7 @@ export function findBareWording() {else if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) s = node.text;else if (ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)) s = node.text;if (s !== null) {- const stripped = s.replace(ALLOWED, '');+ const stripped = s.replace(MAESTRO, '').replace(ALLOWED, '');// URLs, paths, event names and storage keys (kwnt:..., kwant.x) are not prose.// Example paths a person reads (~/dev/x) stay in.const prose = stripped.replace(/(?<!\S)(?!~)\S*(?:[:./_#=]\w)\S*/g, (w) => (/^[A-Za-z]+[.,;:!?)]?$/.test(w) ? w : ''));