Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): ship the providers, and put the model next to the box you type in

esengine1b359ad7c9f7
diff --git a/desktop/electron/agent/host.ts b/desktop/electron/agent/host.ts
index 2198560bb..f85ffee98 100644
--- a/desktop/electron/agent/host.ts
+++ b/desktop/electron/agent/host.ts
@@ -69,6 +69,13 @@ export interface AgentHost {
confirm(callId: string, allow: boolean): void;
/** Drop the conversation and start over; the next turn re-reads the key. */
reset(): AgentStatus;
+ /**
+ * Re-push the status because something OUTSIDE changed it — the window picked
+ * a different provider, so `ready` now answers differently. Without this the
+ * mirror only learns on the next transition, and the drawer keeps saying
+ * "no model configured" at a user who just configured one.
+ */
+ announce(): void;
}
export function createAgentHost(deps: AgentHostDeps): AgentHost {
@@ -181,6 +188,7 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
pushStatus();
}
},
+ announce: pushStatus,
reset: () => {
running?.abort();
running = null;
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 56953686f..159be0228 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -48,7 +48,7 @@ import { secretStatus, setSecret, clearSecret, readSecret } from './secrets';
import { createSurfaceDriver } from './surfaceDriver';
import { createAgentHost } from './agent/host';
import { createAnthropicProvider } from './agent/anthropic';
-import { AGENT_API_KEY } from '../src/settings/agentIds';
+
import {
discoverPlugins, compilePlugin, isTrusted, trustPlugin, revokeTrust, isDisabled, setPluginEnabled,
PROJECT_PLUGIN_DIR, USER_PLUGIN_DIR,
@@ -660,14 +660,16 @@ ipcMain.handle('secret:clear', (_e, id: string) => clearSecret(id));
// settings live in its localStorage) and merged, since the two rows fire
// separately; read at session creation, so a change lands on the next
// conversation rather than under the one being read.
-let agentEndpoint: { baseUrl?: string; model?: string } = {};
+let agentEndpoint: { baseUrl?: string; model?: string; keyId?: string } = {};
const agentHost = createAgentHost({
driver: createSurfaceDriver(() => win),
push: (message) => win?.webContents.send('agent:message', message),
- ready: () => secretStatus(AGENT_API_KEY).configured,
+ // Which key, like which endpoint, is the window's to decide: it is the side
+ // that knows which provider the user picked.
+ ready: () => !!agentEndpoint.keyId && secretStatus(agentEndpoint.keyId).configured,
provider: () => {
- const apiKey = readSecret(AGENT_API_KEY);
+ const apiKey = agentEndpoint.keyId ? readSecret(agentEndpoint.keyId) : null;
// Phrased for the person who will read it in the transcript, and it names
// where to fix it — a bare "401" or "missing apiKey" does neither.
if (!apiKey) throw new Error('No API key is configured. Add one in Settings › AI Agents.');
@@ -683,8 +685,10 @@ ipcMain.handle('agent:send', (_e, text: string) => agentHost.send(text));
ipcMain.handle('agent:stop', () => agentHost.stop());
ipcMain.handle('agent:confirm', (_e, callId: string, allow: boolean) => agentHost.confirm(callId, allow));
ipcMain.handle('agent:reset', () => agentHost.reset());
-ipcMain.handle('agent:setEndpoint', (_e, patch: { baseUrl?: string; model?: string }) => {
+ipcMain.handle('agent:setEndpoint', (_e, patch: { baseUrl?: string; model?: string; keyId?: string }) => {
agentEndpoint = { ...agentEndpoint, ...patch };
+ // `ready` is derived from which key this points at, so it just changed.
+ agentHost.announce();
});
// — Custom window controls (frameless Windows/Linux; macOS uses native traffic lights) —
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 14af544eb..3a94d0954 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -121,7 +121,7 @@ const api = {
reset: (): Promise<AgentStatus> => ipcRenderer.invoke('agent:reset'),
/** Point the NEXT session at an endpoint/model. Merged, so each settings row
* can push its own field. */
- setEndpoint: (patch: { baseUrl?: string; model?: string }): Promise<void> =>
+ setEndpoint: (patch: { baseUrl?: string; model?: string; keyId?: string }): Promise<void> =>
ipcRenderer.invoke('agent:setEndpoint', patch),
/** Transcript events + status changes, in the order they happened; returns
* an unsubscribe. One channel because the two must not be reordered. */
diff --git a/desktop/src/agent/providers.ts b/desktop/src/agent/providers.ts
new file mode 100644
index 000000000..84b709e98
--- /dev/null
+++ b/desktop/src/agent/providers.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file providers.ts — who the built-in agent can talk to.
+ *
+ * The unit of CONFIGURATION is a provider; the unit of CHOICE is a model. A
+ * provider's endpoint, dialect and model list are all knowable in advance, so
+ * shipping them means nobody types a URL from memory — and on a gateway that
+ * silently downgrades an unrecognised model name, a typo is not an error, it is
+ * a quietly worse answer for the rest of the session.
+ *
+ * The editor already ships this kind of vendor knowledge for export targets
+ * (project/platforms.ts), and this is the same shape: a registry, so a plugin
+ * can add one without this file knowing it exists.
+ *
+ * Keys are per provider and all kept at once. Switching back to one you used
+ * last week should not mean finding the key again — that is the whole point of
+ * supporting more than one.
+ */
+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';
+
+export interface AgentProviderDef {
+ id: string;
+ label: string;
+ /**
+ * Empty means the Anthropic API itself. Anything else is an
+ * Anthropic-COMPATIBLE gateway, and its presence is what drops the request to
+ * the core wire format (electron/agent/anthropic.ts).
+ */
+ baseUrl: string;
+ /** What this provider offers, best-first. */
+ models: readonly string[];
+ /** Filled in from settings rather than shipped — see {@link CUSTOM_PROVIDER}. */
+ userDefined?: boolean;
+}
+
+/** The id a provider's key is stored under (electron/secrets.ts). */
+export const agentKeyId = (providerId: string): string => `agents.key.${providerId}`;
+
+export const CUSTOM_PROVIDER = 'custom';
+
+const registry = new ContributionRegistry<AgentProviderDef>('agent provider');
+
+registry.registerAll('core', [
+ {
+ id: 'anthropic',
+ label: 'Anthropic',
+ baseUrl: '',
+ models: ['claude-opus-5', 'claude-sonnet-5', 'claude-haiku-4-5'],
+ },
+ {
+ id: 'deepseek',
+ label: 'DeepSeek',
+ baseUrl: 'https://api.deepseek.com/anthropic',
+ models: ['deepseek-v4-pro', 'deepseek-v4-flash'],
+ },
+ // The escape hatch. Its endpoint and model list come from settings, because a
+ // provider we have not heard of is exactly the one we cannot ship a list for.
+ {
+ id: CUSTOM_PROVIDER,
+ label: '',
+ baseUrl: '',
+ models: [],
+ userDefined: true,
+ },
+]);
+
+export const agentProviders = (): AgentProviderDef[] => [...registry.all()];
+export const agentProvider = (id: string): AgentProviderDef | undefined => registry.get(id);
+export const subscribeProviders = (fn: () => void): (() => void) => registry.subscribe(fn);
+/** Scalar snapshot for useSyncExternalStore — {@link agentProviders} hands back
+ * a fresh array each call, which as a snapshot re-renders forever. */
+export const providersRevision = (): number => registry.getRevision();
+
+/** Contribute a provider (a plugin's extension point). */
+export const registerAgentProvider = (def: AgentProviderDef, owner: Owner = 'core'): Disposable =>
+ registry.register(owner, def);
+
+/** Split the custom provider's model list — one per line or comma-separated,
+ * because a person pasting three model names should not have to guess which. */
+export const parseModelList = (raw: string): string[] =>
+ raw.split(/[\n,]/).map((s) => s.trim()).filter(Boolean);
diff --git a/desktop/src/components/AgentDrawer.tsx b/desktop/src/components/AgentDrawer.tsx
index 093d212ed..a82d2d4fa 100644
--- a/desktop/src/components/AgentDrawer.tsx
+++ b/desktop/src/components/AgentDrawer.tsx
@@ -23,17 +23,22 @@
* COLOUR MEANS SOMETHING. Green added, red failed, amber needs you. Nothing
* is tinted for belonging to the agent.
*/
-import { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react';
import {
- X, Plus, PanelRight, ArrowUp, Square, ChevronRight, Check, TriangleAlert,
+ X, Plus, PanelRight, ArrowUp, Square, ChevronRight, ChevronDown, Check, TriangleAlert,
Loader, Copy, Pencil, Eye, KeyRound, Boxes, Stethoscope, Image as ImageIcon,
} from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import {
useAgent, sendAgentMessage, stopAgentTurn, confirmAgentCall, resetAgentSession,
- peekEntities, entitiesInInput,
+ peekEntities, entitiesInInput, effectiveSelection, selectAgentModel,
type AgentTurn, type AgentEntry, type AgentToolEntry,
} from '@/store/AgentStore';
+import {
+ agentProviders, agentProvider, agentKeyId, parseModelList, subscribeProviders, providersRevision,
+} from '@/agent/providers';
+import { secretStatus, subscribeSecrets, secretRevision } from '@/store/SecretStore';
+import { useSettings } from '@/store/settingsStore';
import { t } from '@/i18n';
const TOOL_ICON: Record<string, typeof Eye> = {
@@ -262,6 +267,94 @@ function EmptyState() {
);
}
+/**
+ * Which model the next message runs on, next to the box you type it in — a
+ * per-message decision (cheap and quick to rename a thing, strong to build one),
+ * not a preference buried two dialogs away.
+ *
+ * Providers with no key are still listed, greyed, and lead to Settings: "you
+ * could use this, here is what is missing" beats hiding it and leaving the user
+ * to wonder whether the editor supports their provider at all.
+ */
+function ModelPicker() {
+ const [open, setOpen] = useState(false);
+ const picked = useAgent((s) => s.selection);
+ useAgent((s) => s.status.ready);
+ useSyncExternalStore(subscribeSecrets, () => secretRevision());
+ useSyncExternalStore(subscribeProviders, providersRevision);
+ const providers = agentProviders();
+ const current = effectiveSelection();
+
+ useEffect(() => {
+ if (!open) return;
+ const close = () => setOpen(false);
+ window.addEventListener('mousedown', close);
+ return () => window.removeEventListener('mousedown', close);
+ }, [open]);
+ void picked;
+
+ return (
+ <div className="ag-picker" onMouseDown={(e) => e.stopPropagation()}>
+ <button type="button" className="ag-picker-btn" onClick={() => setOpen((o) => !o)}>
+ {current?.model ?? t('agent.picker.none')}
+ <ChevronDown size={11} strokeWidth={2} />
+ </button>
+ {open && (
+ <div className="ag-picker-menu">
+ {providers.map((p) => {
+ const def = resolveProviderModels(p.id);
+ const keyed = secretStatus(agentKeyId(p.id))?.configured === true;
+ if (def.models.length === 0 && !def.label) return null;
+ return (
+ <div className="ag-picker-grp" key={p.id}>
+ <div className="ag-picker-h">
+ {def.label}
+ {!keyed && <span className="ag-picker-nokey">{t('agent.picker.noKey')}</span>}
+ </div>
+ {def.models.length === 0 && (
+ <button type="button" className="ag-picker-it empty" onClick={() => openAgentSettings()}>
+ {t('agent.picker.configure')}
+ </button>
+ )}
+ {def.models.map((m) => (
+ <button
+ type="button"
+ key={m}
+ className={`ag-picker-it${current?.model === m && current.providerId === p.id ? ' on' : ''}${keyed ? '' : ' locked'}`}
+ onClick={() => {
+ setOpen(false);
+ if (keyed) selectAgentModel(p.id, m);
+ else openAgentSettings();
+ }}
+ >
+ {m}
+ {current?.model === m && current.providerId === p.id && <Check size={12} strokeWidth={2.2} />}
+ </button>
+ ))}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
+
+const openAgentSettings = () => useEditorStore.getState().openSettings('agents');
+
+/** The custom provider's list comes from settings; the rest ship theirs. */
+function resolveProviderModels(id: string): { label: string; models: readonly string[] } {
+ const def = agentProvider(id);
+ if (!def) return { label: '', models: [] };
+ if (def.userDefined) {
+ return {
+ label: t('agent.picker.custom'),
+ models: parseModelList(String(useSettings.getState().getValue('agents.customModels') ?? '')),
+ };
+ }
+ return { label: def.label, models: def.models };
+}
+
function Compose() {
const status = useAgent((s) => s.status);
const [draft, setDraft] = useState('');
@@ -300,6 +393,7 @@ function Compose() {
}
}}
/>
+ <ModelPicker />
<button
type="button"
className="ag-send"
@@ -352,7 +446,6 @@ export function AgentDrawer() {
<div className="ag-head">
<span className="ag-ttl">{t('agent.title')}</span>
<span className="ag-sp" />
- {status.model && <span className="ag-model">{status.model}</span>}
<button type="button" title={t('agent.newConversation')} onClick={() => void resetAgentSession()}>
<Plus size={14} strokeWidth={2} />
</button>
diff --git a/desktop/src/i18n/messages/agent.ts b/desktop/src/i18n/messages/agent.ts
index 1570f1c69..56a30fb50 100644
--- a/desktop/src/i18n/messages/agent.ts
+++ b/desktop/src/i18n/messages/agent.ts
@@ -27,6 +27,12 @@ export const agentMessages = defineMessages({
'agent.hint.newline': { en: 'new line', zh: '换行' },
'agent.hint.close': { en: 'close', zh: '关闭' },
+ // — Which model the next message runs on —
+ 'agent.picker.none': { en: 'Pick a model', zh: '选择模型' },
+ 'agent.picker.noKey': { en: 'no key', zh: '未配置密钥' },
+ 'agent.picker.configure': { en: 'Set it up in Settings…', zh: '去设置里配置…' },
+ 'agent.picker.custom': { en: 'Custom', zh: '自定义' },
+
// — Empty states —
'agent.empty.title': { en: 'Ask the agent to do something', zh: '让 Agent 帮你做点什么' },
'agent.empty.body': {
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index 51a263d60..dcb97f8ab 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -114,21 +114,23 @@ export const settingsMessages = defineMessages({
},
// — AI Agents —
- 'set.agents.apiKey': { en: 'Anthropic API key', zh: 'Anthropic API 密钥' },
- 'set.agents.apiKey.desc': {
- en: 'What the built-in agent authenticates with. Held by the system keychain — never written to the project or the settings file, and never handed back to this window.',
- zh: '内置 Agent 用它调用模型。密钥存在系统钥匙串里——不写进项目、不写进设置文件,也不会交回给这个窗口。',
- },
- 'set.agents.baseUrl': { en: 'API endpoint', zh: 'API 地址' },
- 'set.agents.baseUrl.desc': {
- en: 'Leave empty for the Anthropic API. Point it at an Anthropic-compatible gateway (for example https://api.deepseek.com/anthropic) to run another vendor’s models — the agent then sends only the core Messages format, without extended thinking, prompt caching or automatic fallbacks.',
- zh: '留空则使用 Anthropic API。填入兼容 Anthropic 的网关地址(例如 https://api.deepseek.com/anthropic)即可换用其他厂商的模型——此时 Agent 只发送基础 Messages 格式,不带扩展思考、提示缓存和自动回退。',
- },
- 'set.agents.model': { en: 'Model', zh: '模型' },
- 'set.agents.model.desc': {
- en: 'Leave empty to use the default. Name the model when using a gateway — some map an unrecognised name to their smallest model instead of refusing it.',
- zh: '留空则使用默认模型。使用网关时请写明模型名——有些网关遇到无法识别的名字不会报错,而是改用它们最小的模型。',
- },
+ 'set.agents.providerKey': { en: '{provider} API key', zh: '{provider} API 密钥' },
+ 'set.agents.providerKey.desc': {
+ en: 'Held by the system keychain — never written to the project or the settings file, and never handed back to this window. Every provider keeps its own, so switching back to one costs nothing.',
+ zh: '存在系统钥匙串里——不写进项目、不写进设置文件,也不会交回给这个窗口。每个提供方各存各的,切回来不用重输。',
+ },
+ 'set.group.customProvider': { en: 'Custom Provider', zh: '自定义提供方' },
+ 'set.agents.customBaseUrl': { en: 'Endpoint', zh: 'API 地址' },
+ 'set.agents.customBaseUrl.desc': {
+ en: 'An Anthropic-compatible endpoint. Only needed for a provider not in the list — the built-in ones already know their address. The agent then sends only the core Messages format, without extended thinking, prompt caching or automatic fallbacks.',
+ zh: '兼容 Anthropic 的接口地址。只有列表里没有的提供方才需要填——内置的那些自己知道地址。此时 Agent 只发送基础 Messages 格式,不带扩展思考、提示缓存和自动回退。',
+ },
+ 'set.agents.customModels': { en: 'Models', zh: '模型' },
+ 'set.agents.customModels.desc': {
+ en: 'The model names this endpoint offers, comma- or newline-separated. They become choices in the composer.',
+ zh: '这个接口提供的模型名,用逗号或换行分隔。它们会出现在输入框的模型选择器里。',
+ },
+ 'set.agents.customKey': { en: 'Custom API key', zh: '自定义提供方密钥' },
'set.agents.mcpEnabled': { en: 'Allow AI agents to connect', zh: '允许 AI 代理连接' },
'set.agents.mcpEnabled.desc': {
en: 'Serve this editor over MCP on a local-only port, so an agent set up with --attach can drive the project you have open. Off means nothing is listening.',
diff --git a/desktop/src/settings/agentIds.ts b/desktop/src/settings/agentIds.ts
index b72a74755..146a2250b 100644
--- a/desktop/src/settings/agentIds.ts
+++ b/desktop/src/settings/agentIds.ts
@@ -3,19 +3,12 @@
/**
* @file agentIds.ts — the built-in agent's constants, shared by both processes.
*
- * Shared on purpose: the settings row registers under an id and main reads back
- * under the same one, and a secret written under an id nobody reads is
- * indistinguishable from a machine that lost its keychain. Likewise the default
- * model — main falls back to it and the settings row shows it as the
- * placeholder, so a second copy would eventually tell the user something untrue.
- *
* A leaf module with no imports, so main can take it without pulling the editor
- * in (the same reason plugins/paths.ts exists).
+ * in (the same reason plugins/paths.ts exists). Key ids are NOT here — they are
+ * per provider and derived (agent/providers.ts), and the window is the side that
+ * knows which provider was picked.
*/
-/** The built-in agent's model credential. Also its settings-row id. */
-export const AGENT_API_KEY = 'agents.apiKey';
-
/** What runs when the model setting is blank. Opus-tier because this drives a
* real project: a wrong edit costs the user their scene, and the turn's
* checkpoint only helps if the plan was sane. */
diff --git a/desktop/src/settings/editorSettings.ts b/desktop/src/settings/editorSettings.ts
index d278eb612..654009212 100644
--- a/desktop/src/settings/editorSettings.ts
+++ b/desktop/src/settings/editorSettings.ts
@@ -19,8 +19,8 @@ import { EngineHost } from '@/engine/EngineHost';
import { Toasts } from '@/store/Toasts';
import { mcpStatus, setMcpEnabled, subscribeMcp } from '@/store/McpStore';
import { secretStatusLine, subscribeSecrets } from '@/store/SecretStore';
-import { setAgentEndpoint } from '@/store/AgentStore';
-import { AGENT_API_KEY, DEFAULT_MODEL } from './agentIds';
+import { syncAgentEndpoint } from '@/store/AgentStore';
+import { agentProviders, agentKeyId, CUSTOM_PROVIDER } from '@/agent/providers';
import { t, editorLocale, systemDefaultLocale, EDITOR_LOCALES, LANGUAGE_SETTING_ID } from '@/i18n';
const root = () => document.documentElement.style;
@@ -235,58 +235,63 @@ settingsRegistry.register({
});
// ── AI Agents ───────────────────────────────────────────────────────────────
-// The built-in agent's credential. Registered before the MCP row because it is
-// the one an ordinary user needs; the endpoint below is for agents that live
-// outside the editor.
-//
-// The value is never here: this descriptor carries no more than its id, and the
-// key itself lives in main behind the OS keychain (electron/secrets.ts). That is
-// what keeps it out of localStorage, which is where every OTHER setting is.
+// The unit of configuration is a PROVIDER, and every one keeps its own key —
+// switching back to one you used last week must not mean finding its key again.
+// Which model runs is picked in the composer instead, because that is a
+// per-message decision, not a preference (src/agent/providers.ts).
+for (const provider of agentProviders()) {
+ if (provider.userDefined) continue;
+ settingsRegistry.register({
+ id: agentKeyId(provider.id),
+ type: 'secret',
+ scope: 'editor',
+ section: 'agents',
+ group: t('set.group.builtinAgent'),
+ label: t('set.agents.providerKey', { provider: provider.label }),
+ description: t('set.agents.providerKey.desc', { provider: provider.label }),
+ placeholder: 'sk-…',
+ default: false,
+ status: { read: () => secretStatusLine(agentKeyId(provider.id)), subscribe: subscribeSecrets },
+ });
+}
+
+// The escape hatch, for a provider we have not heard of — which is exactly the
+// one we cannot ship an endpoint or a model list for.
settingsRegistry.register({
- id: AGENT_API_KEY,
- type: 'secret',
+ id: 'agents.customBaseUrl',
+ type: 'string',
scope: 'editor',
section: 'agents',
- group: t('set.group.builtinAgent'),
- label: t('set.agents.apiKey'),
- description: t('set.agents.apiKey.desc'),
- placeholder: 'sk-ant-…',
- default: false,
- status: { read: () => secretStatusLine(AGENT_API_KEY), subscribe: subscribeSecrets },
+ group: t('set.group.customProvider'),
+ label: t('set.agents.customBaseUrl'),
+ description: t('set.agents.customBaseUrl.desc'),
+ placeholder: 'https://example.com/anthropic',
+ default: '',
+ effect: () => syncAgentEndpoint(),
});
-// The endpoint and model are pushed to main rather than read by it: settings
-// live in this window's localStorage, and main owns the session. Same path as
-// the MCP toggle — one setter, replayed at boot by applySettings(), so the two
-// processes cannot hold different answers.
-//
-// They take effect on the NEXT conversation. Rebuilding a live session on a
-// keystroke would throw away the transcript the user is reading, and a string
-// field commits on every keystroke.
settingsRegistry.register({
- id: 'agents.baseUrl',
+ id: 'agents.customModels',
type: 'string',
scope: 'editor',
section: 'agents',
- group: t('set.group.builtinAgent'),
- label: t('set.agents.baseUrl'),
- description: t('set.agents.baseUrl.desc'),
- placeholder: 'https://api.anthropic.com',
+ group: t('set.group.customProvider'),
+ label: t('set.agents.customModels'),
+ description: t('set.agents.customModels.desc'),
+ placeholder: 'model-a, model-b',
default: '',
- effect: (v) => setAgentEndpoint({ baseUrl: v }),
+ effect: () => syncAgentEndpoint(),
});
settingsRegistry.register({
- id: 'agents.model',
- type: 'string',
+ id: agentKeyId(CUSTOM_PROVIDER),
+ type: 'secret',
scope: 'editor',
section: 'agents',
- group: t('set.group.builtinAgent'),
- label: t('set.agents.model'),
- description: t('set.agents.model.desc'),
- placeholder: DEFAULT_MODEL,
- default: '',
- effect: (v) => setAgentEndpoint({ model: v }),
+ group: t('set.group.customProvider'),
+ label: t('set.agents.customKey'),
+ default: false,
+ status: { read: () => secretStatusLine(agentKeyId(CUSTOM_PROVIDER)), subscribe: subscribeSecrets },
});
// ── External agents (main-owned endpoint, driven from here) ─────────────────
diff --git a/desktop/src/store/AgentStore.ts b/desktop/src/store/AgentStore.ts
index e6c69ff80..c0eb921f3 100644
--- a/desktop/src/store/AgentStore.ts
+++ b/desktop/src/store/AgentStore.ts
@@ -19,6 +19,11 @@
import { create } from 'zustand';
import type { AgentStatus, AgentMessage } from '../../electron/agent/host';
import type { AgentEvent, ConfirmReason, ConfirmRequest } from '../../electron/agent/types';
+import {
+ agentProviders, agentProvider, agentKeyId, parseModelList, CUSTOM_PROVIDER,
+} from '@/agent/providers';
+import { refreshSecret, secretStatus, subscribeSecrets } from '@/store/SecretStore';
+import { useSettings } from '@/store/settingsStore';
export type { AgentStatus, AgentEvent };
@@ -98,13 +103,98 @@ interface AgentState {
peeked: readonly number[];
/** The turn whose checkpoint bar has been answered — see AgentCheckpoint. */
checkpointDone: number | null;
+ /** What the user picked, or null for "whichever provider has a key". */
+ selection: AgentSelection | null;
}
export const useAgent = create<AgentState>(() => ({
status: IDLE, turns: [], driving: false, peeked: [], checkpointDone: null,
+ selection: loadSelection(),
}));
export const peekEntities = (ids: readonly number[]): void => useAgent.setState({ peeked: ids });
+
+// ── Which provider and model the next conversation runs on ──────────────────
+// Persisted here rather than as a registered setting: it is picked from the
+// composer, and a settings row for it would be a second control for one choice.
+
+const SELECTION_KEY = 'estella.agent.selection';
+
+export interface AgentSelection {
+ providerId: string;
+ model: string;
+}
+
+function loadSelection(): AgentSelection | null {
+ try {
+ const raw = localStorage.getItem(SELECTION_KEY);
+ return raw ? (JSON.parse(raw) as AgentSelection) : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The custom provider's endpoint and models come from settings — it is the one
+ * we cannot ship a list for. */
+function resolveProvider(id: string) {
+ const def = agentProvider(id);
+ if (!def) return undefined;
+ if (id !== CUSTOM_PROVIDER) return def;
+ const settings = useSettings.getState();
+ return {
+ ...def,
+ baseUrl: String(settings.getValue('agents.customBaseUrl') ?? ''),
+ models: parseModelList(String(settings.getValue('agents.customModels') ?? '')),
+ };
+}
+
+const hasKey = (providerId: string): boolean =>
+ secretStatus(agentKeyId(providerId))?.configured === true;
+
+/**
+ * What the next conversation will use.
+ *
+ * With nothing picked, the first provider that has a key IS the answer — so
+ * configuring a key is the whole setup, and a person who only ever uses one
+ * provider never opens the picker at all.
+ */
+export function effectiveSelection(): AgentSelection | null {
+ const picked = useAgent.getState().selection;
+ if (picked && resolveProvider(picked.providerId)) return picked;
+ for (const p of agentProviders()) {
+ const def = resolveProvider(p.id);
+ if (def && def.models.length > 0 && hasKey(p.id)) return { providerId: p.id, model: def.models[0] };
+ }
+ return null;
+}
+
+/** Tell main what to build the next session against. Called on every input to
+ * that answer: the pick, a key appearing, a custom endpoint being typed. */
+export function syncAgentEndpoint(): void {
+ const selection = effectiveSelection();
+ const def = selection ? resolveProvider(selection.providerId) : undefined;
+ void window.estella?.agent?.setEndpoint({
+ baseUrl: def?.baseUrl ?? '',
+ model: selection?.model ?? '',
+ keyId: selection ? agentKeyId(selection.providerId) : '',
+ });
+}
+
+/**
+ * Pick a provider + model. A conversation already under way is ENDED rather
+ * than continued: a session is built for one model, thinking blocks have to
+ * come back to the model that produced them, and the cached prefix is a byte
+ * match — so "same conversation, different model" is not a thing that exists.
+ */
+export function selectAgentModel(providerId: string, model: string): void {
+ const selection: AgentSelection = { providerId, model };
+ useAgent.setState({ selection });
+ try {
+ localStorage.setItem(SELECTION_KEY, JSON.stringify(selection));
+ } catch { /* private mode — it just will not persist */ }
+ syncAgentEndpoint();
+ if (useAgent.getState().turns.length > 0) void resetAgentSession();
+}
export const dismissCheckpoint = (turnId: number): void => useAgent.setState({ checkpointDone: turnId });
/** The run still taking events, if any. Only the last one can be open. */
@@ -243,7 +333,12 @@ export function applyAgentMessage(message: AgentMessage): void {
export function attachAgentBridge(): () => void {
const off = window.estella?.agent?.onMessage(applyAgentMessage) ?? (() => {});
void window.estella?.agent?.status().then(adoptStatus);
- return off;
+ // Which keys exist decides which provider runs when nothing is picked, so ask
+ // once at boot rather than the first time a settings row happens to render.
+ for (const p of agentProviders()) void refreshSecret(agentKeyId(p.id)).then(syncAgentEndpoint);
+ const offSecrets = subscribeSecrets(syncAgentEndpoint);
+ syncAgentEndpoint();
+ return () => { off(); offSecrets(); };
}
export async function sendAgentMessage(text: string): Promise<void> {
@@ -261,18 +356,7 @@ export function stopAgentTurn(): void {
void window.estella?.agent?.stop();
}
-/**
- * Tell main which endpoint and model to build the next session against.
- *
- * Pushed rather than read: settings live in this window's localStorage and main
- * owns the session, so this is the same one-way path the MCP toggle uses. The
- * settings' `effect` calls it — including the boot replay — and a partial patch
- * is merged in main, because the two rows are separate settings that each fire
- * on their own.
- */
-export function setAgentEndpoint(patch: { baseUrl?: string; model?: string }): void {
- void window.estella?.agent?.setEndpoint(patch);
-}
+
/**
* Answer a pending confirmation. The row moves on the click rather than on
diff --git a/desktop/src/store/SecretStore.ts b/desktop/src/store/SecretStore.ts
index e8f8aa816..665d5786d 100644
--- a/desktop/src/store/SecretStore.ts
+++ b/desktop/src/store/SecretStore.ts
@@ -36,6 +36,11 @@ export const secretStatus = (id: string): SecretStatus | undefined => store.getS
/** Re-render on any change (useSyncExternalStore / plain subscriber). */
export const subscribeSecrets = (fn: () => void): (() => void) => store.subscribe(fn);
+/** A scalar snapshot for useSyncExternalStore — the map itself is rebuilt on
+ * every adopt, so a component reading it directly would loop. */
+export const secretRevision = (): number => Object.keys(store.getState().byId).length
+ + Object.values(store.getState().byId).filter((s) => s.configured).length * 1000;
+
export async function refreshSecret(id: string): Promise<SecretStatus | undefined> {
const status = await window.estella?.secrets?.status(id);
return status && adopt(status);
diff --git a/desktop/src/theme/agent.css b/desktop/src/theme/agent.css
index 6faf0eed6..92186a581 100644
--- a/desktop/src/theme/agent.css
+++ b/desktop/src/theme/agent.css
@@ -440,3 +440,59 @@
.act-agent.asking::after { animation: ag-pulse 1.6s ease-in-out infinite; }
}
@keyframes ag-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
+
+/* ── Which model the next message runs on ───────────────────────────────────
+ In the composer, because it is a per-message decision — cheap and quick to
+ rename a thing, strong to build one — and not a preference. */
+.ag-picker { position: relative; flex: none; }
+.ag-picker-btn {
+ display: flex; align-items: center; gap: 4px;
+ height: 27px;
+ padding: 0 6px 0 8px;
+ border-radius: var(--r-sm);
+ font: var(--fs-2xs) var(--font-mono);
+ color: var(--text-faint);
+ max-width: 150px;
+ white-space: nowrap; overflow: hidden;
+ transition: color var(--t-fast), background var(--t-fast);
+}
+.ag-picker-btn:hover { color: var(--text); background: var(--hover); }
+.ag-picker-menu {
+ position: absolute;
+ right: 0;
+ bottom: calc(100% + 6px);
+ z-index: 8;
+ min-width: 210px;
+ max-height: 300px;
+ overflow: auto;
+ padding: 5px;
+ border-radius: var(--r-md, 6px);
+ background: var(--raised);
+ border: 1px solid var(--line-strong);
+ box-shadow: 0 18px 44px -10px rgba(0, 0, 0, 0.85);
+}
+.ag-picker-h {
+ display: flex; align-items: center; gap: 7px;
+ padding: 6px 8px 4px;
+ font: 500 var(--fs-2xs) var(--font-ui);
+ letter-spacing: 0.09em;
+ text-transform: uppercase;
+ color: var(--text-faint);
+}
+/* Listed but not offered: "you could use this, and here is what is missing"
+ beats hiding it and leaving the user to wonder if we support their provider. */
+.ag-picker-nokey { text-transform: none; letter-spacing: 0; color: var(--warn); font-family: var(--font-mono); }
+.ag-picker-grp + .ag-picker-grp { border-top: 1px solid var(--line); margin-top: 4px; padding-top: 2px; }
+.ag-picker-it {
+ display: flex; align-items: center; gap: 8px;
+ width: 100%;
+ padding: 6px 8px;
+ border-radius: var(--r-sm);
+ font: var(--fs-xs) var(--font-mono);
+ color: var(--text);
+ text-align: left;
+}
+.ag-picker-it svg { margin-left: auto; color: var(--star-hi); }
+.ag-picker-it:hover { background: var(--hover); }
+.ag-picker-it.on { color: var(--text-hi); }
+.ag-picker-it.locked, .ag-picker-it.empty { color: var(--text-faint); font-family: var(--font-ui); }
diff --git a/desktop/tests/agent-providers.test.ts b/desktop/tests/agent-providers.test.ts
new file mode 100644
index 000000000..85db0c5ab
--- /dev/null
+++ b/desktop/tests/agent-providers.test.ts
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The shipped provider catalog. The point of shipping it is that nobody
+ * types an endpoint or a model name from memory — so the values being
+ * RIGHT is the feature, and on a gateway that maps an unrecognised model
+ * to its smallest one, a wrong name is not an error, it is a quietly
+ * worse answer for the rest of the session.
+ */
+import { describe, it, expect } from 'vitest';
+import { agentProviders, agentProvider, agentKeyId, parseModelList, CUSTOM_PROVIDER } from '@/agent/providers';
+
+describe('the shipped providers', () => {
+ it('knows DeepSeek without being told', () => {
+ const deepseek = agentProvider('deepseek');
+ expect(deepseek?.baseUrl).toBe('https://api.deepseek.com/anthropic');
+ expect(deepseek?.models).toEqual(['deepseek-v4-pro', 'deepseek-v4-flash']);
+ });
+
+ // An empty baseUrl is what selects the native dialect (agent/anthropic.ts);
+ // giving Anthropic a URL here would silently strip its own extensions.
+ it('leaves Anthropic without an endpoint, which is what picks the native dialect', () => {
+ expect(agentProvider('anthropic')?.baseUrl).toBe('');
+ expect(agentProvider('anthropic')?.models[0]).toBe('claude-opus-5');
+ });
+
+ it('keeps one key per provider, so switching back costs nothing', () => {
+ const ids = agentProviders().map((p) => agentKeyId(p.id));
+ expect(new Set(ids).size).toBe(ids.length);
+ expect(agentKeyId('deepseek')).toBe('agents.key.deepseek');
+ });
+
+ it('ships the custom slot empty — it is the one we cannot know', () => {
+ const custom = agentProvider(CUSTOM_PROVIDER);
+ expect(custom?.userDefined).toBe(true);
+ expect(custom?.models).toEqual([]);
+ });
+});
+
+// Someone pasting three model names should not have to guess which separator.
+describe('the custom model list', () => {
+ it('takes commas or newlines, and ignores the gaps', () => {
+ expect(parseModelList('a, b,c')).toEqual(['a', 'b', 'c']);
+ expect(parseModelList('a\n b \n\nc')).toEqual(['a', 'b', 'c']);
+ expect(parseModelList(' ')).toEqual([]);
+ });
+});
diff --git a/desktop/tests/secrets.test.ts b/desktop/tests/secrets.test.ts
index 5d10f458e..dffb475b8 100644
--- a/desktop/tests/secrets.test.ts
+++ b/desktop/tests/secrets.test.ts
@@ -14,7 +14,8 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, existsSync, readFileSync, writeFileSync, statSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
-import { AGENT_API_KEY } from '../src/settings/agentIds';
+/** Any id — this file is about the store, not about who happens to use it. */
+const KEY = 'agents.key.anthropic';
let userData: string;
let available = true;
@@ -63,78 +64,78 @@ afterEach(() => {
describe('storing a secret', () => {
it('reports nothing configured before anything is stored, and writes no file', async () => {
const { secretStatus } = await load();
- expect(secretStatus(AGENT_API_KEY)).toEqual({
- id: AGENT_API_KEY, configured: false, storage: 'keychain', error: null,
+ expect(secretStatus(KEY)).toEqual({
+ id: KEY, configured: false, storage: 'keychain', error: null,
});
expect(existsSync(file())).toBe(false);
});
it('hands the value back to main and never writes it in the clear', async () => {
const { setSecret, readSecret } = await load();
- expect(setSecret(AGENT_API_KEY, 'sk-ant-secret')).toMatchObject({ configured: true, error: null });
- expect(readSecret(AGENT_API_KEY)).toBe('sk-ant-secret');
+ expect(setSecret(KEY, 'sk-ant-secret')).toMatchObject({ configured: true, error: null });
+ expect(readSecret(KEY)).toBe('sk-ant-secret');
expect(onDisk()).not.toContain('sk-ant-secret');
});
it('keeps the file to this account', async () => {
const { setSecret } = await load();
- setSecret(AGENT_API_KEY, 'sk-ant-secret');
+ setSecret(KEY, 'sk-ant-secret');
if (process.platform === 'win32') return; // POSIX modes only
expect(statSync(file()).mode & 0o777).toBe(0o600);
});
it('survives a restart', async () => {
const first = await load();
- first.setSecret(AGENT_API_KEY, 'sk-ant-secret');
+ first.setSecret(KEY, 'sk-ant-secret');
const restarted = await load();
- expect(restarted.secretStatus(AGENT_API_KEY)).toMatchObject({ configured: true });
- expect(restarted.readSecret(AGENT_API_KEY)).toBe('sk-ant-secret');
+ expect(restarted.secretStatus(KEY)).toMatchObject({ configured: true });
+ expect(restarted.readSecret(KEY)).toBe('sk-ant-secret');
});
it('replaces rather than accumulates', async () => {
const { setSecret, readSecret } = await load();
- setSecret(AGENT_API_KEY, 'first');
- setSecret(AGENT_API_KEY, 'second');
- expect(readSecret(AGENT_API_KEY)).toBe('second');
- expect(Object.keys(JSON.parse(onDisk()) as object)).toEqual([AGENT_API_KEY]);
+ setSecret(KEY, 'first');
+ setSecret(KEY, 'second');
+ expect(readSecret(KEY)).toBe('second');
+ expect(Object.keys(JSON.parse(onDisk()) as object)).toEqual([KEY]);
});
it('trims what was pasted', async () => {
const { setSecret, readSecret } = await load();
- setSecret(AGENT_API_KEY, ' sk-ant-secret\n');
- expect(readSecret(AGENT_API_KEY)).toBe('sk-ant-secret');
+ setSecret(KEY, ' sk-ant-secret\n');
+ expect(readSecret(KEY)).toBe('sk-ant-secret');
});
// A blank submission is a mistake, and reading it as "forget my key" is not the
// helpful interpretation of one.
it('ignores a blank instead of taking the stored one away', async () => {
const { setSecret, readSecret } = await load();
- setSecret(AGENT_API_KEY, 'sk-ant-secret');
- expect(setSecret(AGENT_API_KEY, ' ')).toMatchObject({ configured: true });
- expect(readSecret(AGENT_API_KEY)).toBe('sk-ant-secret');
+ setSecret(KEY, 'sk-ant-secret');
+ expect(setSecret(KEY, ' ')).toMatchObject({ configured: true });
+ expect(readSecret(KEY)).toBe('sk-ant-secret');
});
// The file on disk still holds the old one, so dropping it in memory would only
// make the two disagree until the next restart.
it('keeps the working key when replacing it fails', async () => {
const { setSecret, readSecret, secretStatus } = await load();
- setSecret(AGENT_API_KEY, 'sk-ant-works');
+ setSecret(KEY, 'sk-ant-works');
sealFails = true; // the keychain refuses mid-session
- const failed = setSecret(AGENT_API_KEY, 'sk-ant-new');
+ const failed = setSecret(KEY, 'sk-ant-new');
sealFails = false;
expect(failed.error).toContain('refused');
- expect(secretStatus(AGENT_API_KEY)).toMatchObject({ configured: true });
- expect(readSecret(AGENT_API_KEY)).toBe('sk-ant-works');
+ expect(secretStatus(KEY)).toMatchObject({ configured: true });
+ expect(readSecret(KEY)).toBe('sk-ant-works');
});
it('forgets one on request, on disk too', async () => {
const { setSecret, clearSecret, readSecret } = await load();
- setSecret(AGENT_API_KEY, 'sk-ant-secret');
- expect(clearSecret(AGENT_API_KEY)).toMatchObject({ configured: false });
- expect(readSecret(AGENT_API_KEY)).toBeNull();
+ setSecret(KEY, 'sk-ant-secret');
+ expect(clearSecret(KEY)).toMatchObject({ configured: false });
+ expect(readSecret(KEY)).toBeNull();
expect(JSON.parse(onDisk())).toEqual({});
});
});
@@ -143,11 +144,11 @@ describe('a machine that cannot encrypt', () => {
it('refuses to store rather than falling back to plaintext', async () => {
available = false;
const { setSecret, secretStatus } = await load();
- expect(setSecret(AGENT_API_KEY, 'sk-ant-secret')).toEqual({
- id: AGENT_API_KEY, configured: false, storage: 'unavailable', error: null,
+ expect(setSecret(KEY, 'sk-ant-secret')).toEqual({
+ id: KEY, configured: false, storage: 'unavailable', error: null,
});
expect(existsSync(file())).toBe(false);
- expect(secretStatus(AGENT_API_KEY).storage).toBe('unavailable');
+ expect(secretStatus(KEY).storage).toBe('unavailable');
});
// Linux's basic_text backend encrypts with a hardcoded password. safeStorage
@@ -159,7 +160,7 @@ describe('a machine that cannot encrypt', () => {
backend = 'basic_text';
try {
const { setSecret } = await load();
- expect(setSecret(AGENT_API_KEY, 'sk-ant-secret')).toMatchObject({
+ expect(setSecret(KEY, 'sk-ant-secret')).toMatchObject({
configured: true, storage: 'obfuscated',
});
} finally {
@@ -171,31 +172,31 @@ describe('a machine that cannot encrypt', () => {
describe('a stored secret this machine cannot open', () => {
it('reads as not configured, and says why', async () => {
const first = await load();
- first.setSecret(AGENT_API_KEY, 'sk-ant-secret');
+ first.setSecret(KEY, 'sk-ant-secret');
keyring = 'another-machine'; // restored from a backup / a rotated keychain
const restarted = await load();
- const status = restarted.secretStatus(AGENT_API_KEY);
+ const status = restarted.secretStatus(KEY);
expect(status.configured).toBe(false);
expect(status.error).toContain('decrypt');
- expect(restarted.readSecret(AGENT_API_KEY)).toBeNull();
+ expect(restarted.readSecret(KEY)).toBeNull();
});
it('is replaced by simply entering it again', async () => {
const first = await load();
- first.setSecret(AGENT_API_KEY, 'sk-ant-secret');
+ first.setSecret(KEY, 'sk-ant-secret');
keyring = 'another-machine';
const restarted = await load();
- expect(restarted.setSecret(AGENT_API_KEY, 'sk-ant-new')).toMatchObject({ configured: true, error: null });
- expect(restarted.readSecret(AGENT_API_KEY)).toBe('sk-ant-new');
+ expect(restarted.setSecret(KEY, 'sk-ant-new')).toMatchObject({ configured: true, error: null });
+ expect(restarted.readSecret(KEY)).toBe('sk-ant-new');
});
it('treats an unparseable file as nothing stored rather than throwing', async () => {
writeFileSync(file(), '{ this is not json');
const { secretStatus, setSecret } = await load();
- expect(secretStatus(AGENT_API_KEY)).toMatchObject({ configured: false, error: null });
- expect(setSecret(AGENT_API_KEY, 'sk-ant-secret')).toMatchObject({ configured: true });
+ expect(secretStatus(KEY)).toMatchObject({ configured: false, error: null });
+ expect(setSecret(KEY, 'sk-ant-secret')).toMatchObject({ configured: true });
});
});