Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

External-agent revamp: split create / external tabs, dedupe names, project-dir form input

claw229a5c14dd0f4
diff --git a/src/main/features/agents.ts b/src/main/features/agents.ts
index 32e0c16b..c8ad4754 100644
--- a/src/main/features/agents.ts
+++ b/src/main/features/agents.ts
@@ -47,7 +47,7 @@ import { renameAgentInMembers } from './group_chat/state';
export type AgentSource = 'builtin' | 'custom';
-export type AgentInputType = 'text' | 'textarea' | 'select' | 'multiselect' | 'number' | 'boolean' | 'file';
+export type AgentInputType = 'text' | 'textarea' | 'select' | 'multiselect' | 'number' | 'boolean' | 'file' | 'directory';
export interface AgentInputOption {
value: string;
@@ -262,7 +262,7 @@ function agentBaseDir(source: AgentSource): string {
}
const INPUT_ID_RE = /^[a-z_][a-z0-9_]{0,31}$/;
-const ALLOWED_INPUT_TYPES: readonly AgentInputType[] = ['text', 'textarea', 'select', 'multiselect', 'number', 'boolean', 'file'];
+const ALLOWED_INPUT_TYPES: readonly AgentInputType[] = ['text', 'textarea', 'select', 'multiselect', 'number', 'boolean', 'file', 'directory'];
// Reserved agent display names — collide with the commander role surfaced in
// the chat-recipient chip ("指挥官") and the sidebar tab ("总指挥"). The bus
@@ -283,6 +283,28 @@ function assertAgentNameAllowed(name: string): void {
}
}
+/** Reject names already in use by another agent (custom OR builtin).
+ * Matches `_agentNameKey` (case-insensitive, all whitespace stripped) so
+ * "Code Helper" and "codehelper" collide. `excludeAgentId` lets the
+ * update path keep its own name. Caller owns the check at every write
+ * entry — IPC create / IPC update / LLM-driven create+edit — so neither
+ * the UI form nor the LLM can land a duplicate. */
+async function assertAgentNameUnique(
+ name: string, excludeAgentId?: string,
+): Promise<void> {
+ const key = _agentNameKey(name);
+ if (!key) return;
+ const all = await listAgents();
+ for (const a of all) {
+ if (excludeAgentId && a.agent_id === excludeAgentId) continue;
+ if (_agentNameKey(a.name || '') === key) {
+ const err: any = new Error(`agent name "${name}" is already in use`);
+ err.code = 'E_AGENT_NAME_TAKEN';
+ throw err;
+ }
+ }
+}
+
/**
* Normalize + validate a candidate `AgentInput[]`. Drop malformed entries
* with a warn log rather than throw — we don't want one bad field to make
@@ -367,6 +389,9 @@ export function validateAgentInputs(raw: unknown): AgentInput[] {
const allowed = new Set(options!.map((o) => o.value));
const filtered = arr.filter((v) => allowed.has(v));
def = filtered;
+ } else if (type === 'directory') {
+ // Directory — default is always empty; the user picks via native dialog.
+ def = '';
} else { // file — default is always empty (the model can't pre-pick a file)
def = fileMultiple ? [] : '';
}
@@ -469,6 +494,16 @@ function _normalizeRuntime(raw: unknown): AgentRuntime | null {
return out;
}
+/** True when this CLI is a coding agent (claude code / codex). Coding
+ * agents are dispatched with a per-conversation project directory as
+ * cwd instead of the user workspace; the chip in the conversation
+ * surface lets the user set it. Single source of truth for both UI
+ * visibility and dispatch routing. */
+export const CODING_CLIS = new Set<string>(['claude', 'codex']);
+export function cliIsCodingAgent(cli: string | undefined): boolean {
+ return !!cli && CODING_CLIS.has(cli);
+}
+
/** True when this agent runs via a local CLI rather than in-process
* core-agent. Single source of truth — group_chat / chats / renderer
* all import this rather than re-checking `runtime?.kind` directly. */
@@ -617,6 +652,7 @@ export async function createCustomAgent(
{ name = '', description = '', description_zh, description_en, workflow = '', icon, color, interactive, runtime }: CreateAgentOptions = {},
): Promise<Agent | null> {
assertAgentNameAllowed(name);
+ await assertAgentNameUnique(String(name || '').trim());
fs.mkdirSync(CUSTOM_AGENTS_DIR(), { recursive: true });
let agentId: string;
do { agentId = genAgentId(); }
@@ -641,13 +677,35 @@ export async function createCustomAgent(
// selection is the implicit default and not written to disk so old
// tooling diffs cleanly.
const rt = _normalizeRuntime(runtime);
- if (rt && rt.kind === 'cli') data.runtime = rt;
+ if (rt && rt.kind === 'cli') {
+ data.runtime = rt;
+ // Coding CLIs (claude / codex) need a working directory. We inject
+ // a `project_dir` input dependency so the standard agent-input-form
+ // pipeline collects it before the first dispatch — same UX as any
+ // other required input. The agent worker reads the submitted
+ // value to set CLI cwd.
+ if (cliIsCodingAgent(rt.cli)) {
+ data.inputs = [PROJECT_DIR_INPUT];
+ }
+ }
await writeJson(customAgentFile(agentId), data);
_invalidateAgentListCache();
log.info(`created id=${agentId} name=${data.name}`);
return normalizeAgent(data, 'custom');
}
+/** Required-input schema injected on every external coding agent. The
+ * field id `project_dir` is a contract — the dispatch path looks for
+ * exactly this id when extracting the cwd from a form submission. */
+export const PROJECT_DIR_INPUT_ID = 'project_dir';
+const PROJECT_DIR_INPUT: AgentInput = {
+ id: PROJECT_DIR_INPUT_ID,
+ type: 'directory',
+ label: '项目目录',
+ required: true,
+ default: '',
+};
+
export interface UpdateAgentFields {
name?: string;
description?: string;
@@ -693,7 +751,10 @@ export async function updateCustomAgent(
const data = await readJson<AgentRaw>(f);
const oldName = typeof (data as any).name === 'string' ? (data as any).name : '';
if (Object.prototype.hasOwnProperty.call(updates || {}, 'name')) {
- assertAgentNameAllowed(typeof updates.name === 'string' ? updates.name : '');
+ const incomingName = typeof updates.name === 'string' ? updates.name : '';
+ assertAgentNameAllowed(incomingName);
+ const trimmed = incomingName.trim();
+ if (trimmed) await assertAgentNameUnique(trimmed, agentId);
}
// CLI-backed agents have no authored workflow / skill_list — the
// edit prompt forbids the LLM from emitting those tags, but if it
@@ -826,6 +887,19 @@ export async function updateCustomAgent(
if (!rt || rt.kind === 'in_process') delete data.runtime;
else data.runtime = rt;
}
+ // Reconcile the project_dir input with the (post-update) cli kind.
+ // Coding cli ↔ project_dir input is a contract, not a user-authored
+ // schema: swap claude → codex keeps it, swap to a non-coding cli
+ // drops it, etc. We don't touch any other input the user defined.
+ const finalCli = data.runtime && _normalizeRuntime(data.runtime)?.kind === 'cli'
+ ? (_normalizeRuntime(data.runtime) as Extract<AgentRuntime, { kind: 'cli' }>).cli
+ : '';
+ const wantsProjectDir = cliIsCodingAgent(finalCli);
+ const inputs = Array.isArray(data.inputs) ? validateAgentInputs(data.inputs) : [];
+ const without = inputs.filter((i) => i.id !== PROJECT_DIR_INPUT_ID);
+ if (wantsProjectDir) data.inputs = [PROJECT_DIR_INPUT, ...without];
+ else if (without.length) data.inputs = without;
+ else delete data.inputs;
}
if (!data.name) data.name = '未命名智能体';
data.updated_at = nowIso();
@@ -934,6 +1008,13 @@ const AGENT_CONTAINER_RE = /<agent>([\s\S]*?)<\/agent>/g;
const AGENT_CHILD_RE = (tag: string) => new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`);
export interface ExtractedFields {
+ /** Parsed from `<agent_id>` inside `<agent>`. Present → commander wants to
+ * patch this existing custom agent (main-chat edit flow); absent → create
+ * a brand-new agent. The agent-edit-chat surface ignores this field — the
+ * target id is supplied by URL context, the LLM never writes it. Body
+ * must pass `safeId`; otherwise the key is dropped (mis-spelled id should
+ * NOT silently fall through to the create branch). */
+ agent_id?: string;
name?: string;
description?: string;
description_zh?: string;
@@ -960,6 +1041,11 @@ export function extractAgentFieldBlocks(text: string): { cleanText: string; fiel
const first = text.match(/<agent>([\s\S]*?)<\/agent>/);
if (first) {
const inner = first[1];
+ const aidM = inner.match(AGENT_CHILD_RE('agent_id'));
+ if (aidM) {
+ const v = aidM[1].trim();
+ if (safeId(v)) fields.agent_id = v;
+ }
const nameM = inner.match(AGENT_CHILD_RE('name'));
if (nameM) {
const v = nameM[1].trim();
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 52789bbb..9557fe9e 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -36,7 +36,7 @@ import {
import {
resolveRecipients, parseMentions,
extractFormFromFinal, computeFormId, ChatFormPayload,
- extractAgentFieldBlocks,
+ extractAgentFieldBlocks, decodeSubmission,
} from './router';
import {
setPlan, updateStep, readPlan, formatPlanAnnouncement, formatPlanForPrompt,
@@ -848,7 +848,27 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// `write_file` tool; CLI agents have their own product-side
// conventions and don't need that scoping. Override here:
const userWorkspace = await import('../user_workspace');
- const cliWorkingDir = userWorkspace.getWorkspacePath(uid);
+ const wsRoot = userWorkspace.getWorkspacePath(uid);
+ // Coding agents (claude / codex) honour the per-conversation
+ // `coding_project_dir` when set so the CLI runs inside the user's
+ // actual project; non-coding CLIs always use the workspace. The
+ // chip in the conversation surface lets the user set/change the
+ // dir mid-conversation. We also defensively check the directory
+ // exists and is a real dir — if it vanished between picker and
+ // dispatch we fall back rather than failing the run.
+ const agentsFeat = await import('../agents');
+ let cliWorkingDir = wsRoot;
+ if (agentsFeat.cliIsCodingAgent(cliAgent.runtime?.kind === 'cli' ? cliAgent.runtime.cli : '')) {
+ const st = await import('./state');
+ const stateFile = await st.readState(uid, cid);
+ const projDir = stateFile.coding_project_dir;
+ if (projDir) {
+ try {
+ const fs = await import('node:fs');
+ if (fs.statSync(projDir).isDirectory()) cliWorkingDir = projDir;
+ } catch { /* missing → fall through to wsRoot */ }
+ }
+ }
try {
const slice = await readSlice(uid, cid, actor.id);
const cliOut = await _runCliAgentTurn({
@@ -1739,6 +1759,40 @@ planExecutor.bindBusHooks({
const CLI_PROMPT_MAX_BYTES = 200 * 1024;
+/** Build an `<agent-input-form>` block listing the agent's required
+ * inputs that are still unfulfilled, or return `null` when nothing is
+ * missing. Currently the only auto-injected input is `project_dir`
+ * (coding agents only); we read its fulfilment from `state.coding_project_dir`.
+ * Other required inputs the user has authored on the agent flow through
+ * here too — for those we have no per-conv storage yet, so they're
+ * re-asked on every dispatch (matches the "prompt every turn until
+ * collected" behaviour the in-process branch already has). */
+async function _maybeBuildCliInputForm(
+ uid: string, cid: string, agent: import('../agents').Agent,
+): Promise<string | null> {
+ const inputs = Array.isArray(agent.inputs) ? agent.inputs : [];
+ if (!inputs.length) return null;
+ const required = inputs.filter((f) => f.required);
+ if (!required.length) return null;
+
+ const state = await readState(uid, cid);
+ const projectDir = state.coding_project_dir || '';
+
+ const isFulfilled = (fieldId: string): boolean => {
+ if (fieldId === 'project_dir') return !!projectDir;
+ return false;
+ };
+
+ const missing = required.filter((f) => !isFulfilled(f.id));
+ if (!missing.length) return null;
+
+ const body = JSON.stringify({
+ agent_id: agent.agent_id,
+ fields: missing,
+ });
+ return `<agent-input-form>\n${body}\n</agent-input-form>`;
+}
+
async function _runCliAgentTurn(opts: {
uid: string;
cid: string;
@@ -1751,6 +1805,20 @@ async function _runCliAgentTurn(opts: {
onProcess: (data: Record<string, unknown>) => void;
}): Promise<{ text: string; error?: string; aborted?: boolean }> {
const runtime = opts.agent.runtime as Extract<NonNullable<import('../agents').AgentRuntime>, { kind: 'cli' }>;
+
+ // Required-input gate: a CLI agent never runs an LLM, so the form-emit
+ // logic in `chat_agent_in_group.md` (where in-process agents check their
+ // inputs_schema and emit `<agent-input-form>` themselves) doesn't fire.
+ // We mirror that here: if any required input is unfulfilled, return a
+ // synthetic body containing the form block — runTurn's
+ // `extractFormFromFinal` then lifts it into a `form` payload, the
+ // renderer shows the picker, and the user's submission re-dispatches
+ // through the standard pipeline. Only the `project_dir` input is
+ // currently auto-injected, but the gate is generic so future required
+ // inputs reuse the same path.
+ const formBlock = await _maybeBuildCliInputForm(opts.uid, opts.cid, opts.agent);
+ if (formBlock) return { text: formBlock };
+
// Look up any prior CLI session bound to this (cid, aid, cli). If
// present, we ask the CLI to resume it (claude: `--resume <id>`)
// and skip replaying the visibility slice in the prompt — the CLI
@@ -1926,7 +1994,41 @@ async function _buildCliPrompt(
const tailLines: string[] = [];
tailLines.push('## Your task');
- tailLines.push(item.llmPayload);
+ // When the dispatched item is just a form submission (the user
+ // confirmed the input form, not a fresh ask), the task body is
+ // metadata — `- 项目目录:…` summary + an `<agent-input-submission>`
+ // XML tag — with the original user request now sitting upstream in
+ // the slice. A coding CLI handed only that metadata has nothing
+ // actionable: claude / codex sit idle until killed (observed:
+ // 2+ min "processing" with 0 bytes of output). Walk the slice
+ // backward to recover the most recent user message that ISN'T
+ // another submission and use it as the real task; append the
+ // confirmed values as extra context. The cwd is already routed
+ // via `state.coding_project_dir`, so we don't need to re-state
+ // `project_dir` to the CLI.
+ const submission = decodeSubmission(item.llmPayload);
+ if (submission) {
+ let originalTask = '';
+ for (let i = slice.length - 1; i >= 0; i--) {
+ const m = slice[i];
+ const txt = (m.text || '').trim();
+ if (m.from !== 'user' || !txt) continue;
+ if (decodeSubmission(txt)) continue;
+ originalTask = txt;
+ break;
+ }
+ tailLines.push(originalTask || item.llmPayload);
+ const extraValues = Object.entries(submission.values)
+ .filter(([k]) => k !== 'project_dir')
+ .map(([k, v]) => `- ${k}: ${typeof v === 'string' ? v : JSON.stringify(v)}`);
+ if (extraValues.length) {
+ tailLines.push('');
+ tailLines.push('## Confirmed parameters');
+ tailLines.push(...extraValues);
+ }
+ } else {
+ tailLines.push(item.llmPayload);
+ }
const head = headLines.join('\n');
const tail = tailLines.join('\n');
diff --git a/src/main/features/group_chat/index.ts b/src/main/features/group_chat/index.ts
index 67229126..ed4d8c23 100644
--- a/src/main/features/group_chat/index.ts
+++ b/src/main/features/group_chat/index.ts
@@ -16,7 +16,8 @@ import { readJsonl, rewriteJsonlLine, nowIso, safeId } from '../../storage';
import { createLogger } from '../../logger';
import {
- USER_ID, readMembers, seedReservedActors, purgeGroupDir,
+ USER_ID, readMembers, readState, seedReservedActors, purgeGroupDir,
+ setCodingProjectDir,
} from './state';
import { readPlan, type PlanFile } from './plan';
import * as planExecutor from './plan_executor';
@@ -256,6 +257,28 @@ export async function markFormSubmittedAndDispatch(
}
log.info(`form-submitted user=${userId} cid=${cid} msgId=${msgId} agent=${agentId} fields=${target.form.fields.length}`);
+ // Coding-agent contract: when a `project_dir` field is present in the
+ // submitted form for an external claude / codex agent, persist it to
+ // conv state so `_runCliAgentTurn` can spawn the CLI inside that
+ // directory. Other form values stay only in the message log — the
+ // agent extracts them from the encoded submission text.
+ try {
+ const projDir = values && typeof (values as any).project_dir === 'string'
+ ? String((values as any).project_dir).trim()
+ : '';
+ if (projDir) {
+ const agentsFeat = await import('../agents');
+ const ag = await agentsFeat.getAgent(agentId);
+ const cli = ag?.runtime?.kind === 'cli' ? ag.runtime.cli : '';
+ if (agentsFeat.cliIsCodingAgent(cli)) {
+ await setCodingProjectDir(userId, cid, projDir);
+ log.info(`coding project_dir set user=${userId} cid=${cid} agent=${agentId} dir=${projDir}`);
+ }
+ }
+ } catch (err) {
+ log.warn(`form-submit project_dir hook failed: ${(err as Error).message}`);
+ }
+
const sliceFile = groupChatVisibilityFile(userId, cid, agentId);
if (fs.existsSync(sliceFile)) {
const slice = await readJsonl<GroupMessage>(sliceFile, 100_000);
diff --git a/src/main/features/group_chat/state.ts b/src/main/features/group_chat/state.ts
index c41969fe..9af49493 100644
--- a/src/main/features/group_chat/state.ts
+++ b/src/main/features/group_chat/state.ts
@@ -64,6 +64,13 @@ export interface StateFile {
* the directory or update this field. See `conv_workspace.ts` for the
* slug rules and the placeholder fallback. */
workspace_dir?: string;
+ /** Project directory for coding-agent (claude / codex) dispatches in
+ * this conversation. User-set via the project-dir chip in the chat
+ * surface; absolute path. Missing / empty → coding agents fall back
+ * to the conv's workspace root (matches the prior behaviour). The
+ * field is per-conversation, NOT per-agent: one project for the
+ * whole conversation across however many coding agents it has. */
+ coding_project_dir?: string;
}
export const COMMANDER_ID = 'commander';
@@ -215,6 +222,9 @@ export async function readState(uid: string, cid: string): Promise<StateFile> {
...(typeof data.workspace_dir === 'string' && data.workspace_dir
? { workspace_dir: data.workspace_dir }
: {}),
+ ...(typeof data.coding_project_dir === 'string' && data.coding_project_dir
+ ? { coding_project_dir: data.coding_project_dir }
+ : {}),
};
}
} catch (err) {
@@ -313,6 +323,22 @@ export async function setWorkspaceDirOnce(uid: string, cid: string, dir: string)
});
}
+/** Set / clear the per-conversation coding-agent project directory.
+ * Pass `''` (or missing) to clear; an absolute path otherwise.
+ * Caller is responsible for absolute-path validation — we only do
+ * string handling here. Returns the resulting state. */
+export async function setCodingProjectDir(uid: string, cid: string, dir: string): Promise<StateFile> {
+ return _stateLock(uid, cid).runExclusive(async () => {
+ const s = await readState(uid, cid);
+ const trimmed = String(dir || '').trim();
+ if (trimmed) s.coding_project_dir = trimmed;
+ else delete s.coding_project_dir;
+ s.last_active_at = nowIso();
+ await writeStateRaw(uid, cid, s);
+ return s;
+ });
+}
+
/** Drop the whole group dir (called from chats.deleteConversation). */
export async function purgeGroupDir(uid: string, cid: string): Promise<void> {
const dir = groupChatDir(uid, cid);
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 67b4bac2..998a0183 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -152,6 +152,22 @@ const invokeHandlers: Record<string, InvokeHandler> = {
});
},
+ // Generic native directory picker. Used by the agent-input-form
+ // `directory` type so coding agents (claude / codex) collect their
+ // project directory through the standard input-form pipeline.
+ 'common.pickDirectory': async ({ title } = {}) => {
+ const parent = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];
+ const opts: Electron.OpenDialogOptions = {
+ properties: ['openDirectory'],
+ title: typeof title === 'string' && title ? title : '选择目录',
+ };
+ const res = parent
+ ? await dialog.showOpenDialog(parent, opts)
+ : await dialog.showOpenDialog(opts);
+ if (res.canceled || !res.filePaths?.length) return { cancelled: true };
+ return { cancelled: false, path: res.filePaths[0] };
+ },
+
// ── Chat attachments (per-cid file pool for main chat) ──
'conversations.attachments.list': async ({ cid }, ctx) => {
if (!safeId(cid)) throw new Error('invalid cid');
@@ -187,10 +203,11 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { agent };
},
- 'agents.create': async ({ name = '', description = '', workflow = '', icon, color, runtime } = {}) => {
- return { agent: await agents.createCustomAgent({ name, description, workflow, icon, color, runtime }) };
+ 'agents.create': async ({ name = '', description = '', description_zh, description_en, workflow = '', icon, color, runtime } = {}) => {
+ return { agent: await agents.createCustomAgent({ name, description, description_zh, description_en, workflow, icon, color, runtime }) };
},
+
'agents.update': async ({ agent_id, updates }) => {
if (!agents.isValidAgentId(agent_id)) throw new Error('invalid agent_id');
const data = await agents.updateCustomAgent(agent_id, updates || {});
@@ -766,7 +783,13 @@ export function register(): void {
return { ok: true, ...(result || {}) };
} catch (err) {
log.error(`invoke ${channel} failed`, { error: (err as Error)?.message || String(err) });
- return { ok: false, error: (err as Error).message || String(err) };
+ const out: { ok: false; error: string; code?: string } = {
+ ok: false,
+ error: (err as Error).message || String(err),
+ };
+ const code = (err as { code?: unknown }).code;
+ if (typeof code === 'string') out.code = code;
+ return out;
}
});
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 762385fa..161d8bb7 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -283,7 +283,7 @@
</div>
<div class="agents-detail-body">
<div class="agents-detail-section" id="agents-detail-runtime-section" style="display:none">
- <div class="agents-detail-label" data-i18n="agents.label_runtime">运行环境</div>
+ <div class="agents-detail-label" data-i18n="agents.label_runtime">外接智能体</div>
<div class="agents-detail-runtime" id="agents-detail-runtime"></div>
</div>
<div class="agents-detail-section">
@@ -508,18 +508,47 @@
<div class="modal-overlay" id="agent-modal">
<div class="modal">
<h3 data-i18n="agent_modal.title">新建智能体</h3>
- <div class="form-row">
- <label data-i18n="agent_modal.name">名称</label>
- <input type="text" id="agent-name-input" data-i18n-placeholder="agent_modal.name_placeholder" placeholder="例如:代码审查助手" />
+
+ <!-- Mode tabs: 创建 (in-process) / 外接 (cli runtime). Mirrors the
+ skill-modal tab pattern; reuses the same .skill-modal-tab styles
+ via the agent-modal-tab class for consistent chrome. -->
+ <div class="skill-modal-tabs" id="agent-modal-tabs">
+ <button type="button" class="skill-modal-tab is-active" data-agent-tab="create" data-i18n="agent_modal.tab_create">创建</button>
+ <button type="button" class="skill-modal-tab" data-agent-tab="external" data-i18n="agent_modal.tab_external">外接</button>
</div>
- <div class="form-row">
- <label><span data-i18n="agent_modal.desc">简介</span> <span class="form-hint" data-i18n="agent_modal.desc_hint">一句话说明用途,创建后 AI 会基于此生成工作流程</span></label>
- <textarea id="agent-desc-input" rows="4" data-i18n-placeholder="agent_modal.desc_placeholder" placeholder="例如:帮我在提交前审查代码,重点看逻辑漏洞和安全问题..."></textarea>
+
+ <!-- Create panel (default): manual authoring. Runtime selector is
+ intentionally absent here — that flow lives in the External tab. -->
+ <div class="skill-modal-panel is-active" data-agent-panel="create">
+ <div class="form-row">
+ <label data-i18n="agent_modal.name">名称</label>
+ <input type="text" id="agent-name-input" data-i18n-placeholder="agent_modal.name_placeholder" placeholder="例如:代码审查助手" />
+ </div>
+ <div class="form-row">
+ <label><span data-i18n="agent_modal.desc">简介</span> <span class="form-hint" data-i18n="agent_modal.desc_hint">一句话说明用途,创建后 AI 会基于此生成工作流程</span></label>
+ <textarea id="agent-desc-input" rows="4" data-i18n-placeholder="agent_modal.desc_placeholder" placeholder="例如:帮我在提交前审查代码,重点看逻辑漏洞和安全问题..."></textarea>
+ </div>
</div>
- <div class="form-row" id="agent-modal-runtime-row" style="display:none">
- <label><span data-i18n="agent_modal.runtime_label">运行环境</span> <span class="form-hint" data-i18n="agent_modal.runtime_hint">选择本地 CLI 则由该 CLI 来运行智能体</span></label>
- <div class="ai-select" id="agent-modal-runtime-select"></div>
+
+ <!-- External panel: bind a local CLI as the runtime. CLI selector
+ appears first; name + description are pre-filled from the chosen
+ CLI's defaults but stay editable. claude / codex additionally
+ expose a project-directory input. -->
+ <div class="skill-modal-panel" data-agent-panel="external">
+ <div class="form-row">
+ <label data-i18n="agent_modal.ext_cli_label">智能体</label>
+ <div class="ai-select" id="agent-modal-ext-cli-select"></div>
+ </div>
+ <div class="form-row">
+ <label data-i18n="agent_modal.ext_name">名称</label>
+ <input type="text" id="agent-ext-name-input" data-i18n-placeholder="agent_modal.ext_name_placeholder" placeholder="例如:Claude Code" />
+ </div>
+ <div class="form-row">
+ <label data-i18n="agent_modal.ext_desc">简介</label>
+ <textarea id="agent-ext-desc-input" rows="4" data-i18n-placeholder="agent_modal.ext_desc_placeholder" placeholder="(选择 CLI 后自动填入,可手动覆盖)"></textarea>
+ </div>
</div>
+
<div class="form-msg" id="agent-form-msg"></div>
<div class="modal-actions">
<button class="btn" onclick="closeAgentModal()" data-i18n="common.cancel">取消</button>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index 4f04e61a..e448700a 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -99,6 +99,7 @@
"chat.form.required_select": "Please select",
"chat.form.required_multiselect": "Select at least one",
"chat.form.required_file": "Please pick a file",
+ "chat.form.required_directory": "Please pick a directory",
"chat.form.file_pick": "Pick file",
"chat.form.file_pick_multi": "Pick files (multi)",
"chat.form.file_uploading": "uploading…",
@@ -215,7 +216,7 @@
"agents.edit": "Edit",
"agents.delete": "Delete",
"agents.label_desc": "Summary",
- "agents.label_runtime": "Runtime",
+ "agents.label_runtime": "External agent",
"agents.label_workflow": "Workflow",
"agents.clear_chat": "Clear",
"agents.clear_chat_title": "Clear the edit chat for this agent",
@@ -229,6 +230,8 @@
"agents.input_name_needed": "Please enter a name",
"agents.input_desc_needed": "Please enter a summary",
"agents.name_reserved": "That name is reserved by the system (Commander). Pick another.",
+ "agents.name_taken": "That name is already used by another agent. Pick another.",
+ "agents.ext_cli_needed": "Pick an external agent first",
"agents.create_failed": "Create failed",
"agents.seed_workflow": "Help me refine this agent",
"agents.network_error": "Network error: {reason}",
@@ -431,25 +434,35 @@
"settings.metacognition.toggle": "Enable",
"settings.metacognition.env_forced_off": "Forced off by env ORKAS_METACOGNITION=0",
"agent_modal.title": "New agent",
+ "agent_modal.tab_create": "Create",
+ "agent_modal.tab_external": "External",
"agent_modal.name": "Name",
"agent_modal.name_placeholder": "e.g. Code Review Assistant",
"agent_modal.desc": "Summary",
"agent_modal.desc_hint": "One line on what it does — the AI will generate a workflow from this",
"agent_modal.desc_placeholder": "e.g. Review my code before commit, focus on logic bugs and security issues...",
- "agent_modal.runtime_label": "Runtime",
- "agent_modal.runtime_hint": "Pick a local CLI and that CLI will run the agent",
- "agent_modal.runtime_in_process": "Orkas",
+ "agent_modal.ext_cli_label": "Agent",
+ "agent_modal.ext_cli_none": "Not selected",
+ "agent_modal.ext_name": "Name",
+ "agent_modal.ext_name_placeholder": "e.g. Claude Code",
+ "agent_modal.ext_desc": "Summary",
+ "agent_modal.ext_desc_placeholder": "(auto-filled when a CLI is picked; can be overridden)",
"agent_modal.runtime_cli_claude": "Claude Code",
"agent_modal.runtime_cli_codex": "Codex",
"agent_modal.runtime_cli_openclaw": "OpenClaw",
"agent_modal.runtime_cli_opencode": "OpenCode",
"agent_modal.runtime_cli_hermes": "Hermes",
- "agent.cli_badge.claude": "CLI · Claude Code",
- "agent.cli_badge.codex": "CLI · Codex",
- "agent.cli_badge.openclaw": "CLI · OpenClaw",
- "agent.cli_badge.opencode": "CLI · OpenCode",
- "agent.cli_badge.hermes": "CLI · Hermes",
- "agent.cli_missing": "⚠ Local CLI not installed",
+ "agent.external_word": "External",
+ "agent.external_badge.claude": "External · Claude Code",
+ "agent.external_badge.codex": "External · Codex",
+ "agent.external_badge.openclaw": "External · OpenClaw",
+ "agent.external_badge.opencode": "External · OpenCode",
+ "agent.external_badge.hermes": "External · Hermes",
+ "agent.cli_missing": "⚠ External agent not installed",
+ "input.dir.none": "(not set)",
+ "input.dir.pick": "Pick directory…",
+ "input.dir.change": "Change…",
+ "input.dir.clear": "Clear",
"skill_modal.title_create": "New skill",
"skill_modal.title_edit": "Edit skill",
"skill_modal.name": "Name (English)",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index 9f43e02b..0e22cbbe 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -99,6 +99,7 @@
"chat.form.required_select": "请选择",
"chat.form.required_multiselect": "至少选择一项",
"chat.form.required_file": "请选择文件",
+ "chat.form.required_directory": "请选择目录",
"chat.form.file_pick": "选择文件",
"chat.form.file_pick_multi": "选择文件(可多选)",
"chat.form.file_uploading": "上传中…",
@@ -215,7 +216,7 @@
"agents.edit": "编辑",
"agents.delete": "删除",
"agents.label_desc": "简介",
- "agents.label_runtime": "运行环境",
+ "agents.label_runtime": "外接智能体",
"agents.label_workflow": "工作流程",
"agents.clear_chat": "清空",
"agents.clear_chat_title": "清空当前智能体的对话记录",
@@ -229,6 +230,8 @@
"agents.input_name_needed": "请输入名称",
"agents.input_desc_needed": "请输入简介",
"agents.name_reserved": "该名称为系统保留(指挥官 / 总指挥),请换一个",
+ "agents.name_taken": "该名称已被其他智能体使用,请换一个",
+ "agents.ext_cli_needed": "请先选择外接智能体",
"agents.create_failed": "创建失败",
"agents.seed_workflow": "帮我完善这个智能体",
"agents.network_error": "网络错误:{reason}",
@@ -431,25 +434,35 @@
"settings.metacognition.toggle": "启动",
"settings.metacognition.env_forced_off": "已被环境变量 ORKAS_METACOGNITION=0 强制关闭",
"agent_modal.title": "新建智能体",
+ "agent_modal.tab_create": "创建",
+ "agent_modal.tab_external": "外接",
"agent_modal.name": "名称",
"agent_modal.name_placeholder": "例如:代码审查助手",
"agent_modal.desc": "简介",
"agent_modal.desc_hint": "一句话说明用途,创建后 AI 会基于此生成工作流程",
"agent_modal.desc_placeholder": "例如:帮我在提交前审查代码,重点看逻辑漏洞和安全问题...",
- "agent_modal.runtime_label": "运行环境",
- "agent_modal.runtime_hint": "选择本地 CLI 则由该 CLI 来运行智能体",
- "agent_modal.runtime_in_process": "Orkas",
+ "agent_modal.ext_cli_label": "智能体",
+ "agent_modal.ext_cli_none": "未选择",
+ "agent_modal.ext_name": "名称",
+ "agent_modal.ext_name_placeholder": "例如:Claude Code",
+ "agent_modal.ext_desc": "简介",
+ "agent_modal.ext_desc_placeholder": "(选择 CLI 后自动填入,可手动覆盖)",
"agent_modal.runtime_cli_claude": "Claude Code",
"agent_modal.runtime_cli_codex": "Codex",
"agent_modal.runtime_cli_openclaw": "OpenClaw",
"agent_modal.runtime_cli_opencode": "OpenCode",
"agent_modal.runtime_cli_hermes": "Hermes",
- "agent.cli_badge.claude": "CLI · Claude Code",
- "agent.cli_badge.codex": "CLI · Codex",
- "agent.cli_badge.openclaw": "CLI · OpenClaw",
- "agent.cli_badge.opencode": "CLI · OpenCode",
- "agent.cli_badge.hermes": "CLI · Hermes",
- "agent.cli_missing": "⚠ 本地 CLI 未安装",
+ "agent.external_word": "外接",
+ "agent.external_badge.claude": "外接 · Claude Code",
+ "agent.external_badge.codex": "外接 · Codex",
+ "agent.external_badge.openclaw": "外接 · OpenClaw",
+ "agent.external_badge.opencode": "外接 · OpenCode",
+ "agent.external_badge.hermes": "外接 · Hermes",
+ "agent.cli_missing": "⚠ 外接智能体未安装",
+ "input.dir.none": "(未选择)",
+ "input.dir.pick": "选择目录…",
+ "input.dir.change": "更换…",
+ "input.dir.clear": "清除",
"skill_modal.title_create": "新建技能",
"skill_modal.title_edit": "编辑技能",
"skill_modal.name": "名称(英文)",
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 47fac7ae..c1580da4 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -9,14 +9,18 @@ let _agentFieldSaveTimer = null;
// Mirror of `agents.ts::RESERVED_AGENT_NAMES` so the renderer can fail fast
// without a round-trip. Server is still authoritative — this is just UX.
const _RESERVED_AGENT_NAMES = new Set(['指挥官', '总指挥', 'commander']);
-/** Look up the localized "CLI · <Brand>" label for an agent runtime
- * type, with a guaranteed-readable fallback when the locale key is
- * missing. Orkas's `t()` returns the key itself on miss (so a naive
- * `t(key) || fallback` never falls back); we explicitly compare. */
+/** Look up the localized "外接 · <Brand>" label for an agent runtime
+ * type. The external badge (formerly "CLI · X") is the single
+ * user-facing tag for cli-runtime agents — name surfaces consistently
+ * in cards, detail page, and edit form. */
function _cliBadgeLabel(type) {
- const key = 'agent.cli_badge.' + type;
+ const key = 'agent.external_badge.' + type;
const v = t(key);
- if (!v || v === key) return 'CLI · ' + type;
+ if (!v || v === key) {
+ const externalWord = t('agent.external_word');
+ const word = (externalWord && externalWord !== 'agent.external_word') ? externalWord : 'External';
+ return word + ' · ' + type;
+ }
return v;
}
@@ -511,15 +515,50 @@ async function _renderAgentDetailRuntime(agent) {
onChange: async (next) => {
const m = /^cli:(.+)$/.exec(next);
if (!m) return;
+ const newCli = m[1];
+ // Mirror the create-modal behaviour: if the user's current name /
+ // description are still the defaults of the previous CLI (or empty),
+ // follow the new CLI's defaults. Otherwise, leave their edits alone.
+ const updates = { runtime: { kind: 'cli', cli: newCli } };
+ const lang = (typeof getLang === 'function') ? getLang() : 'zh';
+ const prev = (typeof getCliDefaults === 'function') ? getCliDefaults(currentType) : null;
+ const next2 = (typeof getCliDefaults === 'function') ? getCliDefaults(newCli) : null;
+ const prevDescLocal = prev ? (lang === 'en' ? prev.description_en : prev.description_zh) : '';
+ const curName = (agent.name || '').trim();
+ const curDescLocal = pickDesc(agent, lang).trim();
+ // Same default-like detection as the create modal: bare default OR
+ // dedup-style "<default> 2" / "(2)" suffixes count as untouched.
+ const nameUntouched = _isDefaultlikeName(curName, prev?.name);
+ const descUntouched = !curDescLocal || (prev && curDescLocal === prevDescLocal);
+ if (next2 && nameUntouched) updates.name = next2.name;
+ if (next2) {
+ if (descUntouched) {
+ updates.description_zh = next2.description_zh;
+ updates.description_en = next2.description_en;
+ }
+ }
try {
const res = await window.orkas.invoke('agents.update', {
- agent_id: agent.agent_id, updates: { runtime: { kind: 'cli', cli: m[1] } },
+ agent_id: agent.agent_id, updates,
});
if (res?.ok && res.agent) {
_agentsCache = null;
const fetched = await apiFetch(`/api/agents/${encodeURIComponent(agent.agent_id)}`);
const data = await fetched.json();
if (data.ok && data.agent) _renderAgentDetail(data.agent, _agentEditing);
+ } else if (res?.code === 'E_AGENT_NAME_TAKEN') {
+ // Name we tried to auto-apply already belongs to another
+ // agent. Re-issue the update without the name override so
+ // the runtime swap still goes through.
+ const safeUpdates = { ...updates };
+ delete safeUpdates.name;
+ await window.orkas.invoke('agents.update', {
+ agent_id: agent.agent_id, updates: safeUpdates,
+ });
+ _agentsCache = null;
+ const fetched = await apiFetch(`/api/agents/${encodeURIComponent(agent.agent_id)}`);
+ const data = await fetched.json();
+ if (data.ok && data.agent) _renderAgentDetail(data.agent, _agentEditing);
}
} catch (err) {
_agentsLog.warn('agents.update runtime failed', err);
@@ -619,9 +658,19 @@ async function _enterAgentEditMode() {
const res = await apiFetch(`/api/agents/${encodeURIComponent(_selectedAgent.id)}`);
const data = await res.json();
if (data.ok && data.agent) _renderAgentDetail(data.agent, true);
- document.getElementById('agents-chat-col').style.display = '';
- await _loadAgentChatHistory(_selectedAgent.id);
- setTimeout(() => document.getElementById('agents-chat-input')?.focus(), 50);
+ // External (cli-runtime) agents have no LLM-driven authoring — the
+ // CLI brings its own behaviour, and the edit chat would just sit
+ // empty. Hide the chat column so the user only sees the manual
+ // name + description editors. In-process agents keep the chat.
+ const isExternal = !!(data.ok && data.agent && data.agent.runtime?.kind === 'cli');
+ const chatCol = document.getElementById('agents-chat-col');
+ if (chatCol) chatCol.style.display = isExternal ? 'none' : '';
+ if (!isExternal) {
+ await _loadAgentChatHistory(_selectedAgent.id);
+ setTimeout(() => document.getElementById('agents-chat-input')?.focus(), 50);
+ } else {
+ setTimeout(() => document.getElementById('agents-detail-name')?.focus(), 50);
+ }
// Wire field blur-save (one-time attach)
_bindAgentFieldSave();
}
@@ -689,7 +738,12 @@ async function _flushAgentFieldSave() {
body: JSON.stringify({ [field]: value }),
});
const data = await res.json();
- if (!data.ok) throw new Error(data.error || 'save failed');
+ if (!data.ok) {
+ // Surface duplicate-name / reserved-name with their localised messages
+ // instead of the raw English server text.
+ const localised = _agentCreateErrorMessage(data);
+ throw new Error(localised || data.error || 'save failed');
+ }
// Eagerly refresh — name changes feed the chat-bubble @-mention regex
// (`_buildMentionRe` reads `_agentsCache`); leaving the cache null until
// the next picker open means freshly-typed `@<multi-word-name>` only
@@ -712,24 +766,133 @@ async function _flushAgentFieldSave() {
}
}
-// ─── Create agent (modal-first, mirrors skill flow) ───
+// ─── Create agent (modal-first, two tabs: 创建 / 外接) ───
+//
+// "创建" (default tab) — manual authoring of an in-process agent. The
+// LLM-driven edit chat opens immediately on save so the workflow can
+// be refined.
+//
+// "外接" — bind a local CLI as the runtime. CLI selector is at the top
+// (default 未选择); selecting a CLI auto-fills name + description from
+// CLI_DEFAULTS. The user can override either; subsequent CLI swaps
+// only re-fill fields that still match the previous CLI's defaults
+// (so a user-edited value is never clobbered).
+//
+// Track the last-applied CLI defaults so that "switch CLI → fields
+// follow" can detect "did the user touch this field?". `null` =
+// nothing applied yet (untouched-default state, or 创建 tab).
+
+function _switchAgentTab(tab) {
+ const tabs = document.querySelectorAll('#agent-modal-tabs [data-agent-tab]');
+ tabs.forEach((el) => el.classList.toggle('is-active', el.dataset.agentTab === tab));
+ const panels = document.querySelectorAll('#agent-modal [data-agent-panel]');
+ panels.forEach((el) => el.classList.toggle('is-active', el.dataset.agentPanel === tab));
+ const msgEl = document.getElementById('agent-form-msg');
+ if (msgEl) { msgEl.textContent = ''; msgEl.className = 'form-msg'; }
+ setTimeout(() => {
+ const focusId = tab === 'external' ? 'agent-modal-ext-cli-select' : 'agent-name-input';
+ const el = document.getElementById(focusId);
+ // ai-select wrapper isn't focusable directly; just leave it alone.
+ if (el && typeof el.focus === 'function' && el.tagName !== 'DIV') el.focus();
+ }, 30);
+}
+window._switchAgentTab = _switchAgentTab;
+
+// Track which CLI defaults are currently reflected in the External-tab
+// inputs. When a user types over a default, the field key drops out of
+// this set so subsequent CLI swaps don't overwrite the typed value.
+let _extActiveCli = null;
+let _extDefaultFieldsAtMount = { name: false, desc: false };
+
+/** Decide whether a current `name` value still counts as "the default
+ * for `defaultName`" — meaning a CLI swap should overwrite it. We
+ * recognise the bare default plus the dedup-style suffixes a user
+ * is likely to add when fighting the name-taken error: "Claude Code",
+ * "Claude Code 2", "Claude Code-2", "Claude Code (2)", etc. Anything
+ * with non-digit text after the default ("Claude Code Pro") counts as
+ * user-edited and is kept. */
+function _isDefaultlikeName(value, defaultName) {
+ if (!value) return true;
+ if (!defaultName) return false;
+ if (value === defaultName) return true;
+ const escaped = defaultName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const re = new RegExp('^' + escaped + '\\s*(?:[-_]\\s*)?(?:\\(\\s*\\d+\\s*\\)|\\d+)$');
+ return re.test(value);
+}
+
+function _applyExternalCliDefaults(cliType, { force = false } = {}) {
+ const defaults = (typeof getCliDefaults === 'function') ? getCliDefaults(cliType) : null;
+ const nameEl = document.getElementById('agent-ext-name-input');
+ const descEl = document.getElementById('agent-ext-desc-input');
+ if (!nameEl || !descEl) return;
+
+ const lang = (typeof getLang === 'function') ? getLang() : 'zh';
+ const localizedDesc = defaults
+ ? (lang === 'en' ? defaults.description_en : defaults.description_zh)
+ : '';
+ const targetName = defaults ? defaults.name : '';
+ const targetDesc = localizedDesc;
+
+ // Decide per field whether to overwrite. The two checks are independent —
+ // a user who edits the name but leaves the description alone keeps their
+ // name and gets a refreshed description. "Default-like name" also covers
+ // dedup suffixes like "Claude Code 2" (added to dodge name-taken errors).
+ const prev = (typeof getCliDefaults === 'function') ? getCliDefaults(_extActiveCli) : null;
+ const prevDescLocalized = prev ? (lang === 'en' ? prev.description_en : prev.description_zh) : '';
+
+ const nameUntouched = force || _isDefaultlikeName(nameEl.value, prev?.name);
+ const descUntouched = force
+ || descEl.value === ''
+ || (prev && descEl.value === prevDescLocalized);
+
+ if (cliType === null) {
+ // Reverted to 未选择 — only clear fields that still hold the
+ // previous CLI's defaults. Keep user-typed text.
+ if (nameUntouched) nameEl.value = '';
+ if (descUntouched) descEl.value = '';
+ } else {
+ if (nameUntouched) nameEl.value = targetName;
+ if (descUntouched) descEl.value = targetDesc;
+ }
+ _extActiveCli = cliType;
+}
function openAgentModal() {
const modal = document.getElementById('agent-modal');
- const nameInput = document.getElementById('agent-name-input');
- const descInput = document.getElementById('agent-desc-input');
const msgEl = document.getElementById('agent-form-msg');
- nameInput.value = '';
- descInput.value = '';
msgEl.textContent = '';
msgEl.className = 'form-msg';
- // Refresh runtime selector each open — local CLI install state can
- // change between opens (user installs claude during the session).
- if (typeof mountLocalAgentRuntimeRow === 'function') {
- mountLocalAgentRuntimeRow().catch(() => { /* falls through to hidden row */ });
+
+ // Reset both panels' inputs.
+ const nameInput = document.getElementById('agent-name-input');
+ const descInput = document.getElementById('agent-desc-input');
+ const extName = document.getElementById('agent-ext-name-input');
+ const extDesc = document.getElementById('agent-ext-desc-input');
+ if (nameInput) nameInput.value = '';
+ if (descInput) descInput.value = '';
+ if (extName) extName.value = '';
+ if (extDesc) extDesc.value = '';
+ _extActiveCli = null;
+ _extDefaultFieldsAtMount = { name: true, desc: true };
+
+ // Wire tabs (idempotent).
+ const tabBar = document.getElementById('agent-modal-tabs');
+ if (tabBar && !tabBar.dataset.wired) {
+ tabBar.querySelectorAll('[data-agent-tab]').forEach((btn) => {
+ btn.addEventListener('click', () => _switchAgentTab(btn.dataset.agentTab));
+ });
+ tabBar.dataset.wired = '1';
}
+ _switchAgentTab('create');
+
+ // Refresh the External-tab CLI selector. Re-mount each open so newly-
+ // installed CLIs surface without an app restart.
+ if (typeof mountExternalCliSelect === 'function') {
+ mountExternalCliSelect((cli) => _applyExternalCliDefaults(cli)).catch(() => {});
+ }
+
modal.classList.add('open');
- setTimeout(() => nameInput.focus(), 50);
+ setTimeout(() => document.getElementById('agent-name-input')?.focus(), 50);
}
window.openAgentModal = openAgentModal;
@@ -739,9 +902,16 @@ function closeAgentModal() {
window.closeAgentModal = closeAgentModal;
async function saveAgentModal() {
+ const msgEl = document.getElementById('agent-form-msg');
+ const activeTab = document.querySelector('#agent-modal-tabs .is-active')?.dataset.agentTab || 'create';
+ if (activeTab === 'external') return _saveExternalAgent({ msgEl });
+ return _saveCreateAgent({ msgEl });
+}
+window.saveAgentModal = saveAgentModal;
+
+async function _saveCreateAgent({ msgEl }) {
const name = document.getElementById('agent-name-input').value.trim();
const description = document.getElementById('agent-desc-input').value.trim();
- const msgEl = document.getElementById('agent-form-msg');
if (!name) {
msgEl.textContent = t('agents.input_name_needed');
@@ -763,12 +933,8 @@ async function saveAgentModal() {
}
try {
- // 创建时本地随机一对头像,让每个新智能体一上来就有不同的视觉锚点。
- // 不让 LLM 介入 —— 头像是 UI 元数据,不影响 prompt 行为。
const avatar = randomAgentAvatar();
- const runtime = (typeof getRuntimeFormValue === 'function') ? getRuntimeFormValue() : null;
const body = { name, description, icon: avatar.icon, color: avatar.color };
- if (runtime) body.runtime = runtime;
const res = await apiFetch('/api/agents/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -776,7 +942,7 @@ async function saveAgentModal() {
});
const data = await res.json();
if (!data.ok || !data.agent) {
- msgEl.textContent = data.error || t('agents.create_failed');
+ msgEl.textContent = _agentCreateErrorMessage(data) || t('agents.create_failed');
msgEl.className = 'form-msg err';
return;
}
@@ -785,8 +951,6 @@ async function saveAgentModal() {
await loadAgents(true);
await _showAgentsDetailView(data.agent.agent_id);
await _enterAgentEditMode();
- // Auto-seed: use the user's description as context for the LLM so it
- // starts refining the workflow without the user having to restate it.
const seed = t('agents.seed_workflow', { description });
await _autoSendAgentChat(seed);
} catch (e) {
@@ -794,7 +958,89 @@ async function saveAgentModal() {
msgEl.className = 'form-msg err';
}
}
-window.saveAgentModal = saveAgentModal;
+
+async function _saveExternalAgent({ msgEl }) {
+ const cli = (typeof getExternalCliValue === 'function') ? getExternalCliValue() : null;
+ const name = document.getElementById('agent-ext-name-input').value.trim();
+ const desc = document.getElementById('agent-ext-desc-input').value.trim();
+
+ if (!cli) {
+ msgEl.textContent = t('agents.ext_cli_needed');
+ msgEl.className = 'form-msg err';
+ return;
+ }
+ if (!name) {
+ msgEl.textContent = t('agents.input_name_needed');
+ msgEl.className = 'form-msg err';
+ document.getElementById('agent-ext-name-input').focus();
+ return;
+ }
+ if (_isReservedAgentName(name)) {
+ msgEl.textContent = t('agents.name_reserved');
+ msgEl.className = 'form-msg err';
+ document.getElementById('agent-ext-name-input').focus();
+ return;
+ }
+ if (!desc) {
+ msgEl.textContent = t('agents.input_desc_needed');
+ msgEl.className = 'form-msg err';
+ document.getElementById('agent-ext-desc-input').focus();
+ return;
+ }
+
+ // Both `description_zh` + `description_en` are stored so locale switches
+ // are zero-cost. The locale we're currently editing in goes into that
+ // side; the other side gets the canonical CLI default. Users who want
+ // both fully-translated can edit each side later.
+ const defaults = (typeof getCliDefaults === 'function') ? getCliDefaults(cli) : null;
+ const lang = (typeof getLang === 'function') ? getLang() : 'zh';
+ const description_zh = lang === 'zh' ? desc : (defaults ? defaults.description_zh : desc);
+ const description_en = lang === 'en' ? desc : (defaults ? defaults.description_en : desc);
+
+ try {
+ const avatar = randomAgentAvatar();
+ const body = {
+ name,
+ description: desc,
+ description_zh, description_en,
+ icon: avatar.icon, color: avatar.color,
+ runtime: { kind: 'cli', cli },
+ };
+ const res = await apiFetch('/api/agents/create', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const data = await res.json();
+ if (!data.ok || !data.agent) {
+ msgEl.textContent = _agentCreateErrorMessage(data) || t('agents.create_failed');
+ msgEl.className = 'form-msg err';
+ return;
+ }
+ closeAgentModal();
+ setView('agents');
+ await loadAgents(true);
+ // External agents go straight to the detail view but skip the LLM
+ // edit-chat — there's nothing to author. The user can still rename
+ // or reword the description through the inline name/desc editors.
+ await _showAgentsDetailView(data.agent.agent_id);
+ } catch (e) {
+ msgEl.textContent = t('agents.network_error', { reason: e.message || e });
+ msgEl.className = 'form-msg err';
+ }
+}
+
+/** Normalise IPC-shim error replies into a user-facing message. The
+ * backend tags duplicate-name / reserved-name failures with a `code`
+ * so we surface the localised string instead of the raw "agent name
+ * ... is already in use" English text. */
+function _agentCreateErrorMessage(data) {
+ if (!data) return '';
+ const code = data.code;
+ if (code === 'E_AGENT_NAME_TAKEN') return t('agents.name_taken');
+ if (code === 'E_AGENT_NAME_RESERVED') return t('agents.name_reserved');
+ return data.error || '';
+}
async function _autoSendAgentChat(content) {
if (!_selectedAgent) return;
@@ -1182,6 +1428,11 @@ function bindAgentPickers() {
_renderAgentPickerList(searchInput.value);
});
searchInput?.addEventListener('keydown', (e) => {
+ // IME composition guard (CLAUDE.md §8): Enter / Arrow keys belong to
+ // the IME while a Chinese / Japanese / Korean candidate is being
+ // composed; without this early-return, pressing Enter to commit an
+ // English candidate would also fire our select-active-item handler.
+ if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Escape') { _atKeyMark = null; _closeAgentPicker(); e.preventDefault(); return; }
if (e.key === 'ArrowDown') { _moveAgentPickerActive(1); e.preventDefault(); return; }
if (e.key === 'ArrowUp') { _moveAgentPickerActive(-1); e.preventDefault(); return; }
diff --git a/src/renderer/modules/chat-input-form.js b/src/renderer/modules/chat-input-form.js
index c5e65715..d76ad335 100644
--- a/src/renderer/modules/chat-input-form.js
+++ b/src/renderer/modules/chat-input-form.js
@@ -129,6 +129,72 @@
ctrlWrap.appendChild(fileWidget.el);
read = fileWidget.read;
isReady = fileWidget.isReady;
+ } else if (field.type === 'directory') {
+ // Directory picker: native dialog through `common.pickDirectory`.
+ // The widget shows the picked absolute path; the value submitted is
+ // the path string (or empty when nothing picked). Used by external
+ // coding agents (claude / codex) to collect their cwd via the
+ // standard input-form pipeline.
+ const dirWrap = document.createElement('div');
+ dirWrap.className = 'form-field-dir';
+ const pathLabel = document.createElement('span');
+ pathLabel.className = 'form-field-dir-path';
+ let value = (typeof initial === 'string' && initial) ? initial : '';
+ const renderPath = () => {
+ if (value) {
+ pathLabel.textContent = value;
+ pathLabel.title = value;
+ pathLabel.classList.remove('is-empty');
+ } else {
+ pathLabel.textContent = t('input.dir.none') || '(未选择)';
+ pathLabel.removeAttribute('title');
+ pathLabel.classList.add('is-empty');
+ }
+ };
+ renderPath();
+ const pickBtn = document.createElement('button');
+ pickBtn.type = 'button';
+ pickBtn.className = 'btn btn-sm form-field-dir-pick';
+ pickBtn.textContent = t('input.dir.pick') || '选择目录…';
+ const clearBtn = document.createElement('button');
+ clearBtn.type = 'button';
+ clearBtn.className = 'btn btn-sm form-field-dir-clear';
+ clearBtn.textContent = t('input.dir.clear') || '清除';
+ pickBtn.disabled = disabled;
+ clearBtn.disabled = disabled;
+ pickBtn.addEventListener('click', async () => {
+ try {
+ const res = await window.orkas.invoke('common.pickDirectory', {
+ title: field.label || '选择目录',
+ });
+ if (res && !res.cancelled && res.path) {
+ value = String(res.path);
+ renderPath();
+ pickBtn.textContent = t('input.dir.change') || '更换…';
+ // Notify the form so the submit button re-evaluates `isReady`
+ // — without this the button stays disabled (and shows the
+ // "请等待文件上传完成" hint) even after the user picks a dir.
+ if (ctx && typeof ctx.onChange === 'function') ctx.onChange();
+ }
+ } catch (_) { /* user cancelled or no permission */ }
+ });
+ clearBtn.addEventListener('click', () => {
+ value = '';
+ renderPath();
+ pickBtn.textContent = t('input.dir.pick') || '选择目录…';
+ if (ctx && typeof ctx.onChange === 'function') ctx.onChange();
+ });
+ if (value) pickBtn.textContent = t('input.dir.change') || '更换…';
+ dirWrap.appendChild(pickBtn);
+ dirWrap.appendChild(clearBtn);
+ dirWrap.appendChild(pathLabel);
+ ctrlWrap.appendChild(dirWrap);
+ read = () => value;
+ // No `isReady` override: `isReady` is reserved for "in-flight"
+ // states (e.g. file upload still going) which gate the submit
+ // button + show the "请等待文件上传完成" hint. Required-empty for a
+ // directory is reported by `_validate` on submit click, matching
+ // text / number / select.
} else {
// Unknown type — shouldn't happen (main validated) but degrade gracefully.
const note = document.createElement('div');
@@ -312,6 +378,8 @@
? !Array.isArray(value) || value.length === 0
: !value;
if (empty) return t('chat.form.required_file');
+ } else if (field.type === 'directory') {
+ if (!String(value || '').trim()) return t('chat.form.required_directory');
}
}
if (field.type === 'number' && typeof value === 'number') {
diff --git a/src/renderer/modules/contexts.js b/src/renderer/modules/contexts.js
index fb2487cc..22ddeb9a 100644
--- a/src/renderer/modules/contexts.js
+++ b/src/renderer/modules/contexts.js
@@ -247,6 +247,9 @@ function _bindCtxTreeHandlers(container) {
await _commitInlineRename(rel, next);
};
input.addEventListener('keydown', (e) => {
+ // IME guard (CLAUDE.md §8) — Enter while composing should commit
+ // the candidate to the rename input, not finalise the rename.
+ if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Enter') { e.preventDefault(); commit(true); }
else if (e.key === 'Escape') { e.preventDefault(); commit(false); }
});
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index 0f258247..d39d58a3 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -211,6 +211,8 @@ function _activeRecipient(target) {
function getChatRecipient(target) { return { ..._activeRecipient(target) }; }
+function _onRecipientChanged(_target) { /* reserved for future hooks */ }
+
function setChatRecipient(target, next, _opts = {}) {
const r = _normRecipient(next);
if (!r) return;
@@ -222,6 +224,7 @@ function setChatRecipient(target, next, _opts = {}) {
_saveRecipientMap();
}
_renderRecipientChip(target);
+ _onRecipientChanged(target);
}
// Called by the new-chat send path *after* the new conv id is known so the
@@ -1243,7 +1246,7 @@ async function loadConversationHistory(cid) {
const loadingEl = appendChatMessage({
role: 'assistant',
content: `<span class="chat-replying">${escapeHtml(t('chat.thinking'))}</span>`,
- time: new Date().toISOString(),
+ time: nowIsoLocal(),
});
pendingConvs.set(cid, { loadingEl, needsIndicator: false });
_updateConvSendUI(cid);
@@ -1267,7 +1270,7 @@ async function loadConversationHistory(cid) {
const loadingEl = appendChatMessage({
role: 'assistant',
content: `<span class="chat-replying">${escapeHtml(t('chat.thinking'))}</span>`,
- time: new Date().toISOString(),
+ time: nowIsoLocal(),
});
state.loadingEl = loadingEl;
}
@@ -2459,7 +2462,12 @@ function createChatController(config) {
{
role: 'user',
content,
- time: new Date().toISOString(),
+ // Match server's `nowIso()` format (local-time, second-precision).
+ // Using `new Date().toISOString()` here would ms-bump the user
+ // bubble past the server-stamped agent reply within the same
+ // second and `_insertByTimestamp` would render the agent's
+ // reply before the user message.
+ time: nowIsoLocal(),
...(attachmentsForBubble ? { attachments: attachmentsForBubble } : {}),
},
false,
@@ -2611,8 +2619,11 @@ function createChatController(config) {
if (inputEl && !inputEl.dataset.ctrlBound) {
inputEl.dataset.ctrlBound = '1';
inputEl.addEventListener('keydown', (e) => {
- // Enter sends; Shift+Enter newline; Ctrl/Cmd+Enter also sends. Skip IME.
- if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
+ // Enter sends; Shift+Enter newline; Ctrl/Cmd+Enter also sends. Skip IME
+ // (CLAUDE.md §8 — keyCode 229 catches older Electron / Safari builds
+ // where `isComposing` is occasionally inaccurate).
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
_submitFromInput();
}
diff --git a/src/renderer/modules/dialogs.js b/src/renderer/modules/dialogs.js
index 8f44159a..b81102fb 100644
--- a/src/renderer/modules/dialogs.js
+++ b/src/renderer/modules/dialogs.js
@@ -30,6 +30,9 @@ function _uiShowDialog({ message, showCancel }) {
const okBtn = overlay.querySelector('[data-act="ok"]');
const cancelBtn = overlay.querySelector('[data-act="cancel"]');
const onKey = (e) => {
+ // IME guard (CLAUDE.md §8) — Enter while composing should commit
+ // the IME candidate, not auto-confirm the dialog.
+ if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Escape') finish(false);
else if (e.key === 'Enter') finish(true);
};
@@ -84,6 +87,9 @@ function uiPrompt(message, defaultValue = '') {
const okBtn = overlay.querySelector('[data-act="ok"]');
const cancelBtn = overlay.querySelector('[data-act="cancel"]');
const onKey = (e) => {
+ // IME guard (CLAUDE.md §8) — Enter while composing in the prompt
+ // input belongs to the IME, not to the dialog confirm action.
+ if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Escape') finish(null);
else if (e.key === 'Enter' && e.target === input) finish(input.value);
};
diff --git a/src/renderer/modules/ipc-shim.js b/src/renderer/modules/ipc-shim.js
index 81ddf3cc..36d0ccf4 100644
--- a/src/renderer/modules/ipc-shim.js
+++ b/src/renderer/modules/ipc-shim.js
@@ -46,6 +46,7 @@ const _IPC_ROUTES = [
['POST', '/api/contexts/reveal', 'contexts.reveal'],
['POST', '/api/search/global', 'search.global'],
['POST', '/api/conversations/attachments/adopt', 'conversations.attachments.adopt'],
+ ['POST', '/api/common/pick-directory', 'common.pickDirectory'],
['GET', '/api/kb/status', 'kb.status'],
['POST', '/api/kb/reconcile', 'kb.reconcile'],
['POST', '/api/kb/reprocess', 'kb.reprocess'],
diff --git a/src/renderer/modules/local-agents.js b/src/renderer/modules/local-agents.js
index dbeb51a3..0d968e4d 100644
--- a/src/renderer/modules/local-agents.js
+++ b/src/renderer/modules/local-agents.js
@@ -1,24 +1,76 @@
// ─── Local CLI agents (renderer side) ─────────────────────────────────
//
-// One dropdown in the create-agent modal:
-// Orkas (default, in-process) | Claude Code | Codex | OpenClaw | OpenCode | Hermes
-// Anything not detected on this machine is omitted from the list.
+// Two surfaces share this module:
+// 1. The agent-modal "外接" tab — selector lists every detected CLI
+// (default: 未选择). Selecting one auto-fills name + description
+// from CLI_DEFAULTS so a single click is enough to ship an
+// external-agent shell.
+// 2. The agent-detail runtime selector (existing CLI-bound agents)
+// lives in agents.js; this module just supplies the registry list.
//
-// Model + custom_args are intentionally NOT exposed in the modal — the
-// CLI picks its own default model (closer to what the user's account
-// actually supports), and most users never need extra flags. The spec
-// still supports both fields; advanced users can hand-edit `agent.json`
-// or we add a "details" toggle later when there's real demand.
+// CLI_DEFAULTS holds the bilingual seed values used by both create
+// and edit. `description_zh` + `description_en` are stored side-by-
+// side on the agent so locale switches are zero-cost; `name` is a
+// single brand label (the user can rename to disambiguate two
+// instances of the same CLI bound to different project_dirs).
//
-// Detection pre-warms 500ms after the first agents-page render so the
-// 60s registry cache is warm by the time the user opens the modal —
-// the first cold detection runs `which` + `--version` for each CLI in
-// parallel and can take ~200ms; this avoids the layout-shift flash
-// that comes from awaiting it inside `openAgentModal`.
+// Detection pre-warms 500ms after script load so the first modal
+// open doesn't pay the cold detection cost.
const _localAgentsLog = createLogger('local-agents');
-let _localCliEntries = null; // cached availability list
+// Single source of truth for default name + description per CLI type.
+// English-source (per CLAUDE.md "English-only project text") with the
+// Chinese variant carried alongside for the agent description pair.
+const CLI_DEFAULTS = {
+ claude: {
+ name: 'Claude Code',
+ description_zh: 'Anthropic 出品的本地编码智能体 CLI,擅长代码理解、重构与多文件改动;支持工程上下文感知、工具调用与流式回复。',
+ description_en: "Anthropic's local coding agent CLI — strong at code understanding, refactoring, and multi-file edits; project-aware context, tool use, streaming output.",
+ isCoding: true,
+ },
+ codex: {
+ name: 'Codex',
+ description_zh: 'OpenAI 出品的本地编码智能体 CLI,擅长代码生成与补丁式改写;支持沙箱执行与会话续接。',
+ description_en: "OpenAI's local coding agent CLI — strong at code generation and patch-style edits; sandboxed execution and session resume.",
+ isCoding: true,
+ },
+ openclaw: {
+ name: 'OpenClaw',
+ description_zh: '开源多模型聚合智能体 CLI,可在多家模型/工具间切换;适合通用任务编排与轻量自动化。',
+ description_en: 'Open-source multi-model agent CLI; routes across providers and tools — good for general orchestration and lightweight automation.',
+ isCoding: false,
+ },
+ opencode: {
+ name: 'OpenCode',
+ description_zh: '开源编码智能体 CLI,支持多模型切换;侧重代码生成、文件改写与终端任务。',
+ description_en: 'Open-source coding agent CLI with multi-model support; focused on code generation, file editing, and terminal tasks.',
+ isCoding: false,
+ },
+ hermes: {
+ name: 'Hermes',
+ description_zh: '通过 ACP 协议接入的智能体 CLI,可执行多步任务与工具调用;以会话粒度协同。',
+ description_en: 'Agent CLI integrated over the ACP protocol; runs multi-step tasks with tool use; session-scoped collaboration.',
+ isCoding: false,
+ },
+};
+
+/** Defaults for a given CLI type, or null when the type is unknown. */
+function getCliDefaults(cliType) {
+ return cliType && Object.prototype.hasOwnProperty.call(CLI_DEFAULTS, cliType)
+ ? CLI_DEFAULTS[cliType]
+ : null;
+}
+
+/** True when the CLI is one of claude / codex (the coding agents that
+ * expose a project-dir form input). Mirrors `cliSupportsProjectDir`
+ * in features/agents.ts — keep in sync. */
+function cliIsCodingAgent(cliType) {
+ const d = getCliDefaults(cliType);
+ return !!(d && d.isCoding);
+}
+
+let _localCliEntries = null;
async function loadLocalCliEntries({ force = false } = {}) {
if (_localCliEntries && !force) return _localCliEntries;
@@ -32,69 +84,73 @@ async function loadLocalCliEntries({ force = false } = {}) {
return _localCliEntries;
}
-let _runtimeSelectApi = null;
+// ── External-tab CLI selector (create modal) ───────────────────────────
+//
+// Sentinel value for "未选择" — distinct from empty string so a user who
+// genuinely empties the selector still re-routes through this branch.
+const EXT_CLI_NONE = '__none__';
+
+let _extCliSelectApi = null;
/**
- * Render the runtime selector inside the create-agent modal.
- * - No CLIs detected → row stays hidden, selector treated as Orkas.
- * - At least one detected → fills with "Orkas" (default) + each
- * available CLI; defaults to Orkas.
- * Idempotent: calling again rebuilds the row from current detection.
+ * Mount the External-tab CLI selector. Default option is 未选择;
+ * detected CLIs follow. `onChange` fires with the chosen `LocalCliType`
+ * (string) or null when the user reverts to 未选择 — agents.js wires
+ * this to the auto-fill / project-dir-row toggling logic.
+ *
+ * Idempotent: re-mounting just resets options + value so a re-open of
+ * the modal picks up newly-installed CLIs.
*/
-async function mountLocalAgentRuntimeRow() {
- const row = document.getElementById('agent-modal-runtime-row');
- const mount = document.getElementById('agent-modal-runtime-select');
- if (!row || !mount) return false;
-
+async function mountExternalCliSelect(onChange) {
+ const mount = document.getElementById('agent-modal-ext-cli-select');
+ if (!mount) return null;
const entries = await loadLocalCliEntries();
const available = entries.filter(e => e.available);
- if (available.length === 0) {
- row.style.display = 'none';
- if (_runtimeSelectApi) _runtimeSelectApi.setOptions([], { value: 'in_process' });
- return false;
- }
-
- row.style.display = '';
+ const noneLabel = t('agent_modal.ext_cli_none') || '未选择';
const options = [
- { value: 'in_process', label: t('agent_modal.runtime_in_process') },
+ { value: EXT_CLI_NONE, label: noneLabel },
...available.map(e => ({
- value: `cli:${e.type}`,
- label: `${t('agent_modal.runtime_cli_' + e.type)}${e.version ? ` (${e.version})` : ''}`,
+ value: e.type,
+ label: `${(getCliDefaults(e.type)?.name) || e.type}${e.version ? ` (${e.version})` : ''}`,
})),
];
- // Mount once, re-set options on subsequent opens. Keeps the API
- // instance stable so `getRuntimeFormValue` reads the same widget.
- if (!_runtimeSelectApi) {
- _runtimeSelectApi = _aiSelectMount(mount, {
- options, value: 'in_process',
- placeholder: t('agent_modal.runtime_in_process'),
- onChange: () => { /* read on save */ },
+ const handleChange = (v) => {
+ const cli = (!v || v === EXT_CLI_NONE) ? null : v;
+ if (typeof onChange === 'function') onChange(cli);
+ };
+ if (!_extCliSelectApi) {
+ _extCliSelectApi = _aiSelectMount(mount, {
+ options, value: EXT_CLI_NONE,
+ placeholder: noneLabel,
+ onChange: handleChange,
});
} else {
- _runtimeSelectApi.setOptions(options, { value: 'in_process' });
+ _extCliSelectApi.setOptions(options, { value: EXT_CLI_NONE });
}
- return true;
+ return _extCliSelectApi;
}
-/**
- * Read the current selector state into a runtime spec, or null when
- * the user kept "Orkas" (so the caller doesn't write a runtime field
- * at all and the agent stays in-process by default). Model + custom
- * args are not collected here — backends fall back to their own
- * defaults, which is usually what users want.
- */
-function getRuntimeFormValue() {
- const v = _runtimeSelectApi ? _runtimeSelectApi.getValue() : 'in_process';
- if (!v || v === 'in_process') return null;
- const m = /^cli:(.+)$/.exec(v);
- if (!m) return null;
- return { kind: 'cli', cli: m[1] };
+/** Read the currently-selected CLI type from the External tab, or null
+ * when the user kept "未选择". */
+function getExternalCliValue() {
+ const v = _extCliSelectApi ? _extCliSelectApi.getValue() : EXT_CLI_NONE;
+ if (!v || v === EXT_CLI_NONE) return null;
+ return v;
+}
+
+/** Programmatically set the External-tab selector (used by edit form
+ * to seed from the bound CLI). Pass null to revert to 未选择. */
+function setExternalCliValue(cliType) {
+ if (!_extCliSelectApi) return;
+ _extCliSelectApi.setValue(cliType || EXT_CLI_NONE);
}
-// Pre-warm the registry cache shortly after script load so the first
-// modal open doesn't pay the cold detection cost. Fire-and-forget.
+// Pre-warm the registry cache.
setTimeout(() => { loadLocalCliEntries().catch(() => { /* warm-up best-effort */ }); }, 500);
-window.mountLocalAgentRuntimeRow = mountLocalAgentRuntimeRow;
-window.getRuntimeFormValue = getRuntimeFormValue;
window.loadLocalCliEntries = loadLocalCliEntries;
+window.getCliDefaults = getCliDefaults;
+window.cliIsCodingAgent = cliIsCodingAgent;
+window.mountExternalCliSelect = mountExternalCliSelect;
+window.getExternalCliValue = getExternalCliValue;
+window.setExternalCliValue = setExternalCliValue;
diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.js
index 30ee1137..0ac1eec4 100644
--- a/src/renderer/modules/settings.js
+++ b/src/renderer/modules/settings.js
@@ -464,8 +464,16 @@ function _settingsShowApiKeyForm(provider, modelId) {
await _settingsReload();
};
saveBtn.onclick = save;
- labelInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') { keyInput.focus(); e.preventDefault(); } });
- keyInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') { save(); e.preventDefault(); } });
+ // IME guard (CLAUDE.md §8): Enter on these inputs advances focus / saves;
+ // skip while a Chinese / Japanese / Korean candidate is being composed.
+ labelInput.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Enter') { keyInput.focus(); e.preventDefault(); }
+ });
+ keyInput.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Enter') { save(); e.preventDefault(); }
+ });
actions.appendChild(cancelBtn);
actions.appendChild(saveBtn);
@@ -603,7 +611,10 @@ function _oauthFlowRender(provider, status, closeFlow) {
await window.orkas.invoke('auth.submitOAuthInput', { flowId: _oauthFlowId, value: val });
};
body.querySelector('.oauth-manual-submit-btn').onclick = submit;
- input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { submit(); e.preventDefault(); } });
+ input.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Enter') { submit(); e.preventDefault(); }
+ });
}
return;
}
@@ -629,7 +640,10 @@ function _oauthFlowRender(provider, status, closeFlow) {
await window.orkas.invoke('auth.submitOAuthInput', { flowId: _oauthFlowId, value: val });
};
body.querySelector('.oauth-submit-btn').onclick = submit;
- input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { submit(); e.preventDefault(); } });
+ input.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Enter') { submit(); e.preventDefault(); }
+ });
setTimeout(() => input.focus(), 0);
return;
}
diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.js
index 0fb1fba7..146263f0 100644
--- a/src/renderer/modules/state.js
+++ b/src/renderer/modules/state.js
@@ -154,7 +154,9 @@ function bindStaticHandlers() {
// Enter sends; Shift+Enter newline; Ctrl/Cmd+Enter also sends (kept for
// muscle memory). Skip while IME is composing — Chinese pinyin commit
// also fires Enter and would otherwise send a half-typed message.
- if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
+ // keyCode 229 catches older Electron / Safari builds (CLAUDE.md §8).
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleNewChatSubmit();
}
@@ -176,8 +178,10 @@ function bindStaticHandlers() {
}
});
chatInput.addEventListener('keydown', (e) => {
- // Enter sends; Shift+Enter newline; Ctrl/Cmd+Enter also sends. Skip IME.
- if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
+ // Enter sends; Shift+Enter newline; Ctrl/Cmd+Enter also sends. Skip IME
+ // (CLAUDE.md §8 — keyCode 229 belt-and-suspenders for older builds).
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleChatSubmit();
}
diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.js
index c062a47a..93539423 100644
--- a/src/renderer/modules/utils.js
+++ b/src/renderer/modules/utils.js
@@ -380,6 +380,19 @@ document.addEventListener('click', (e) => {
window.orkas.invoke('auth.openExternal', { url: href }).catch(() => {});
});
+/** Renderer-side mirror of `storage.ts::nowIso()` — local-time ISO8601
+ * truncated to seconds, no TZ suffix. Optimistic / placeholder timestamps
+ * must use this format so they sort identically with persisted ts strings
+ * produced server-side. Mixing `new Date().toISOString()` (UTC + ms) with
+ * the server's second-precision local-time string parses to a 0–999ms
+ * drift that makes a same-second user msg test as "later than" the agent
+ * reply, flipping bubble order in the chat (CLAUDE.md §8). */
+function nowIsoLocal() {
+ const d = new Date();
+ const pad = (n) => String(n).padStart(2, '0');
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
+}
+
function formatTime(iso) {
if (!iso) return '-';
try {
@@ -553,6 +566,11 @@ function _aiSelectMount(el, config) {
const onDocDown = (e) => { if (!el.contains(e.target)) close(); };
const onKey = (e) => {
+ // IME composition guard (CLAUDE.md §8): the popover keydown listener
+ // is on `document`, so a Chinese / Japanese / Korean composition in an
+ // adjacent input would otherwise commit its Enter into "pick the
+ // active option" of this select.
+ if (e.isComposing || e.keyCode === 229) return;
if (e.key === 'Escape') { close(); e.preventDefault(); }
else if (e.key === 'ArrowDown') {
state.activeIdx = Math.min(state.options.length - 1, state.activeIdx + 1);
diff --git a/src/renderer/style.css b/src/renderer/style.css
index 6c3ca74b..443051de 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -1483,6 +1483,7 @@ body.model-not-configured .main-content { flex-direction: column; }
position: relative;
}
+
/* Inline "创建智能体" entry pinned to the end of #chat-history — divider
lines on both sides with a small button in the middle. Hidden during
streaming via inline display:none toggled in conversation.js. */
@@ -2149,6 +2150,26 @@ body.model-not-configured .main-content { flex-direction: column; }
flex-direction: column;
gap: 6px;
}
+.chat-input-form .form-field-dir {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+.chat-input-form .form-field-dir-path {
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 12px;
+ color: var(--text);
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.chat-input-form .form-field-dir-path.is-empty {
+ font-family: inherit;
+ color: var(--muted);
+}
.chat-input-form .form-field-file-chips {
display: flex;
flex-wrap: wrap;