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.

Translate comments, docstrings, error strings, and renderer fallbacks to English

wyt090027e04e7e
diff --git a/src/core-agent/src/agent/runner.ts b/src/core-agent/src/agent/runner.ts
index 30110b27..cdcd7161 100644
--- a/src/core-agent/src/agent/runner.ts
+++ b/src/core-agent/src/agent/runner.ts
@@ -564,37 +564,37 @@ export class AgentRunner {
// What tools were used
if (metrics.toolNames.length > 0) {
- lines.push(`使用的工具: ${metrics.toolNames.join(', ')}`);
+ lines.push(`Tools used: ${metrics.toolNames.join(', ')}`);
}
// Which skills were loaded
if (metrics.skillsLoaded.length > 0) {
- lines.push(`加载的技能: ${metrics.skillsLoaded.join(', ')}`);
+ lines.push(`Skills loaded: ${metrics.skillsLoaded.join(', ')}`);
}
// Error info with classification
if (result.meta.error) {
- lines.push(`错误: [${result.meta.error.kind}] ${result.meta.error.message}`);
- if (metrics.recovered) lines.push('结果: 从错误中恢复,任务完成');
+ lines.push(`Error: [${result.meta.error.kind}] ${result.meta.error.message}`);
+ if (metrics.recovered) lines.push('Outcome: recovered from the error and completed the task');
}
if (metrics.errorKind !== 'none') {
- const label = metrics.errorKind === 'transient' ? '瞬态(网络/超时/速率限制)'
- : metrics.errorKind === 'mixed' ? '混合(含瞬态 + 永久)'
- : '永久(非瞬态)';
- lines.push(`错误类型: ${label}(瞬态 ${metrics.transientErrorCount} 次)`);
+ const label = metrics.errorKind === 'transient' ? 'transient (network / timeout / rate limit)'
+ : metrics.errorKind === 'mixed' ? 'mixed (transient + permanent)'
+ : 'permanent (non-transient)';
+ lines.push(`Error kind: ${label} (${metrics.transientErrorCount} transient occurrence(s))`);
}
// Trigger signals
- lines.push(`触发信号: ${signals.map(s => `${s.name}(${s.reason})`).join('; ')}`);
+ lines.push(`Trigger signals: ${signals.map(s => `${s.name}(${s.reason})`).join('; ')}`);
// The agent's final response (truncated) — this is the most important
// context for understanding what actually happened
if (result.text) {
const maxLen = 1500;
const text = result.text.length > maxLen
- ? result.text.slice(0, maxLen) + '\n…(截断)'
+ ? result.text.slice(0, maxLen) + '\n…(truncated)'
: result.text;
- lines.push('', '--- 对话最终回复 ---', text);
+ lines.push('', '--- Final assistant reply ---', text);
}
// Session message history (user messages only, for additional context)
@@ -611,7 +611,7 @@ export class AgentRunner {
.filter(t => t.length > 0);
if (userMessages.length > 0) {
- lines.push('', '--- 用户消息 ---');
+ lines.push('', '--- User messages ---');
// Include last few user messages (most relevant)
const recent = userMessages.slice(-3);
for (const msg of recent) {
@@ -702,7 +702,7 @@ export class AgentRunner {
const result = await provider.complete({
model: modelId,
messages: reflectSession.getMessages(),
- systemPrompt: '你是一个自我改进助手。根据对话摘要反思并改进技能和自我认知。可用工具:skill_manage(创建/修补/删除技能)、metacognition(更新 COMPETENCE.md / LEARNING_STRATEGIES.md)。',
+ systemPrompt: 'You are a self-improvement assistant. Reflect on the conversation summary and refine your skills and self-knowledge. Available tools: skill_manage (create / patch / delete skills) and metacognition (update COMPETENCE.md / LEARNING_STRATEGIES.md).',
tools: toolDefs.length > 0 ? toolDefs : undefined,
maxTokens: 2048,
signal,
@@ -808,20 +808,20 @@ function sleep(ms: number): Promise<void> {
*/
function buildSkillsGuidance(skillsIndex: string): string {
const parts: string[] = [
- "## 自我改进:技能 & 元认知",
+ "## Self-improvement: skills & metacognition",
"",
- "你拥有 skill_manage 和 metacognition 两个工具来持续提升自己。",
+ "You have two tools — `skill_manage` and `metacognition` — for continuously improving yourself.",
"",
- "### 技能管理 (skill_manage)",
- "- 完成复杂任务(5+ 工具调用)、修复棘手错误、或发现非显而易见的工作流后,保存为技能",
- "- 使用技能时发现过时或不完整,立即 patch — 不要等用户要求",
- "- 简单一次性任务不需要保存。创建或删除前先和用户确认",
+ "### Skill management (skill_manage)",
+ "- After finishing a complex task (5+ tool calls), fixing a tricky bug, or discovering a non-obvious workflow, save it as a skill",
+ "- If you find a skill outdated or incomplete while using it, patch it immediately — don't wait for the user to ask",
+ "- Simple one-off tasks don't need to be saved. Confirm with the user before creating or deleting a skill",
"",
- "### 元认知 (metacognition)",
- "- COMPETENCE.md: 记录你的擅长领域和已知弱点,每次有重要发现时更新",
- "- LEARNING_STRATEGIES.md: 记录有效的学习策略和解决问题的方法论",
- "- 被用户纠正后,更新 COMPETENCE.md 记录弱点",
- "- 成功解决已知弱点领域的问题后,更新 COMPETENCE.md 记录进步",
+ "### Metacognition",
+ "- COMPETENCE.md: record your strong areas and known weaknesses; update whenever you make an important discovery",
+ "- LEARNING_STRATEGIES.md: record effective learning strategies and problem-solving methodologies",
+ "- After being corrected by the user, update COMPETENCE.md to log the weakness",
+ "- After successfully solving a problem in a previously weak area, update COMPETENCE.md to log the improvement",
];
if (skillsIndex) {
diff --git a/src/core-agent/src/providers/pi-provider.ts b/src/core-agent/src/providers/pi-provider.ts
index 1b5944f0..fbdec431 100644
--- a/src/core-agent/src/providers/pi-provider.ts
+++ b/src/core-agent/src/providers/pi-provider.ts
@@ -279,15 +279,17 @@ export function createPiProvider(config: {
apiKey?: string;
baseUrl?: string;
/** Pre-built pi-ai Model object. Bypasses `getModel()` lookup — use for
- * providers not registered in pi-ai's catalog (e.g. Moonshot 开放平台)
- * where the `Model<"openai-completions">` shape is hand-constructed in
- * the caller. When set, `config.model` / `config.baseUrl` are ignored
- * (the Model already carries them). */
+ * providers not registered in pi-ai's catalog (e.g. Moonshot's open
+ * platform), where the `Model<"openai-completions">` shape is
+ * hand-constructed by the caller. When set, `config.model` /
+ * `config.baseUrl` are ignored (the Model already carries them). */
customModel?: Model<Api>;
- /** pi-ai 每个 provider 在 `buildParams` 之后、发请求之前都会调
- * `options.onPayload?(params, model)`,允许返回新 params 覆盖原 params。
- * 透传到 pi-ai 的同名 hook,上层可借此注入厂商 server-side tools(如
- * `{type:"web_search_preview"}`)而不改 pi-ai 源码。 */
+ /** Each pi-ai provider invokes `options.onPayload?(params, model)`
+ * after `buildParams` and before sending the request, allowing the
+ * callback to return new params that overwrite the originals.
+ * Forwarded directly to pi-ai's hook of the same name; the upper
+ * layer can use it to inject vendor server-side tools (e.g.
+ * `{type:"web_search_preview"}`) without modifying pi-ai source. */
onPayload?: (params: unknown, model: Model<Api>) => unknown | Promise<unknown>;
/** Default thinking level applied when the caller does not pass
* `params.reasoning`. Set this for models whose API requires
diff --git a/src/core-agent/src/sandbox/executor.ts b/src/core-agent/src/sandbox/executor.ts
index c9c5bdad..3303526e 100644
--- a/src/core-agent/src/sandbox/executor.ts
+++ b/src/core-agent/src/sandbox/executor.ts
@@ -81,7 +81,8 @@ export class SandboxExecutor {
this.config = {
timeoutMs: 30_000,
maxOutputBytes: 1024 * 1024, // 1MB
- // Windows 走 cmd.exe(COMSPEC 变量指向);POSIX 走 /bin/sh。
+ // Windows uses cmd.exe (resolved via the COMSPEC env var);
+ // POSIX uses /bin/sh.
shell: process.platform === "win32"
? (process.env.COMSPEC || "cmd.exe")
: "/bin/sh",
diff --git a/src/main/features/agents.ts b/src/main/features/agents.ts
index abe6c0fd..c974f604 100644
--- a/src/main/features/agents.ts
+++ b/src/main/features/agents.ts
@@ -8,7 +8,7 @@
* Schema (one JSON per agent):
* { agent_id, name, description, workflow, created_at, updated_at }
*
- * The inline "编辑" chat lets the LLM refine an agent by emitting one
+ * The inline "edit" chat lets the LLM refine an agent by emitting one
* `<agent>...</agent>` container per turn, whose children are the fields
* to update: `<name>` / `<description>` / `<workflow>` / `<skills>` /
* `<inputs>`. Each child is a full-replacement update for that field.
@@ -58,7 +58,7 @@ export interface AgentInputOption {
* Populated by the agent-edit LLM (or commander quick-create) via the
* `<inputs>` child of the `<agent>` update container; consumed at run
* time by the agent itself per `chat_agent_in_group.md` § inputs_schema
- * 触发的强制确认 (it emits a fenced `agent-input-form` block when fields
+ * mandatory-confirmation trigger (it emits a fenced `agent-input-form` block when fields
* are missing or low-confidence) and by the chat-bubble form widget
* (renderer renders it). */
export interface AgentInput {
@@ -172,8 +172,10 @@ export type AgentRuntime =
custom_args?: string[];
};
-// 头像 token 校验走 catalog 白名单(src/main/data/avatars.json 是单一真相源)。
-// renderer/modules/avatar.js 也从同一份文件拉数据,前后端不再有任何重复。
+// Avatar tokens are validated against the catalog allow-list
+// (src/main/data/avatars.json is the single source of truth).
+// renderer/modules/avatar.js pulls from the same file, so frontend and
+// backend never duplicate it.
import * as avatars from './avatars';
export interface AgentChatMeta { session_id?: string; [k: string]: unknown }
@@ -265,10 +267,11 @@ const INPUT_ID_RE = /^[a-z_][a-z0-9_]{0,31}$/;
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
-// router also keys "commander" as a member id, so we guard the English form
-// too. Comparison is case-insensitive after stripping all whitespace, so
-// " Commander " or "总 指挥" all resolve to the same canonical key.
+// the chat-recipient chip and the sidebar tab (Chinese localizations are
+// "指挥官" and "总指挥" respectively). The bus router also keys "commander"
+// as a member id, so we guard the English form too. Comparison is
+// case-insensitive after stripping all whitespace, so " Commander " or
+// the spaced Chinese form "总 指挥" all resolve to the same canonical key.
const RESERVED_AGENT_NAMES = new Set(['指挥官', '总指挥', 'commander']);
function _agentNameKey(name: string): string {
return String(name || '').replace(/\s+/g, '').toLowerCase();
@@ -287,7 +290,7 @@ function assertAgentNameAllowed(name: string): void {
// Agent names must round-trip through the @-mention regex used by the
// router (`router.ts::TOKEN_CLASS = [A-Za-z0-9_一-鿿-]`) — slashes,
// backslashes, dots, parens, control chars etc. either truncate the
-// match (so `@Agent/Skill搜罗大师` only matches `Agent`) or escape the
+// match (e.g. `@Agent/SkillSomeName` only matches `Agent`) or escape the
// alternation arm at the regex stage. We additionally cap length and
// allow a single internal space so multi-word display names
// ("Code Review Helper") still resolve via the alternation. Leading /
@@ -420,10 +423,14 @@ export function validateAgentInputs(raw: unknown): AgentInput[] {
}
def = b;
} else if (type === 'select') {
- // prompt(chat_agent_in_group.md)明示运行时弹的 form 允许"空表单(不带 default)"。
- // 旧逻辑对缺/非法 default 直接 drop 整个 field,fields 全空 → form 不挂 →
- // raw <agent-input-form> XML 被 markdown 当未知 HTML 渲染 = 用户看到样式崩。
- // 优雅降级:fallback 到 options[0].value(对应浏览器 <select> 默认显示首项的行为)。
+ // The prompt (chat_agent_in_group.md) explicitly allows the runtime
+ // form to render an "empty form" (one without a default selection).
+ // The old logic dropped the whole field on a missing/invalid
+ // default, so all-empty fields → no form rendered → the raw
+ // `<agent-input-form>` XML got rendered by markdown as unknown
+ // HTML, breaking the user's styling. Graceful fallback: use
+ // options[0].value (matching the browser's default-first-option
+ // behavior for `<select>`).
const v = typeof e.default === 'string' ? e.default : '';
if (v && options!.some((o) => o.value === v)) {
def = v;
@@ -1000,8 +1007,9 @@ export async function deleteCustomAgent(agentId: string): Promise<boolean> {
if (!agentId) return false;
const dir = agentDir(getActiveUserId(), agentId);
if (!fs.existsSync(dir)) return false;
- // 一刀切 `agents/<aid>/` 整个目录:agent.json + meta/ + skills/ 都在里面,
- // 不再需要单独 cascade metacognition.purgeAgent / SkillStore.delete。
+ // Wipe the whole `agents/<aid>/` directory in one shot — agent.json,
+ // meta/, and skills/ all live inside it, so we no longer need separate
+ // cascades for metacognition.purgeAgent / SkillStore.delete.
try { await fsp.rm(dir, { recursive: true, force: true }); }
catch (err) { log.warn(`rm failed ${dir}: ${(err as Error).message}`); return false; }
_invalidateAgentListCache();
@@ -1040,8 +1048,9 @@ export async function deleteCustomAgent(agentId: string): Promise<boolean> {
} catch (err) {
log.warn(`cascade chat cleanup failed for ${agentId}: ${(err as Error).message}`);
}
- // Metacognition + evolved skills 已随 `rm -rf agents/<aid>/` 一并删除——
- // meta / skills 子目录就在这棵树里。无需单独 purge。
+ // Metacognition + evolved skills are already wiped by the
+ // `rm -rf agents/<aid>/` above — meta / skills sub-directories live
+ // inside that tree. No separate purge is needed.
log.info(`deleted id=${agentId}`);
return true;
@@ -1055,7 +1064,8 @@ export async function deleteCustomAgent(agentId: string): Promise<boolean> {
// `<description>`, `<workflow>`, `<skills>`, `<inputs>`. One container per
// turn gives us atomic extraction (all fields in or none) and a single
// placeholder to stream-hide. Shared between agent-edit chat and main-chat
-// quick-create; see `chat_agent_setup.md` / `chat_commander.md` § 创建智能体.
+// quick-create; see the "Create agent" section of
+// `chat_agent_setup.md` / `chat_commander.md`.
const AGENT_CONTAINER_RE = /<agent>([\s\S]*?)<\/agent>/g;
const AGENT_CHILD_RE = (tag: string) => new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`);
@@ -1391,8 +1401,8 @@ export async function* streamSendToAgentEditChat(
}
}
// Collapse description / description_zh / description_en into one
- // user-facing progress event — the user sees "简介更新" regardless
- // of which language slot the LLM filled this turn.
+ // user-facing progress event — the user sees "description updated"
+ // regardless of which language slot the LLM filled this turn.
const descTouched = fields.description !== undefined
|| fields.description_zh !== undefined
|| fields.description_en !== undefined;
diff --git a/src/main/features/auth.ts b/src/main/features/auth.ts
index 60795e98..1784bf11 100644
--- a/src/main/features/auth.ts
+++ b/src/main/features/auth.ts
@@ -104,9 +104,11 @@ function piOauth(): Promise<PiOauthModule> {
const { registerMinimaxOAuthProviders } = await import('./oauth-minimax');
await registerMinimaxOAuthProviders();
} catch (err) {
- // 失败不 swallow:把信息同时塞进 log + 缓存里的模块对象,让后续
- // listProviders / startOAuth 都能看到"MiniMax 没注册成功"并给出
- // 明确提示,而不是用户点了 OAuth 才撞到 "does not support OAuth"。
+ // Don't swallow the failure: stash the message into both the log
+ // and the cached module object so subsequent listProviders /
+ // startOAuth calls can surface a clear "MiniMax registration
+ // failed" hint, instead of the user only finding out via the
+ // generic "does not support OAuth" error after clicking OAuth.
const msg = (err as Error)?.message || String(err);
log.warn('failed to register custom OAuth providers:', msg);
_minimaxRegisterError = msg;
@@ -117,7 +119,8 @@ function piOauth(): Promise<PiOauthModule> {
return _oauthPromise;
}
-/** 最近一次 MiniMax 注册失败原因;供 startOAuth 给用户兜底提示。 */
+/** Last MiniMax registration failure reason; used by startOAuth to
+ * surface a fallback hint to the user. */
let _minimaxRegisterError: string | null = null;
/**
@@ -432,7 +435,7 @@ export interface ProviderEntry {
* Renderer shows it as a warning-tinted hint on the card + the add-key
* form so users can verify they have the right kind of account. */
subscriptionNote?: string;
- /** Cosmetic hint — renderer appends a "(推荐 / Recommended)" suffix on the
+ /** Cosmetic hint — renderer appends a "(Recommended)" suffix on the
* picker label. Source of truth is `CatalogEntry.recommended`. */
recommended?: boolean;
profiles: ProfileView[];
@@ -465,10 +468,13 @@ export async function listProviders(): Promise<{ providers: ProviderEntry[] }> {
try { mod = await ca(); } catch (e) {
log.warn('core-agent unavailable for listProviders; falling back to static catalog', { error: (e as Error).message });
}
- // OAuth 能力来源 = pi-ai 运行时注册表。自定义 provider(如 MiniMax
- // Portal)由 `piOauth()` 启动时同步注册完毕;若注册失败会在日志打 warn。
- // `OAUTH_PROVIDERS` 常量只在 pi-ai 整个 oauth 模块加载失败时做兜底,
- // 不做 UNION —— 否则会在 UI 上显示根本无法走通的 OAuth 按钮。
+ // OAuth capability source = pi-ai's runtime registry. Custom
+ // providers (e.g. MiniMax Portal) are registered synchronously by
+ // `piOauth()` at startup; registration failures get a warn-level log.
+ // The `OAUTH_PROVIDERS` constant is only a fallback for the case
+ // where pi-ai's entire oauth module fails to load — we deliberately
+ // do NOT union it in, otherwise the UI would show OAuth buttons that
+ // can never actually work.
let oauthIds: Set<string>;
try {
const oauth = await piOauth();
@@ -485,9 +491,11 @@ export async function listProviders(): Promise<{ providers: ProviderEntry[] }> {
byProvider.set(prof.provider, list);
}
- // OAuth 别名合并:把挂在 OAuth 后端下的 profile 折叠到父级 provider 的卡片
- // 上,这样用户在"MiniMax"卡上通过 OAuth 登录后,拿到的 profile 就展示在
- // 同一张卡片里(而不是突然又冒出一张"MiniMax 订阅 (CN)"卡)。
+ // OAuth alias merge: profiles attached to an OAuth backend get folded
+ // into the parent provider's card, so a user who logs in via OAuth on
+ // the "MiniMax" card sees the resulting profile displayed on the
+ // same card (instead of a surprise extra "MiniMax Subscription (CN)"
+ // card appearing).
for (const [parent, alias] of Object.entries(OAUTH_ALIAS_FOR)) {
const aliasProfiles = byProvider.get(alias);
if (aliasProfiles && aliasProfiles.length) {
@@ -872,9 +880,10 @@ export function openExternalUrl(url: string): { ok: boolean; error?: string } {
const target = String(url || '').trim();
if (!target) return { ok: false, error: 'url required' };
if (!/^https?:\/\//i.test(target)) return { ok: false, error: 'url must be http(s)' };
- // Electron 的 shell.openExternal 是跨平台的官方 API:macOS 走 open(1)、
- // Windows 走 ShellExecuteW、Linux 走 xdg-open —— 替代了以前自己拼 shell
- // 命令(Windows cmd 的 `start "" "url"` 引号嵌套在 exec() 下容易崩)。
+ // Electron's shell.openExternal is the official cross-platform API:
+ // macOS uses open(1), Windows uses ShellExecuteW, Linux uses
+ // xdg-open — supersedes our old hand-rolled shell commands (Windows
+ // cmd's `start "" "url"` quoting was prone to breaking under exec()).
shell.openExternal(target).catch((err: unknown) => {
log.warn('openExternal failed:', (err as Error)?.message || String(err));
});
@@ -921,7 +930,7 @@ export async function startOAuth(
usesCallbackServer,
};
// Auto-open the user's system default browser. If this fails the
- // renderer still shows the URL + 复制链接 button as a fallback.
+ // renderer still shows the URL + "copy link" button as a fallback.
openExternalUrl(info.url);
},
onPrompt: async (prompt) => {
diff --git a/src/main/features/chat_attachments.ts b/src/main/features/chat_attachments.ts
index e2ea0126..16ebd00b 100644
--- a/src/main/features/chat_attachments.ts
+++ b/src/main/features/chat_attachments.ts
@@ -388,7 +388,8 @@ function imageMimeFromExt(ext: string): ImageMimeType {
}
/**
- * Move an entire draft attachment dir (e.g. `main_chat/`, used by 总指挥 tab
+ * Move an entire draft attachment dir (e.g. `main_chat/`, used by the
+ * commander tab
* before a conversation exists) into a freshly-minted `<cid>/`. No caches
* need to follow — cache entries are keyed by absolute path and will simply
* point at the old draft location until next access, at which point
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index 084fae54..124c52c5 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -92,7 +92,7 @@ export async function listConversations(userId: string): Promise<Conversation[]>
// 2. bus is mid-flush — e.g. user clicked abort while a tool was in
// flight; state.json flips to 'aborted' immediately but the worker's
// runTurn still has to unwind (await tool finish → outcome → enqueue
- // the "(已中断)" + processItems message). On-disk status looks
+ // the "(stopped)" + processItems message). On-disk status looks
// terminal but jsonl is still growing. If the renderer reloads in
// this window (Cmd+R right after stop) and we say processing=false,
// it stops polling and never picks up the late abort message — user
diff --git a/src/main/features/component_enabled.ts b/src/main/features/component_enabled.ts
index 91ed1e0d..dd2962b9 100644
--- a/src/main/features/component_enabled.ts
+++ b/src/main/features/component_enabled.ts
@@ -1,10 +1,11 @@
/**
- * 个人启用/禁用配置 — agents + skills 的"用户级开关"。
+ * Per-user enable/disable config — the "user-level toggle" for agents +
+ * skills.
*
- * 落点:`<uid>/cloud/config/component-enabled.json`,与 preferences.json 同目录,
- * 走同一份云同步策略。
+ * Lives at `<uid>/cloud/config/component-enabled.json`, alongside
+ * preferences.json and following the same cloud-sync policy.
*
- * **schema**(v1):
+ * **Schema** (v1):
* ```
* {
* "version": 1,
@@ -13,19 +14,25 @@
* }
* ```
*
- * **存储约定 — 只存 false 覆盖**:
- * - 缺 key = 走 spec 默认值(当前所有 spec 默认 = enabled,所以缺 key = enabled)
- * - 显式 `true` 不会被 setEnabled 写入(写 true 时直接 delete 该 key)
- * - 这样新增组件天然 enabled,不需要迁移;后期 spec 引入 `default_enabled: false`
- * 时同一份 file 立即生效,单 resolver `overrides[id] ?? specDefault ?? true`
+ * **Storage convention — only `false` overrides are stored**:
+ * - Missing key = use the spec default (every spec is currently
+ * `enabled`, so missing key = enabled).
+ * - Explicit `true` is never written by setEnabled (writing `true`
+ * deletes the key instead).
+ * - This way new components are naturally enabled without a
+ * migration; if a future spec ships `default_enabled: false`, the
+ * same file works immediately under the single resolver
+ * `overrides[id] ?? specDefault ?? true`.
*
- * **resolver**(单一函数):
+ * **Resolver** (single function):
* `isEnabled(uid, kind, id, specDefault?) = overrides[kind][id] ?? specDefault ?? true`
*
- * **invalidate 由调用方负责**:本模块只管文件 IO,setAgentEnabled / setSkillEnabled
- * 写完返回,调用 IPC handler 自行触发各自的缓存失效(_invalidateAgentsCache /
- * _invalidateSkillListCache + invalidateCoreAgentSkills)。这样模块边界干净,
- * 不反向 import features/agents.ts / features/skills.ts。
+ * **Invalidation is the caller's responsibility**: this module only
+ * does file IO. setAgentEnabled / setSkillEnabled return after writing,
+ * and the calling IPC handler triggers the relevant cache invalidations
+ * (_invalidateAgentsCache / _invalidateSkillListCache +
+ * invalidateCoreAgentSkills). This keeps module boundaries clean — no
+ * reverse imports of features/agents.ts / features/skills.ts from here.
*/
import * as fs from 'node:fs';
@@ -72,7 +79,7 @@ function sanitiseMap(raw: Record<string, unknown>): Record<string, boolean> {
for (const [k, v] of Object.entries(raw)) {
if (typeof k !== 'string' || !k) continue;
if (typeof v !== 'boolean') continue;
- if (v === true) continue; // 只保留 false 覆盖
+ if (v === true) continue; // only false-overrides are persisted
out[k] = false;
}
return out;
diff --git a/src/main/features/config.ts b/src/main/features/config.ts
index a3e7eaf9..f38b86d6 100644
--- a/src/main/features/config.ts
+++ b/src/main/features/config.ts
@@ -1,14 +1,18 @@
/**
* User preferences bag — `<uid>/cloud/config/preferences.json`.
*
- * 跨设备一致的用户偏好(云同步)。目前仅存 UI 语言(`language: 'zh' | 'en'`)。
+ * Cross-device user preferences (cloud-synced). Currently stores the
+ * UI language only (`language: 'zh' | 'en'`).
*
- * 历史:原 `data/config/config.json` 还存有 legacy `provider` / `model` 字段
- * (`auth.saveConfig` 写入的默认模型对)—— 这份 fallback 已废弃,默认模型由
- * `auth-profiles.json` 的 priority entries 唯一决定(`auth.getConfig()` 读
- * `entries[0]`)。迁移时丢弃这两个字段。
+ * History: the old `data/config/config.json` also held legacy
+ * `provider` / `model` fields (the default model pair written by
+ * `auth.saveConfig`). That fallback is deprecated — the default model
+ * is solely determined by the priority entries in
+ * `auth-profiles.json` (`auth.getConfig()` reads `entries[0]`). The
+ * migration drops those two fields.
*
- * 写入走 merge;key 显式置 undefined 时忽略(等效 no-op)。
+ * Writes merge into the existing file; explicit `undefined` values are
+ * ignored (equivalent to no-op).
*/
import { app } from 'electron';
@@ -31,18 +35,20 @@ export interface CommanderAvatar {
export interface UserPreferences {
language?: Lang;
- /** Per-user 指挥官 avatar (icon id + color id). Tokens come from
+ /** Per-user commander avatar (icon id + color id). Tokens come from
* `renderer/modules/avatar.js`. Missing → renderer falls back to the
* commander default (crown + gold). */
commander_avatar?: CommanderAvatar;
- /** 元认知级别的 agent 自演进开关。undefined / 任意非 false 值 → 视为开启
- * (保留历史默认行为);显式 false → 关闭。env `ORKAS_METACOGNITION='0'`
- * 仍是更高优先级的 kill switch。读取走 `features/metacognition.isFeatureEnabled`. */
+ /** Metacognition-level agent self-evolution toggle. undefined / any
+ * non-false value → treated as enabled (preserving the historical
+ * default); explicit false → disabled. The env var
+ * `ORKAS_METACOGNITION='0'` remains a higher-priority kill switch.
+ * Reads go through `features/metacognition.isFeatureEnabled`. */
metacognition_enabled?: boolean;
[key: string]: unknown;
}
-// 头像 token 校验沿用同一份 catalog(src/main/data/avatars.json)。
+// Avatar tokens reuse the same catalog (src/main/data/avatars.json).
import { isKnownIcon, isKnownColor } from './avatars';
function preferencesFile(): string {
@@ -65,7 +71,8 @@ export function writePreferences(partial: Partial<UserPreferences>): UserPrefere
}
// ── Back-compat aliases for older callers ────────────────────────────────
-// 新代码应使用 read/writePreferences。这些别名给还没迁移完的调用点用。
+// New code should use read/writePreferences directly. These aliases
+// remain for call sites that haven't been migrated yet.
export const readConfig = readPreferences;
export const writeConfig = writePreferences;
export type AppConfig = UserPreferences;
@@ -126,9 +133,10 @@ export function setCommanderAvatar(avatar: CommanderAvatar): CommanderAvatar {
}
// ── Metacognition (self-evolution) toggle ────────────────────────────────
-// 默认 ON:未写过 = undefined → 视为 true,与历史行为一致。
-// 显式 false 才关闭。读取统一走 features/metacognition.isFeatureEnabled,
-// 那里再叠加 env `ORKAS_METACOGNITION='0'` kill switch。
+// Defaults to ON: never-written = undefined → treated as true, matching
+// historical behavior. Only an explicit false disables it. Reads go
+// through features/metacognition.isFeatureEnabled, which additionally
+// layers the env `ORKAS_METACOGNITION='0'` kill switch on top.
export function getMetacognitionEnabled(): boolean {
const v = readPreferences().metacognition_enabled;
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index d31c86cb..91a7eae2 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -77,7 +77,7 @@ export type GroupEvent =
* append a new bubble alongside (turn_end=false). Without this distinction,
* a tool-emitted mid-turn message wrongly consumes commander's placeholder
* and a NEW placeholder gets recreated by post-tool process events, ending
- * up as a stuck "思考中" bubble when commander's turn ends silently. */
+ * up as a stuck "thinking" bubble when commander's turn ends silently. */
| { type: 'message'; cid: string; msg: GroupMessage; turn_end?: boolean }
| { type: 'process'; cid: string; actor: string; data: Record<string, unknown> }
| { type: 'plan_changed'; cid: string }
@@ -143,7 +143,7 @@ interface WorkerState {
pendingPlanAnnouncement?: string;
/** Single-agent dispatches staged by `dispatch_to` mid-turn; flushed via
* `bus.enqueue(forceTo=[X], dispatch:true)` at runTurn end so the recipient
- * worker can't抢跑 — it only wakes after commander's text reply persisted +
+ * worker can't jump the gun — it only wakes after commander's text reply persisted +
* placeholder cleaned. Same staging pattern as pendingPlanAnnouncement +
* deferred planExecutor.reconcile, just for direct dispatches. */
pendingDispatches?: Array<{ to: string; message: string }>;
@@ -231,7 +231,7 @@ export function isQuiescent(uid: string, cid: string): boolean {
/** Recompute the on-disk `status` field based on actual worker / queue
* state. Honors the sticky `aborted` flag — once aborted, ONLY an
* explicit USER `enqueue` clears it (so a follow-up worker reply
- * triggered by the abort itself, like the "(已中断)" message,
+ * triggered by the abort itself, like the "(stopped)" message,
* doesn't surreptitiously revert status to 'idle'). The whole
* read-decide-write is mutex-guarded via `transitionStatus`, so a
* concurrent `setStatus('aborted')` (from `bus.abort`) cannot land
@@ -336,7 +336,7 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
// Reset the sticky `aborted` flag ONLY when the human (user) sends
// a fresh message. Worker-emitted enqueues (commander/agent post-turn
- // replies, including the abort-cleanup "(已中断)") must NOT clear
+ // replies, including the abort-cleanup "(stopped)" message) must NOT clear
// the abort — otherwise a worker's own post-abort message would silently
// un-stick the conversation and the next state_changed would flip back
// to 'idle'/'running'.
@@ -360,7 +360,7 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
to = params.forceTo.slice();
} else {
// Build a global name → id map from the enabled agent registry so the
- // router can resolve `@<人类可读名字>` mentions. Keys are normalized
+ // router can resolve `@<human-readable-name>` mentions. Keys are normalized
// (lowercase + whitespace stripped) to match router's normalization,
// so display names containing spaces ("Writing Helper") or mixed case
// resolve correctly against the user's `@WritingHelper` token.
@@ -484,12 +484,12 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
// Strip ALL `@user` / `@commander` mentions when they're the routed
// recipient — not just leading. The addressee lives in `to`; any literal
// `@<recipient>` in the body is redundant noise. Mid-prose mentions
- // ("好的 @user,关于...") are common LLM filler that users find annoying.
+ // (e.g. "ok @user, about...") are common LLM filler that users find annoying.
// Why ONLY user/commander and not agents: `@<agent>` from commander is
// informational (shows observers which agent got dispatched), so we keep
// those. Agents addressing user/commander gain nothing from the literal.
- // Aliases (`@指挥官` / `@用户`) get the same treatment so Chinese-form
- // mentions don't slip through.
+ // The Chinese aliases (`@指挥官` / `@用户`) get the same treatment so
+ // Chinese-form mentions don't slip through.
const stripTokens = new Set<string>();
for (const r of to) {
if (r === USER_ID) {
@@ -504,8 +504,8 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
// Strip the `@<token>` itself (preserving any preceding separator), then
// run a tidy pass to fix the whitespace/punctuation orphans the strip
// creates. This 2-step keeps prose punctuation around the mention
- // intact: "收到 @user,关于" → "收到,关于" (comma stays), but
- // "好 @user 的" → "好 的" (space-bounded mid-word).
+ // intact: "received @user, about" → "received, about" (comma stays),
+ // but "ok @user end" → "ok end" (space-bounded mid-word).
for (const tok of stripTokens) {
const safeTok = tok.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(
@@ -593,7 +593,8 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
// orchestration role at all — letting it stay asleep keeps the chat
// clean and avoids prompt-driven mistakes (the model second-guessing the
// agent's form / re-dispatching for "polish").
- // Edge case: agent explicitly `@指挥官` to escalate. That message has
+ // Edge case: an agent explicitly mentions the commander to escalate
+ // (e.g. `@commander` / `@指挥官`). That message has
// commander in `to`, so it goes through the regular dispatch loop above.
// User-driven reconcile: when user enqueues, plan_executor needs a chance
@@ -802,7 +803,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// Used as the salvage source when the user aborts mid-stream — the
// event-mapper emits `error` (not `final`) on abort, so without this
// accumulator the partial reply the user already saw rendering would be
- // discarded and we'd persist a bare "(已中断)" placeholder. Same pattern
+ // discarded and we'd persist a bare "(stopped)" placeholder. Same pattern
// as `agents.ts::streamSendToAgentEditChat` (skill / agent edit chats).
let streamingText = '';
let errText: string | null = null;
@@ -831,8 +832,8 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// skill body before executing. Path-sandbox blocks anything outside
// workspace + attachment dir by default, so we have to expose the two
// skill roots here as `extraRoots` (mirrors the skill-edit chat pattern
- // in features/skills.ts). Builtin first to match the prompt's "按来源
- // 定位" guidance.
+ // in features/skills.ts). Builtin first to match the prompt's
+ // "locate by source" guidance.
const skillRoots = [BUILTIN_SKILLS_DIR, userSkillsDir(uid)];
// Same shape for agent directories: chat_commander.md tells the
// commander to `search_files` for an agent.json under
@@ -984,7 +985,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// `final`) when the user hits stop, so `finalText` is empty even though
// `streamingText` holds whatever the renderer was already rendering.
// Push it into finalText so plan_executor's abort branches can preserve
- // it instead of throwing away visible work as a bare "(已中断)" stub.
+ // it instead of throwing away visible work as a bare "(stopped)" stub.
if (!finalText && streamingText) {
finalText = streamingText;
}
@@ -1162,7 +1163,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// Abort post-processing — single source of truth for both "promote silent
// to persist when there's still something visible to keep" AND the
- // "(已中断)" suffix.
+ // "(stopped)" suffix.
//
// plan_executor's abortOutcome can only see partial text + form / created
// agent / produced files; it goes silent for anything else. But process
@@ -1209,7 +1210,8 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// Any placeholder the renderer parked for this actor (e.g. a fresh one
// created by post-tool process events after the original was consumed
// by a mid-turn message) needs an explicit signal to clean up; otherwise
- // a "思考中 + 过程信息" bubble lingers, vanishes only on page refresh.
+ // a "thinking + process info" bubble lingers, vanishing only on
+ // page refresh.
emit(state, { type: 'turn_silent', cid, actor: actor.id });
}
@@ -1232,7 +1234,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
}
// Flush any `dispatch_to` calls staged during commander's turn. Same
- // anti-抢跑 reasoning as the plan reconcile above: recipient workers are
+ // anti-jump-the-gun reasoning as the plan reconcile above: recipient workers are
// only woken after commander's own turn fully settled (text persisted +
// placeholder cleaned), so the user sees commander's reply before any
// dispatched agent's reply. See WorkerState.pendingDispatches.
@@ -1631,7 +1633,7 @@ export async function abort(uid: string, cid: string): Promise<void> {
emit(state, { type: 'state_changed', cid, state: await readState(uid, cid) });
// Wait for every aborted worker's runTurn to finish unwinding (stream
// error → finally → abortOutcome → enqueue). Without this the bus's
- // "(已中断)" + processItems message is still being persisted when
+ // "(stopped)" + processItems message is still being persisted when
// abort() resolves; an external observer (renderer Cmd+R, an automation
// script, a test) that re-reads `<cid>.jsonl` immediately after
// groupChat.abort returns sees a truncated history and never picks up
@@ -2033,7 +2035,8 @@ async function _buildCliPrompt(
tailLines.push('## Your task');
// 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>`
+ // metadata — a `- project_dir: …` style 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:
diff --git a/src/main/features/group_chat/conv_workspace.ts b/src/main/features/group_chat/conv_workspace.ts
index 6c5309a1..d2be45f9 100644
--- a/src/main/features/group_chat/conv_workspace.ts
+++ b/src/main/features/group_chat/conv_workspace.ts
@@ -23,7 +23,8 @@
* navigation (CJK preserved, English lowercased, no opaque cid hex).
*
* Placeholder fallback: when the title is missing / equals the i18n
- * placeholder ("新对话" / "New conversation") / slug-ifies to empty / hits
+ * placeholder (English "New conversation" or its localized form
+ * "新对话") / slug-ifies to empty / hits
* a Windows reserved name, we fall back to `chat-{YYYY-MM-DD}-{N}`. The
* fallback is also frozen on first use, so a write that fired before the
* conv got its real auto-generated title locks in the date-based name —
@@ -44,7 +45,7 @@ const MAX_SLUG_LEN = 32;
// Match the literal default titles `chats.createConversation` writes when
// no title is supplied (currently `t('chat.default_title')` resolved at
-// creation time → '新对话' for zh UI / 'New conversation' for en UI) AND
+// creation time → '新对话' for zh UI, 'New conversation' for en UI) AND
// any historical / capitalization variant. Match by string equality, not
// lang lookup, because state can carry whatever the conv was named at
// creation regardless of the current UI language.
diff --git a/src/main/features/group_chat/index.ts b/src/main/features/group_chat/index.ts
index 03b3def3..10a1ffc3 100644
--- a/src/main/features/group_chat/index.ts
+++ b/src/main/features/group_chat/index.ts
@@ -115,7 +115,8 @@ export async function listMembers(userId: string, cid: string) {
// can decide on its own whether to auto-target the input box at this agent
// when its plan step goes in_progress. Read from the live agent file each
// call (no caching) — agents.ts maintains its own list cache so the read
- // is cheap, and "interactive 跟随 agent 当前配置" is the contract.
+ // is cheap, and "interactive follows the agent's current spec" is the
+ // contract.
const agentsFeat = await import('../agents');
const enriched = await Promise.all(m.actors.map(async (a) => {
if (a.kind !== 'agent') return a;
diff --git a/src/main/features/group_chat/plan.ts b/src/main/features/group_chat/plan.ts
index e2489212..27823f31 100644
--- a/src/main/features/group_chat/plan.ts
+++ b/src/main/features/group_chat/plan.ts
@@ -46,7 +46,8 @@ export interface PlanStep {
/** Human-readable; what the user will see in the UI plan panel. */
title: string;
/** Required. Resolves to: 'user' / 'commander' / agent name (or id).
- * Empty = invalid. Aliases: '指挥官' → commander, '用户' → user. */
+ * Empty = invalid. Aliases: the Chinese forms '指挥官' → commander
+ * and '用户' → user are also accepted. */
assignee: string;
/** Dispatch payload template. Bus renders this and sends it as the message
* body when this step fires. Variables: `{{user_initial_message}}` and
diff --git a/src/main/features/group_chat/plan_executor.ts b/src/main/features/group_chat/plan_executor.ts
index 6e3f29ba..0b4c8e5b 100644
--- a/src/main/features/group_chat/plan_executor.ts
+++ b/src/main/features/group_chat/plan_executor.ts
@@ -380,7 +380,7 @@ async function applyPlanStepTurn(
// the partial reply bus accumulated from delta events); if there's nothing
// to salvage AND no side effect, go silent so the renderer's turn_silent
// handler can either freeze the process rail as a "thinking trail" bubble
- // or remove the placeholder entirely. Avoids the orphan "(已中断)" bubble
+ // or remove the placeholder entirely. Avoids the orphan "(stopped)" bubble
// for turns that aborted before producing anything visible.
if (evt.aborted) {
await transitionStepFailed(uid, cid, step, 'aborted by user', '');
@@ -515,7 +515,7 @@ function errorBubble(msg: string): string {
}
/** Outcome for an aborted turn. Returns the salvageable content (partial
- * streamed reply + any user-visible side effects), with NO "(已中断)"
+ * streamed reply + any user-visible side effects), with NO "(stopped)"
* suffix — bus appends that once, after merging in any staged plan
* announcement, so the marker always lands at the end regardless of which
* pieces survived.
@@ -523,7 +523,7 @@ function errorBubble(msg: string): string {
* No salvageable content AND no side effect → silent. The renderer's
* `turn_silent` handler then either freezes the process rail (tool calls
* etc.) as a thinking-trail bubble or removes the placeholder entirely.
- * Skipping the persist here is what prevents the orphan "(已中断)" bubble
+ * Skipping the persist here is what prevents the orphan "(stopped)" bubble
* for turns that aborted before producing anything visible.
*/
function abortOutcome(evt: TurnFinishedEvent): TurnOutcome {
diff --git a/src/main/features/group_chat/router.ts b/src/main/features/group_chat/router.ts
index 829a053a..163d68c0 100644
--- a/src/main/features/group_chat/router.ts
+++ b/src/main/features/group_chat/router.ts
@@ -15,7 +15,8 @@ import { safeId } from '../../storage';
// ── Mention parsing ──────────────────────────────────────────────────────
// `@token` where token is `[A-Za-z0-9_一-鿿-]+` — ASCII word chars
-// plus CJK Unified Ideographs so users can `@张三` an agent by name. Token
+// plus CJK Unified Ideographs so users can mention agents whose display
+// names use CJK characters. Token
// boundaries:
// - leading: start-of-string or any non-token char
// - trailing: matched greedily up to the first non-token char
@@ -48,17 +49,22 @@ function _buildMentionRe(names?: readonly string[]): RegExp {
/** Scan a message body for `@token` mentions. Deduped, in first-occurrence
* order.
*
- * `fromKind` 决定是否把 `@` 当 dispatch 信号:
- * - `'user'` (或 undefined,向后兼容) — 走完整扫描;真人用户敲 `@A` 是真心要找 A
- * - `'commander'` / `'agent'` — 直接返回 `[]`;LLM 散文里 `**@A**` `@A / @B`
- * 这类是训练数据带来的 markdown 装饰习惯,系统不识别为派活信号。LLM 派活
- * 的唯一通道是 `dispatch_to` (单 agent) 或 `plan_set` (多 actor) 工具。
- * 详见 docs/plans/dispatch-via-tool-call.md 与 CLAUDE.md §5。
+ * `fromKind` decides whether `@` counts as a dispatch signal:
+ * - `'user'` (or undefined, for back-compat) — full scan; a real
+ * user typing `@A` actually means "send to A".
+ * - `'commander'` / `'agent'` — return `[]` immediately; LLM prose
+ * like `**@A**` or `@A / @B` is training-data markdown decoration,
+ * not a dispatch signal. The only LLM-side dispatch channels are
+ * the `dispatch_to` (single agent) and `plan_set` (multi-actor)
+ * tools.
+ * See docs/plans/dispatch-via-tool-call.md and CLAUDE.md §5.
*
- * `names` 启用多词名字精确匹配:用户敲 "@Software Requirements Analyst" 这种
- * 带空格的显示名,fallback 字符类只能截到 "@Software"(白名单不含空格);names
- * 里有该 agent 名时 alternation 会一次匹完整段。caller 应传入 roster +
- * registry 的所有 agent name(原文,大小写敏感保留)。
+ * `names` enables exact multi-word name matching: when a user types
+ * "@Software Requirements Analyst", the fallback char class only
+ * captures "@Software" (the allow-list excludes spaces); when that
+ * agent name is in `names`, the alternation matches the full segment
+ * in one shot. Callers should pass every roster + registry agent name
+ * as-is (case-sensitive preserved).
*/
export function parseMentions(
text: string,
@@ -153,7 +159,8 @@ export interface ResolveOpts {
*/
/** Normalize a token / agent name for lookup: lowercase + strip all
* whitespace. The mention-regex already disallows whitespace inside tokens
- * (so the user can never type `@张 三`); the lowercase + strip pair makes
+ * (so users can never type a mention with internal whitespace); the
+ * lowercase + strip pair makes
* match keys robust to display names that contain spaces ("Writing Helper"
* → "writinghelper") and to Latin-script case differences. */
function _normalizeNameKey(s: string): string {
@@ -163,15 +170,17 @@ function _normalizeNameKey(s: string): string {
export function resolveRecipients(opts: ResolveOpts): RouteResolution {
// Build the name list for the mention parser — roster agents + registry
// display names + reserved aliases. Without this, multi-word names get
- // truncated at the first whitespace by the fallback regex (see日志:
- // user typed "@Socratic Learning Coach 运行" and got `mentions: ['Socratic']`
+ // truncated at the first whitespace by the fallback regex (observed
+ // in logs: a user typed something like
+ // "@Socratic Learning Coach <imperative>" and got `mentions: ['Socratic']`
// → unknown_token → fell back to commander default routing).
const namesForParser: string[] = [];
for (const m of opts.members) {
if (m.kind === 'agent' && m.name) namesForParser.push(m.name);
}
if (opts.agentDisplayNames) namesForParser.push(...opts.agentDisplayNames);
- // Reserved-actor aliases — let `@指挥官` / `@用户` route too. Cheap (4 strings).
+ // Reserved-actor aliases — also accept the Chinese forms
+ // (`@指挥官` / `@用户`). Cheap (4 strings).
namesForParser.push('指挥官', '用户', 'commander', 'user');
const tokens = parseMentions(opts.text, { fromKind: opts.fromKind, names: namesForParser });
const memberIds = new Set(opts.members.map((m) => m.id));
@@ -222,7 +231,8 @@ export function resolveRecipients(opts: ResolveOpts): RouteResolution {
// - commander → user (its replies are user-facing summaries)
// - agent → user (default surface output to the human; agents only
// reach commander via an explicit `@<commander-name>` mention)
- // See `chat_agent_in_group.md` § 群聊机制 + `chat_commander.md`.
+ // See the "Group-chat mechanics" section of `chat_agent_in_group.md`
+ // and `chat_commander.md`.
let def: string;
if (opts.fromKind === 'user') def = COMMANDER_ID;
else def = USER_ID;
diff --git a/src/main/features/image_auth.ts b/src/main/features/image_auth.ts
index 349ae3ad..f2fbd432 100644
--- a/src/main/features/image_auth.ts
+++ b/src/main/features/image_auth.ts
@@ -100,7 +100,7 @@ export interface TestImageProfileResult {
/**
* Connectivity probe — sends a minimal generation request to the picked
* provider's image API. Costs ≈ one cheap image. Caller should only invoke
- * on explicit user action (e.g. "测试" button), not on every save.
+ * on explicit user action (e.g. a "test" button), not on every save.
*/
export async function testImageProfile(id: string): Promise<TestImageProfileResult> {
const list = loadImageProfiles();
diff --git a/src/main/features/image_gen.ts b/src/main/features/image_gen.ts
index 6d43d490..0477f9ac 100644
--- a/src/main/features/image_gen.ts
+++ b/src/main/features/image_gen.ts
@@ -42,8 +42,9 @@ export interface PickedImageGenProfile {
* image generation call.
*
* Priority:
- * 1. The user's dedicated `imageProfiles` list (from settings → 图片生成
- * API Key 卡片). First entry whose provider has a capability wins.
+ * 1. The user's dedicated `imageProfiles` list (from the "Image
+ * Generation API Key" card in settings). First entry whose
+ * provider has a capability wins.
* Multiple entries on the same provider just shadow each other —
* first wins, no rotation (image gen calls are rare; rotation isn't
* worth the surprise factor).
@@ -343,22 +344,31 @@ export async function callGeminiImage(req: AdapterRequest): Promise<AdapterResul
}
/**
- * 火山方舟(豆包) Seedream 文生图 + 图生图(4.5+)。
- * Endpoint: POST /api/v3/images/generations,OpenAI 兼容请求体。
- * 返回 `{ data: [{ url: "..." }] }` 形式(默认)或可请求 base64;
- * 一期走 url 模式,再二次 fetch 取 bytes(避免账户级 base64 配额限制)。
+ * Volcengine Ark (Doubao) Seedream text-to-image + image-to-image (4.5+).
+ * Endpoint: POST /api/v3/images/generations, OpenAI-compatible request body.
+ * Returns `{ data: [{ url: "..." }] }` by default (base64 also available
+ * on request); we use the URL mode and re-fetch the bytes ourselves so
+ * we don't bump into account-level base64 quotas.
*
- * 图生图:在请求体加 `image: string | string[]`,每项是公网 HTTPS URL
- * 或 data URI(`data:<mime>;base64,<b64>`)。本地参考图统一编 data URI。
- * 参考图 + 输出图总数 ≤ 15,工具层另行限到 4 张参考。
+ * Image-to-image: add `image: string | string[]` to the body; each entry
+ * is either a public HTTPS URL or a data URI
+ * (`data:<mime>;base64,<b64>`). Local reference images are encoded as
+ * data URIs uniformly.
+ * Reference images + outputs total ≤ 15; the tool layer additionally
+ * caps references to 4.
*
- * Size 注意:Seedream 4.5 的 `size` 不像 OpenAI 接受任意 `WxH`——必须满足
- * 1. 像素 ≥ 3,686,400 (≈ 1920×1920)
- * 2. 形式是 `WIDTHxHEIGHT` 或关键字 `1k` / `2k` / `4k`
- * 调用方默认传 `1024x1024`(OpenAI 风格),低于 Seedream 下限。这里做一层
- * 翻译:像素不足时升到 `2k`;已经够大或本来就是关键字的原样透传。
- * 图生图模式下若调用方没显式给非默认 size,传 `adaptive` 让模型按参考图
- * 比例决定,避免硬塞 2k 跟参考图比例冲突。
+ * Size note: Seedream 4.5's `size` does NOT accept arbitrary `WxH` like
+ * OpenAI — the value must satisfy both:
+ * 1. Pixels ≥ 3,686,400 (≈ 1920×1920).
+ * 2. Form must be `WIDTHxHEIGHT` or one of the keywords
+ * `1k` / `2k` / `4k`.
+ * Callers default to `1024x1024` (OpenAI-style), which is under
+ * Seedream's lower bound, so we translate here: bump to `2k` when below
+ * the pixel floor; pass through anything already large enough or
+ * already a keyword. In image-to-image mode, when the caller hasn't
+ * explicitly set a non-default size, we pass `adaptive` so the model
+ * picks dimensions from the reference image, avoiding aspect-ratio
+ * conflicts when forcing 2k.
*/
const SEEDREAM_MIN_PIXELS = 3_686_400;
const SEEDREAM_DEFAULT_SIZE = '1024x1024';
diff --git a/src/main/features/oauth-minimax.ts b/src/main/features/oauth-minimax.ts
index cbf9b938..25c56bf6 100644
--- a/src/main/features/oauth-minimax.ts
+++ b/src/main/features/oauth-minimax.ts
@@ -367,10 +367,13 @@ export function buildMinimaxPortalProvider(region: MiniMaxRegion): OAuthProvider
* Register both region variants with pi-ai. Idempotent — safe to call
* multiple times (pi-ai's registry uses id as key).
*
- * **Registry 一致性**:pi-ai 是 ESM-only 的 package,但 Orkas 主进程经
- * `tsx/cjs` 运行态转译;早先遇到过"register 能调通、`getOAuthProvider`
- * 取回 undefined"的诡异行为(可能的 ESM/CJS interop 导致两份 registry
- * 实例)。这里注册完立即读一次做自验证,若不一致立刻抛错便于定位。
+ * **Registry consistency**: pi-ai is an ESM-only package, but the
+ * Orkas main process is transpiled at runtime via `tsx/cjs`. We've
+ * previously hit weird behavior where `register` succeeded yet
+ * `getOAuthProvider` returned undefined (likely an ESM/CJS interop
+ * issue producing two registry instances). After registering, we
+ * immediately read back to self-verify and throw on mismatch so the
+ * cause is locatable.
*/
export async function registerMinimaxOAuthProviders(): Promise<void> {
const oauth = await import('@mariozechner/pi-ai/oauth');
diff --git a/src/main/features/reflection-trigger.ts b/src/main/features/reflection-trigger.ts
index 67767814..5ab7ef13 100644
--- a/src/main/features/reflection-trigger.ts
+++ b/src/main/features/reflection-trigger.ts
@@ -153,9 +153,12 @@ async function realReflectForAgent(uid: string, agentId: string, sinceMs: number
// `runReflection` swallows provider/LLM/loop-exhaustion errors and returns
// `''` instead of throwing (see core-agent runner.ts: line 687/745/749).
- // 空串 = 实际什么都没跑成功,不应消耗 48h 冷却。LLM 真的判断"无需改动"
- // 也会回至少一句话的解释(非空),所以 trim 后空白视作失败。具体失败原因
- // 在 core-agent 日志里(log.error / log.warn 都打了),这里抛 generic 错。
+ // Empty string = nothing actually succeeded, so it must not burn the
+ // 48h cooldown. Even when the LLM concludes "no change needed", it
+ // returns at least one sentence of explanation (non-empty), so a
+ // post-trim blank is treated as failure. The specific failure reason
+ // is in the core-agent logs (log.error / log.warn both fire); we
+ // throw a generic error here.
const responseText = await runner.runReflection(prompt);
if (!responseText || !responseText.trim()) {
throw new Error('reflection returned empty (provider/LLM error or max loops; see core-agent log)');
diff --git a/src/main/features/users.ts b/src/main/features/users.ts
index 670c14ca..1b03c032 100644
--- a/src/main/features/users.ts
+++ b/src/main/features/users.ts
@@ -1,16 +1,22 @@
/**
- * 本机用户注册表 + 活跃 uid 生命周期。
+ * Local-machine user registry + active uid lifecycle.
*
- * `data/users.json` 存 `{ current_user_id, users: [{user_id, created_at}, ...] }`,
- * 是唯一的顶层本机元数据。所有 uid 私域数据都在 `data/<uid>/{cloud,local}/` 下
- * (见 paths.ts)。
+ * `data/users.json` holds
+ * `{ current_user_id, users: [{user_id, created_at}, ...] }` — the sole
+ * top-level local metadata. All per-uid private data lives under
+ * `data/<uid>/{cloud,local}/` (see paths.ts).
*
- * 启动流程:
- * 1. 读 users.json;不存在 → 创建首个 uid(`genUserId`),current_user_id 指向它
- * 2. `activateUser(uid)` 建 uid 子目录骨架 + pin CORE_AGENT_AUTH_DIR + 清相关缓存
- * 3. 之后所有 feature 调用用 `getActiveUserId()` 拿当前 uid
+ * Boot sequence:
+ * 1. Read users.json; if absent, create the first uid (`genUserId`)
+ * and point current_user_id at it.
+ * 2. `activateUser(uid)` mkdir's the uid sub-tree, pins
+ * CORE_AGENT_AUTH_DIR, and clears the relevant caches.
+ * 3. From there, every feature uses `getActiveUserId()` to obtain the
+ * current uid.
*
- * 本期仅支持单活跃 uid(UI 级切换下期另起 plan)。但注册表结构已预留多 uid 场景。
+ * Currently only one uid is active at a time (a UI-level switcher is
+ * planned for a later iteration). The registry shape already
+ * accommodates multi-uid scenarios.
*/
import * as fs from 'node:fs';
@@ -86,13 +92,16 @@ function writeRegistry(reg: UsersRegistry): void {
/**
* Activate `uid` as the live user for this process:
- * - mkdir 完整的 `<uid>/{cloud,local}/*` 骨架
- * - 把 `CORE_AGENT_AUTH_DIR` 指向 `<uid>/local/config/`(core-agent 的
- * `resolveAuthDir()` 每次调用读 env,运行时切换安全)
- * - 清相关模块的内存缓存(session-store、auth、config)
- * - 把 `current_user_id` 写回 users.json
+ * - mkdir the full `<uid>/{cloud,local}/*` skeleton.
+ * - Point `CORE_AGENT_AUTH_DIR` at `<uid>/local/config/`. core-agent's
+ * `resolveAuthDir()` reads the env var on every call, so runtime
+ * switching is safe.
+ * - Clear the relevant module-level caches (session-store, auth,
+ * config).
+ * - Write `current_user_id` back to users.json.
*
- * 调用方通常是 `boot` 与(下一期的)UI 切换入口。
+ * Callers are typically `boot` and (in a future iteration) the UI
+ * switcher.
*/
export function activateUser(uid: string): void {
if (!safeId(uid)) throw new Error(`invalid user id: ${String(uid)}`);
@@ -109,14 +118,16 @@ export function activateUser(uid: string): void {
try { sweepToolResults(userToolResultsDir(uid), 7); }
catch (err) { log.warn(`sweepToolResults uid=${uid}: ${(err as Error).message}`); }
- // 历史 session_id 上的品牌前缀一次性剥掉。idempotent:盖章后再
- // 启动直接 no-op。详见 util/migrate-session-ids.ts。
+ // Strip legacy session_id brand prefixes once.
+ // Idempotent: after the stamp lands, subsequent startups are no-ops.
+ // See util/migrate-session-ids.ts for details.
try { migrateLegacySessionIds(uid); }
catch (err) { log.warn(`migrateLegacySessionIds uid=${uid}: ${(err as Error).message}`); }
- // Agent 布局迁移:`agents/<aid>.json` → `agents/<aid>/agent.json`,
- // `meta/<aid>/*` → `agents/<aid>/meta/*`。同样 idempotent + 盖章。
- // 详见 util/migrate-agent-layout.ts + docs/plans/agent-as-directory.md。
+ // Agent layout migration: `agents/<aid>.json` →
+ // `agents/<aid>/agent.json`, and `meta/<aid>/*` →
+ // `agents/<aid>/meta/*`. Likewise idempotent + stamped. See
+ // util/migrate-agent-layout.ts + docs/plans/agent-as-directory.md.
try { migrateAgentLayout(uid); }
catch (err) { log.warn(`migrateAgentLayout uid=${uid}: ${(err as Error).message}`); }
diff --git a/src/main/index.ts b/src/main/index.ts
index 54ffab8d..35237cd3 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -13,10 +13,11 @@
* 4. Create BrowserWindow loading renderer/index.html.
* 5. IPC handlers serve invoke + stream calls from the renderer.
*
- * 文件位置:`PC/src/main/index.ts`。`bootstrap.cjs` 的
- * `require('./src/main')` 会自动解析到这里(Node 的 folder → index 解析规则)。
- * `__dirname` 指向 `PC/src/main/`,跨层引用 renderer / builtin / resources
- * 时统一经过 `paths.SRC_ROOT` 换算,不要再对 `__dirname` 拼。
+ * File location: `PC/src/main/index.ts`. `bootstrap.cjs`'s
+ * `require('./src/main')` resolves here automatically via Node's
+ * folder → index resolution rule. `__dirname` points at `PC/src/main/`;
+ * cross-tree references to renderer / builtin / resources go through
+ * `paths.SRC_ROOT` — never splice `__dirname` directly.
*/
import * as path from 'node:path';
@@ -54,10 +55,12 @@ protocol.registerSchemesAsPrivileged([
},
]);
-// Packaged 模式 WS_ROOT 重定向(`~/.orkas/data` 或 Windows 容器盘)已经在
-// `bootstrap.cjs` 完成,**必须**那时做 —— TypeScript 的 import 提升会把
-// `paths.ts` 的 require 提到这块代码之前,放到这里设置 env 已来不及。
-// 详细选盘规则见 `packaged-data-root.cjs`,被 `bootstrap.cjs` 直接 require。
+// Packaged-mode WS_ROOT redirect (`~/.orkas/data` or a Windows container
+// drive) is already done in `bootstrap.cjs`, and **must** happen there —
+// TypeScript's import hoisting would pull `paths.ts`'s require ahead of
+// any env-setting block here, so doing it later is too late. Drive
+// selection rules live in `packaged-data-root.cjs`, required directly by
+// `bootstrap.cjs`.
import * as paths from './paths';
// `CORE_AGENT_AUTH_DIR` is pinned per-uid by `features/users.activateUser()`
@@ -109,7 +112,7 @@ function createWindow(): BrowserWindow {
backgroundColor: '#ffffff',
icon: path.join(paths.SRC_ROOT, 'resources', 'icons', 'icon.png'),
webPreferences: {
- // preload 和 index.ts 同在 PC/src/main/ 下 —— 直接 __dirname + 'preload.js'
+ // preload sits next to index.ts in PC/src/main/ — just __dirname + 'preload.js'.
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
@@ -129,11 +132,13 @@ function createWindow(): BrowserWindow {
// frame-only look (drag works, but no label across the top).
win.on('page-title-updated', (e) => e.preventDefault());
- // 对话气泡 / 知识库 / 设置页里的外链,一律交给系统默认浏览器打开 ——
- // - `target="_blank"` / `window.open()` 走 setWindowOpenHandler
- // - 无 target 的 `<a href>` 点击 走 will-navigate(否则 Electron 会
- // 把当前窗口整个导航走,把应用界面替换掉)
- // 非 http(s) 一律拒绝(`file://` 初始加载走 loadFile,不触发这里)。
+ // External links in chat bubbles / knowledge base / settings always open
+ // in the system default browser:
+ // - `target="_blank"` / `window.open()` → setWindowOpenHandler
+ // - `<a href>` clicks without a target → will-navigate (otherwise
+ // Electron navigates the current window away and replaces the UI).
+ // Non-http(s) is always rejected (`file://` only fires through the
+ // initial loadFile, which doesn't reach this handler).
const openIfExternal = (raw: string): boolean => {
const url = String(raw || '').trim();
if (!/^https?:\/\//i.test(url)) return false;
@@ -150,11 +155,11 @@ function createWindow(): BrowserWindow {
if (openIfExternal(url)) event.preventDefault();
});
- // 统一接管 Cmd/Ctrl+R / F5:
- // - 打包后:禁止刷新(App 不需要重载)
- // - dev:强制走 reloadIgnoringCache —— 这样改了 renderer/*.css 或 *.js
- // 后 Cmd+R 直接拿到新版本,renderer 里的 `?v=` cache-busting 后缀
- // 就不再需要人工 bump。
+ // Hijack Cmd/Ctrl+R / F5 uniformly:
+ // - Packaged: refresh disabled (the App doesn't need reload).
+ // - Dev: force reloadIgnoringCache so that after editing
+ // renderer/*.css or *.js, Cmd+R picks up the new version directly —
+ // no need to hand-bump the `?v=` cache-busting suffix in renderer.
win.webContents.on('before-input-event', (event, input) => {
if (input.type !== 'keyDown') return;
if (input.shift) return;
@@ -478,17 +483,21 @@ if (!gotLock) {
} else {
app.whenReady().then(async () => {
await runBootSelfCheck();
- // Dev 态 dock 图标:打包后 macOS 走 .icns(Info.plist),dev 态运行的是
- // Electron.app 自带 Info.plist,必须运行时 setIcon 才能看到自家 logo。
- // Windows 任务栏直接吃 BrowserWindow.icon,不用这条;Linux 同理。
+ // Dev-mode dock icon: packaged macOS picks up .icns from Info.plist,
+ // but dev runs the bundled Electron.app's own Info.plist — we must
+ // setIcon at runtime to see our logo. The Windows taskbar reads
+ // BrowserWindow.icon directly so this branch isn't needed there
+ // (same on Linux).
if (process.platform === 'darwin' && app.dock) {
const iconPath = path.join(paths.SRC_ROOT, 'resources', 'icons', 'icon.png');
const img = nativeImage.createFromPath(iconPath);
if (!img.isEmpty()) app.dock.setIcon(img);
}
- // Windows 任务栏:Electron dev 进程默认归到 electron.exe 的 AppUserModelID,
- // 任务栏会按那个 ID 取图标 → 显示成 Electron 默认 logo。手动设成自家 ID
- // 后,Windows 就改用 BrowserWindow.icon。打包态 NSIS 也会写入同一 ID。
+ // Windows taskbar: by default the Electron dev process inherits
+ // electron.exe's AppUserModelID, and the taskbar uses that ID to look
+ // up the icon → it ends up showing the default Electron logo. Setting
+ // our own ID here makes Windows fall back to BrowserWindow.icon.
+ // Packaged NSIS writes the same ID.
if (process.platform === 'win32') {
app.setAppUserModelId('com.orkas.desktop');
}
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 1af6cd58..fa92c88d 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -414,7 +414,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return contexts.openContextFileInSystem(path || '');
},
- // ── Knowledge base (向量库) ──
+ // ── Knowledge base (vector store) ──
// Snapshot of what's in `kb_files`: status summary + per-file rows.
// Renderer subscribes to the `kb.events` stream (below) for incremental
// updates; this endpoint is the initial-load / full-refresh fetch.
@@ -440,8 +440,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { result: r };
},
- // Re-enqueue a single file (typically the UI's "重新处理" button after a
- // failed extraction).
+ // Re-enqueue a single file (typically the UI's "reprocess" button after
+ // a failed extraction).
'kb.reprocess': async ({ path }, ctx) => {
if (typeof path !== 'string' || !path) throw new Error('path required');
kbIndexer.enqueue(ctx.userId, path, 'upsert');
@@ -464,20 +464,24 @@ const invokeHandlers: Record<string, InvokeHandler> = {
},
'config.getLocales': async () => ({ tables: getRendererTables() }),
- // 头像 catalog(图标 + 颜色 + 指挥官默认)—— 单一真相源在
- // src/main/data/avatars.json。renderer 启动时拉一次,自此用本地缓存。
+ // Avatar catalog (icons + colors + commander default) — single source of
+ // truth lives in src/main/data/avatars.json. The renderer fetches once at
+ // startup, then uses its local cache.
'avatars.getCatalog': async () => ({ catalog: avatars.getCatalog() }),
- // 指挥官头像偏好(云同步)。avatar = { icon, color },token 走 catalog
- // 白名单校验;缺省时 renderer 用 commander 默认(crown + gold)兜底。
+ // Commander avatar preference (cloud-synced). avatar = { icon, color };
+ // tokens are validated against the catalog allow-list. When absent the
+ // renderer falls back to the commander default (crown + gold).
'prefs.getCommanderAvatar': async () => ({ avatar: appConfig.getCommanderAvatar() }),
'prefs.setCommanderAvatar': async ({ icon, color }) => {
return { avatar: appConfig.setCommanderAvatar({ icon, color }) };
},
- // 元认知级别的 agent 自演进开关。落 preferences.json::metacognition_enabled,
- // 真正的 gate 单点真相在 features/metacognition.isFeatureEnabled(叠加 env
- // kill switch)。env `ORKAS_METACOGNITION='0'` 永远压过 UI 设置。
+ // Metacognition-level agent self-evolution toggle. Stored at
+ // preferences.json::metacognition_enabled; the actual gate's single
+ // source of truth is features/metacognition.isFeatureEnabled (with the
+ // env kill switch on top). The env var `ORKAS_METACOGNITION='0'` always
+ // overrides the UI setting.
'prefs.getMetacognition': async () => ({
enabled: appConfig.getMetacognitionEnabled(),
envForcedOff: process.env.ORKAS_METACOGNITION === '0',
diff --git a/src/main/locales/en.json b/src/main/locales/en.json
index 92fee773..4a2f0683 100644
--- a/src/main/locales/en.json
+++ b/src/main/locales/en.json
@@ -101,5 +101,7 @@
"skills.import_block.system_dir": "System directory",
"skills.import_block.credentials_dir": "User credentials directory",
"oauth.minimax.unparseable_response": "MiniMax OAuth response could not be parsed",
- "oauth.minimax.register_error_hint": " (MiniMax OAuth registration error: {message})"
+ "oauth.minimax.register_error_hint": " (MiniMax OAuth registration error: {message})",
+ "provider.moonshot.note_paygo": "Pay-as-you-go open-platform API key — billed separately from the Kimi Coding Plan subscription; the two keys are not interchangeable",
+ "provider.kimi_coding.note_subscription": "Kimi Coding Plan monthly subscription only — uses the Anthropic-protocol endpoint, separate from the pay-as-you-go Moonshot API key"
}
diff --git a/src/main/locales/zh.json b/src/main/locales/zh.json
index 058ec598..d30d58ee 100644
--- a/src/main/locales/zh.json
+++ b/src/main/locales/zh.json
@@ -101,5 +101,7 @@
"skills.import_block.system_dir": "系统目录",
"skills.import_block.credentials_dir": "用户凭证目录",
"oauth.minimax.unparseable_response": "MiniMax OAuth 响应无法解析",
- "oauth.minimax.register_error_hint": "(MiniMax OAuth 注册时报错:{message})"
+ "oauth.minimax.register_error_hint": "(MiniMax OAuth 注册时报错:{message})",
+ "provider.moonshot.note_paygo": "按量付费开放平台 API key,与 Kimi Coding Plan 月付订阅独立计费、不通用",
+ "provider.kimi_coding.note_subscription": "Kimi Coding Plan 月付订阅专用,走 Anthropic 协议端点,与 Moonshot 按量付费 API key 独立"
}
diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.ts
index 4008aada..7542fc09 100644
--- a/src/main/model/core-agent/client.ts
+++ b/src/main/model/core-agent/client.ts
@@ -134,7 +134,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
// implementations (observed with pi-ai's WebSocket/SSE transports) don't
// respond to `signal.aborted` promptly, so the `await iter.next()` stays
// parked and the generator's `finally` never runs — which would leave the
- // session lock permanently held and the next turn stuck in "思考中". Since
+ // session lock permanently held and the next turn stuck in "thinking". Since
// `releaseXxxOnce` is idempotent, the `finally` block calling it again
// is a no-op.
const controller = new AbortController();
@@ -251,7 +251,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
// mid-tool-execution. Without this, the next turn would reuse a
// memory-resident session whose last assistant message has an
// unmatched tool_use — provider APIs silently hang on that shape,
- // which surfaces as "思考中" that never ends. Heal is idempotent and
+ // which surfaces as a "thinking" state that never ends. Heal is idempotent and
// a no-op on healthy sessions, so running it unconditionally every
// turn is safe.
try {
diff --git a/src/main/model/core-agent/event-mapper.ts b/src/main/model/core-agent/event-mapper.ts
index af37fbe0..4dbe1ceb 100644
--- a/src/main/model/core-agent/event-mapper.ts
+++ b/src/main/model/core-agent/event-mapper.ts
@@ -10,9 +10,10 @@
* + a {type:'progress'} line so the UI's log shows it even if
* the process panel filters events
* tool_end → {type:'event', event:{stream:'tool', data:{phase:'end', id, name, isError, result_preview}}}
- * retry → {type:'progress', text: '正在重试·<friendly reason>'} — raw
- * reason (e.g. undici "terminated", "fetch failed", "ECONNRESET")
- * is mapped to user-facing Chinese via `friendlyRetryReason`
+ * retry → {type:'progress', text: 'retrying · <friendly reason>'} —
+ * the raw reason (e.g. undici "terminated", "fetch failed",
+ * "ECONNRESET") is mapped to a user-facing string via
+ * `friendlyRetryReason`
* compaction → {type:'progress', text: 'compacted <before>→<after> tokens'}
* done (ok) → {type:'final', text} then {type:'done'}
* done (err) → {type:'error', text: meta.error.message} then {type:'done'}
@@ -71,12 +72,13 @@ function inputSummary(name: string, input: unknown, max = 80): string {
/**
* Translate a raw retry reason (usually `err.message` from core-agent) into
- * a short Chinese phrase the user can actually read. The raw strings come
- * from undici / pi-ai / provider SDKs and are English / code-like; the
- * process panel is user-facing so we map the common families here.
+ * a short user-facing phrase. The raw strings come from undici / pi-ai /
+ * provider SDKs and are English / code-like; the process panel is
+ * user-facing so we map the common families here. The actual user-visible
+ * string is resolved via i18n (`t()`).
*
- * Unknown reasons fall back to a generic "网络异常" — the full message is
- * still in `data/logs/` for debugging.
+ * Unknown reasons fall back to a generic "network error" — the full
+ * message is still in `data/logs/` for debugging.
*/
export function friendlyRetryReason(reason: string): string {
const r = (reason || '').toLowerCase();
diff --git a/src/main/model/core-agent/external-providers.ts b/src/main/model/core-agent/external-providers.ts
index 616f74c7..9b769ccf 100644
--- a/src/main/model/core-agent/external-providers.ts
+++ b/src/main/model/core-agent/external-providers.ts
@@ -21,8 +21,8 @@
* the OpenRouter aggregate; direct billing requires this adapter.
*
* doubao → https://ark.cn-beijing.volces.com/api/v3
- * OpenAI-compatible (Volcengine 火山方舟). User must create a "model
- * endpoint" (接入点 ID) in the ark console and use that id as the
+ * OpenAI-compatible (Volcengine Ark). User must create a "model
+ * endpoint" (endpoint id) in the ark console and use that id as the
* model — the curated list is just a hint.
*
* ## Adding a new external provider
@@ -40,8 +40,9 @@ import type { LLMProvider } from '#core-agent';
import type { Model } from '@mariozechner/pi-ai';
import { curatedModelsFor } from '../provider_catalog';
-// core-agent 是 ESM 包,Orkas main 进程走 CJS,**不能**静态 import。沿用
-// runner.ts / session-store.ts 的动态 import + 懒缓存 pattern。
+// core-agent is an ESM package and the Orkas main process is CJS, so
+// **static import is not allowed**. Reuse the dynamic-import + lazy cache
+// pattern from runner.ts / session-store.ts.
type CA = typeof import('#core-agent');
let _caPromise: Promise<CA> | null = null;
function ca(): Promise<CA> {
@@ -87,9 +88,10 @@ export function buildMoonshotModel(modelId: string): Model<'openai-completions'>
baseUrl: MOONSHOT_BASE_URL,
reasoning: false,
input: ['text', 'image'],
- // Moonshot 开放平台收费按 token 算,但 pi-ai 的 cost 字段只用于本地成本
- // 统计展示,不影响请求。填 0 代表"不在此处核算",具体价格用户去 Moonshot
- // 账单看。
+ // The Moonshot open platform bills per token, but pi-ai's `cost`
+ // field is only used for local cost-statistics display and does not
+ // affect the actual request. Filling 0 means "not accounted for here";
+ // users check the actual price on their Moonshot bill.
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: moonshotContextWindow(modelId),
maxTokens: 8192,
@@ -102,7 +104,7 @@ export interface CreateMoonshotProviderConfig {
}
/**
- * Build an LLMProvider wired to the Moonshot 开放平台 endpoint.
+ * Build an LLMProvider wired to the Moonshot open-platform endpoint.
*
* Async because core-agent is loaded on-demand (ESM from CJS main).
* Calling this does NOT talk to the network — it just wires a pi-ai
@@ -147,13 +149,16 @@ export function buildDeepSeekModel(modelId: string): Model<'openai-completions'>
api: 'openai-completions',
provider: 'deepseek' as any,
baseUrl: DEEPSEEK_BASE_URL,
- // V4 Pro / V4 Flash 都需当 reasoner 处理:实测 V4 Flash 也会自发返回
- // `reasoning_content`,一旦进入 session 历史,后续轮次缺 `reasoning_effort`
- // 就会被 DeepSeek 拒(误导性错误 "reasoning_content in the thinking mode
- // must be passed back")。pi-ai 的 openai-completions 适配器只在
- // `model.reasoning === true` 时才会拼 `reasoning_effort`(见 pi-ai
- // openai-completions.js 第 396 行),所以这里必须把 v4-* 全部标 true,
- // 配合下面的 `defaultReasoning: 'low'` 让请求里恒带 effort。
+ // Both V4 Pro and V4 Flash must be treated as reasoners: empirically
+ // V4 Flash also spontaneously returns `reasoning_content`, and once
+ // that lands in session history, subsequent turns missing
+ // `reasoning_effort` get rejected by DeepSeek (misleading error
+ // message "reasoning_content in the thinking mode must be passed
+ // back"). pi-ai's openai-completions adapter only attaches
+ // `reasoning_effort` when `model.reasoning === true` (see pi-ai
+ // openai-completions.js line 396), so we must mark every v4-* as
+ // true, paired with `defaultReasoning: 'low'` below so the request
+ // always carries the effort field.
reasoning: /^deepseek-v4-/.test(modelId),
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
@@ -176,22 +181,29 @@ export async function createDeepSeekProvider(config: CreateDeepSeekProviderConfi
provider: 'deepseek',
apiKey: config.apiKey,
customModel: model,
- // DeepSeek V4 server-side 校验有两个对称失效模式,误导性错误信息相同
- // ("reasoning_content in the thinking mode must be passed back to the API"):
- // A. `reasoning_effort` 缺失 + 历史里有 assistant.reasoning_content → 400
- // B. `reasoning_effort` 存在 + 历史里有 assistant 缺 reasoning_content → 400
- // 真正的规则是:`reasoning_effort` 的存在必须与 history 的 reasoning_content
- // 保持一致(全有 / 全无),不能"半开半关"。
+ // DeepSeek V4 server-side validation has two symmetric failure modes
+ // with the same misleading error message ("reasoning_content in the
+ // thinking mode must be passed back to the API"):
+ // A. `reasoning_effort` missing + history has
+ // assistant.reasoning_content → 400
+ // B. `reasoning_effort` present + history has an assistant message
+ // missing reasoning_content → 400
+ // The actual rule is: the presence of `reasoning_effort` must match
+ // the presence of reasoning_content across all history (all-or-none);
+ // a "half-open" mix is rejected.
//
- // 实测场景 B:rotating-provider 把主候选 openai-codex 失败后 fallback 到
- // deepseek,pi-ai/transform-messages.js 在 cross-provider 时把 codex 的
- // `thinking` 块降级成纯文本(丢 thinkingSignature),history 里 assistant
- // 没有 reasoning_content。我们再带 reasoning_effort 就触发 B。
+ // Observed scenario B: rotating-provider falls over from primary
+ // candidate openai-codex to deepseek; pi-ai/transform-messages.js
+ // downgrades codex's `thinking` blocks to plain text on a
+ // cross-provider hop (losing thinkingSignature), so the history's
+ // assistant message has no reasoning_content. Adding reasoning_effort
+ // then triggers B.
//
- // 修法:`onPayload` 动态决定 reasoning_effort —— 检查所有 prior assistant
- // 是否都带 reasoning_content(即"reasoning consistent"):
- // - 都有 → 保留 reasoning_effort (反向治 A)
- // - 不全有 → 删掉 reasoning_effort (治 B)
+ // Fix: `onPayload` decides reasoning_effort dynamically — inspect
+ // every prior assistant turn for reasoning_content
+ // ("reasoning consistent"):
+ // - all have → keep reasoning_effort (covers A in reverse)
+ // - not all → drop reasoning_effort (covers B)
onPayload: (params) => {
try {
const p = params as { reasoning_effort?: string; messages?: Array<{ role?: string; reasoning_content?: unknown; reasoning?: unknown }> };
@@ -216,13 +228,14 @@ export async function createDeepSeekProvider(config: CreateDeepSeekProviderConfi
});
}
-// ── Doubao / 火山方舟 (https://ark.cn-beijing.volces.com/api/v3) ─────────
+// ── Doubao / Volcengine Ark (https://ark.cn-beijing.volces.com/api/v3) ───
const DOUBAO_BASE_URL = 'https://ark.cn-beijing.volces.com/api/v3';
-// 火山方舟 Doubao Seed 2.0 系列 256k 上下文(官方 model card 2026-02 核对)。
-// 用户填的可能是 endpoint id(ep-xxxx)也可能是模型 id;上下文窗口以
-// 模型为准,未知 id fallback 到 131072 安全下界。
+// Doubao Seed 2.0 series on Volcengine Ark — 256k context window (verified
+// against the official model card 2026-02). The user may enter either an
+// endpoint id (ep-xxxx) or a model id; the context window is keyed by model
+// id, with a 131072 safe lower-bound fallback for unknown ids.
const DOUBAO_CONTEXT_WINDOW: Record<string, number> = {
'doubao-seed-2-0-pro-260215': 262144,
'doubao-seed-2-0-lite-260215': 262144,
@@ -240,12 +253,15 @@ export function buildDoubaoModel(modelId: string): Model<'openai-completions'> {
api: 'openai-completions',
provider: 'doubao' as any,
baseUrl: DOUBAO_BASE_URL,
- // Seed 2.0 Pro 默认走推理通道;Lite 是非推理性价比档。Seed 1.x
- // 用 `-thinking-` 后缀区分 reasoning,但 Seed 2.0 系列改成档位区分,
- // 兼容两套命名都能正确识别。
+ // Seed 2.0 Pro defaults to the reasoning channel; Lite is the
+ // non-reasoning budget tier. Seed 1.x distinguished reasoning via a
+ // `-thinking-` suffix, but Seed 2.0 switched to per-tier naming —
+ // we recognize both naming schemes for compatibility.
reasoning: /-pro-/.test(modelId) || /thinking/.test(modelId),
- // 火山方舟 OpenAI 兼容端只接受 system/assistant/user/tool;pi-ai 默认对未知
- // provider 自动启用 OpenAI 的 developer role,会被方舟 400 拒掉。显式关掉。
+ // Volcengine Ark's OpenAI-compatible endpoint only accepts
+ // system/assistant/user/tool; pi-ai by default auto-enables OpenAI's
+ // developer role for unknown providers, which Ark rejects with a
+ // 400. Disable it explicitly.
compat: { supportsDeveloperRole: false },
input: ['text', 'image'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
diff --git a/src/main/model/core-agent/kb-tools.ts b/src/main/model/core-agent/kb-tools.ts
index 1ad0d454..5637390c 100644
--- a/src/main/model/core-agent/kb-tools.ts
+++ b/src/main/model/core-agent/kb-tools.ts
@@ -8,7 +8,8 @@
*
* These tools are read-only and need no localExec permission. They replace
* the pre-kb-vector flow of `cat _INDEX.md` → drill into subdirs → cat files
- * (see `prompts/chat_commander.md` § 知识库 (KB) for the routing rule).
+ * (see the "Knowledge base (KB)" section of `prompts/chat_commander.md`
+ * for the routing rule).
*
* Uses the currently-active user via `getActiveUserId()` — the tool's `uid` is
* captured at runner build time and stays stable for the runner's lifetime
diff --git a/src/main/model/core-agent/native-search-tools.ts b/src/main/model/core-agent/native-search-tools.ts
index e9ee137b..1c57533b 100644
--- a/src/main/model/core-agent/native-search-tools.ts
+++ b/src/main/model/core-agent/native-search-tools.ts
@@ -1,48 +1,63 @@
/**
- * 模型原生 web search tool 调度。
+ * Model-native web search tool dispatch.
*
- * pi-ai 的 provider.stream() 在 `buildParams` 之后调用 `options.onPayload?(params, model)`,
- * 允许返回新 params 覆盖原 params。我们借这个 hook 把厂商 server-side web_search
- * schema 追加进 `params.tools`,不改 pi-ai 源码、不 patch node_modules。
+ * pi-ai's provider.stream() calls `options.onPayload?(params, model)` after
+ * `buildParams`, allowing the callback to return new params that overwrite
+ * the originals. We use this hook to append the vendor's server-side
+ * web_search schema to `params.tools` — without modifying pi-ai source or
+ * patching node_modules.
*
- * 调度依据 pi-ai Model.api 字段(provider.stream() 传进 onPayload 的 model 参数)。
- * 单点真相:新增支持的 api / 调整厂商 tool schema 版本号都改这里一处。
+ * Dispatch is keyed by pi-ai's Model.api field (the `model` argument
+ * passed to onPayload by provider.stream()).
+ * Single source of truth: adding new supported apis / bumping the vendor
+ * tool schema version is a one-place change here.
*/
/**
- * 返回 pi-ai 该 api 对应的模型原生 web search tool schema;不支持时返回 undefined。
- * schema 会直接作为 entry 追加到 `params.tools`,pi-ai 不会再碰它(它只负责转换
- * `type: "function"` 那类)。
+ * Returns the model-native web search tool schema for this pi-ai api;
+ * returns undefined when unsupported.
+ * The schema is appended verbatim to `params.tools`; pi-ai does not touch
+ * it again (it only transforms `type: "function"` entries).
*/
export function nativeSearchToolForApi(api: string | undefined): Record<string, unknown> | undefined {
switch (api) {
- // OpenAI Responses 系(直连 / Azure / ChatGPT Codex OAuth)统一用 **GA** 版
- // `web_search`,不再用老的 `web_search_preview` preview 变体。
- // - Codex 后端(2026-04-23 实测)只接 GA,preview 会报
- // `{"detail":"Unsupported tool type: web_search_preview"}`
- // - 直连账户 preview 和 GA 都能通,但 GA 是正式版,schema 稳定 + 有 SLA,
- // 没理由继续用 preview
- // - Azure 没独立实测,按 API 一致性默认走 GA;若 Azure 后端早几版不认
- // GA,再在此单独分支回退
+ // OpenAI Responses family (direct / Azure / ChatGPT Codex OAuth) all
+ // use the **GA** `web_search` tool, no longer the older
+ // `web_search_preview` variant.
+ // - Codex backend (verified 2026-04-23) only accepts GA; preview
+ // errors with
+ // `{"detail":"Unsupported tool type: web_search_preview"}`.
+ // - Direct accounts accept both preview and GA, but GA is the
+ // official release with stable schema + SLA — no reason to keep
+ // using preview.
+ // - Azure hasn't been independently tested; default to GA by API
+ // consistency. If an early Azure backend version rejects GA,
+ // branch back here.
case 'openai-responses':
case 'azure-openai-responses':
case 'openai-codex-responses':
return { type: 'web_search' };
- // Anthropic Messages 协议 —— **故意不支持**。
- // 官方 docs 里 `web_search_20250305` server tool 是真实存在的,但 Orkas
- // catalog 下 `anthropic` provider 大部分用户走 OAuth(Claude Pro/Max 订阅
- // 或 Claude Code 登录,token 形如 `sk-ant-oat...`),pi-ai 对 OAuth 套了
- // `claude-code-20250219` + `oauth-2025-04-20` 这套 beta header,后端按
- // header 限权——跟 ChatGPT Codex OAuth 拒 `web_search_preview` 是同个机制,
- // OAuth 路径大概率拒收 server tool,注入 → 整次对话 error。
- // 以"首要不能让现有对话挂掉"为原则整条剔掉。如果用户明确用直连 API key
- // 且想开原生搜索,将来再加一条 `if isOAuth ? skip : inject` 的分支。
+ // Anthropic Messages protocol — **deliberately unsupported**.
+ // The `web_search_20250305` server tool is a real entry in the
+ // official docs, but in the Orkas catalog the `anthropic` provider
+ // is mostly accessed via OAuth (Claude Pro/Max subscription or
+ // Claude Code login, token shaped like `sk-ant-oat...`), and pi-ai
+ // wraps OAuth with the `claude-code-20250219` +
+ // `oauth-2025-04-20` beta header — the backend gates capability by
+ // header, the same mechanism that makes ChatGPT Codex OAuth reject
+ // `web_search_preview`. The OAuth path is very likely to reject
+ // server tools; injecting one would error out the whole
+ // conversation.
+ // Following the "above all, don't break the live conversation"
+ // rule we omit the entry. If a user explicitly uses a direct API
+ // key and wants native search, we can later add an
+ // `if isOAuth ? skip : inject` branch.
//
// case 'anthropic-messages':
// return { type: 'web_search_20250305', name: 'web_search', max_uses: 5 };
- // Google Gemini / Vertex —— grounding with google search。不需要额外字段。
+ // Google Gemini / Vertex — grounding with google search. No extra fields.
case 'google-generative-ai':
case 'google-vertex':
return { google_search: {} };
@@ -53,20 +68,24 @@ export function nativeSearchToolForApi(api: string | undefined): Record<string,
}
/**
- * 便于在只拿到 providerId(还没拿到 pi-ai Model 对象)的地方做"会不会注入"
- * 的提前判断,主要给 client.ts 在开始流之前 push synthetic archive event 用。
- * 这个映射是 provider → 最常见的 api 约定;极少数 provider 可能例外(azure
- * openai 走 responses),但那些不在当前 catalog 里。catalog 外的 provider
- * 不在本函数里显式列,返回 undefined 由 onPayload 做最终裁决。
+ * Pre-flight "will we inject?" check for callers that only have a
+ * providerId (no pi-ai Model object yet); used by client.ts to push a
+ * synthetic archive event before the stream starts.
+ * The mapping is provider → its most common api convention; a small
+ * number of providers may differ (e.g. Azure OpenAI uses responses), but
+ * those are not in the current catalog. Providers outside the catalog are
+ * not enumerated here — we return undefined and let onPayload make the
+ * final call.
*/
export function nativeSearchToolForProvider(providerId: string): Record<string, unknown> | undefined {
const api = providerApi(providerId);
return api ? nativeSearchToolForApi(api) : undefined;
}
-/** Conservative providerId → api mapping. 未列 = 未知 = 不注入。
- * `anthropic` 虽然有 api 映射、但 `nativeSearchToolForApi('anthropic-messages')`
- * 当前返回 undefined(见上方注释),等价于不注入。 */
+/** Conservative providerId → api mapping. Unlisted = unknown = no inject.
+ * `anthropic` has an api mapping, but
+ * `nativeSearchToolForApi('anthropic-messages')` currently returns
+ * undefined (see the note above) — effectively no-op. */
function providerApi(providerId: string): string | undefined {
switch (providerId) {
case 'openai': return 'openai-responses';
@@ -79,7 +98,7 @@ function providerApi(providerId: string): string | undefined {
}
}
-/** Human-readable 标签(日志 / archive 事件展示用)。 */
+/** Human-readable label (used by logs / archive event displays). */
export function nativeSearchToolName(tool: Record<string, unknown> | undefined): string | undefined {
if (!tool) return undefined;
const t = tool['type'];
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index fe539c76..06bec6e1 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -11,7 +11,7 @@
* materialize the single provider we picked.
*
* When `pickChatEntry()` returns null we fail fast with a user-facing
- * "未配置模型" error so the renderer doesn't surface the Anthropic SDK's
+ * "no model configured" error so the renderer doesn't surface the Anthropic SDK's
* cryptic "Could not resolve authentication method" message. Dev escape
* hatch: set `ANTHROPIC_API_KEY` in the environment and we pass through
* to the SDK's default-provider + env-var auth path.
@@ -265,7 +265,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// (read_file/write_file/bash/list_files/web_search/web_fetch) merged with
// our wrappedTools via last-write-wins. Used by the snapshot below and by
// the catalog-drift test (`tool-catalog.test.ts`); we no longer render a
- // `## 可用工具 (tools)` block into the system prompt because the model
+ // `## Available tools` block into the system prompt because the model
// already receives every tool's full description + JSON schema via the
// SDK tool-use protocol — the prompt block was an information subset
// duplicating ~800 chars per call without giving the model anything new.
@@ -308,11 +308,16 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
if (skillsBlock) parts.push(skillsBlock.trim());
const resolvedSystemPrompt = parts.join('\n\n');
- // Evolution(自演进 skill 仓库)按 agent 隔离:有 agentId 时落到该 agent 的
- // 私有目录 `<uid>/cloud/agents/<aid>/skills/`,核心 default 对话(无 agentId)
- // 关闭演进——commander 不该自动产 skill,要写就走 user UI 的 System A 路径。
- // 不传 evolution 段时 core-agent 默认 enabled=true + skillsDir="skills" 相对
- // cwd → 会落进 `PC/skills/`(见 docs/plans/agent-as-directory.md 修复点)。
+ // Evolution (the self-evolving skill store) is per-agent: when an
+ // agentId is present we write into that agent's private directory
+ // `<uid>/cloud/agents/<aid>/skills/`. The core default conversation
+ // (no agentId) has evolution disabled — the commander shouldn't be
+ // auto-producing skills; user-authored skills go through the
+ // System A path in the user UI.
+ // When the evolution stanza is not passed, core-agent defaults to
+ // enabled=true + skillsDir="skills" relative to cwd, which would
+ // dump into `PC/skills/` (see the fix point in
+ // docs/plans/agent-as-directory.md).
const evolutionConfig = (agentId && earlyUid)
? { enabled: true, skillsDir: agentEvolvedSkillsDir(earlyUid, agentId) }
: { enabled: false };
@@ -324,13 +329,17 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
...(resolvedSystemPrompt ? { systemPrompt: resolvedSystemPrompt } : {}),
},
evolution: evolutionConfig,
- // 故意不填 `models.providers` —— ProviderRegistry 构造时会对里面每个
- // 条目调默认 factory(anthropic / openai / pi-ai),直接把 provider 实例
- // 塞进 `providers` cache;后续 `providers.get(id)` 优先走 cache,
- // 永远跳不到下面 registerFactory 注入的 rotating-provider(包括单把 key
- // 的情况——之前的 "group.length===1 走原路径" 分支就是这么错过冷却/
- // 错误分类的)。把 provider 创建完全交给 rotating-provider 管,wrapper
- // 对单把 key 也只是一层 closure,开销可忽略,换来统一的错误路径。
+ // We deliberately do NOT populate `models.providers` —
+ // ProviderRegistry's constructor runs the default factory
+ // (anthropic / openai / pi-ai) on every entry and stuffs the
+ // provider instance into the `providers` cache; subsequent
+ // `providers.get(id)` calls hit the cache first and never reach
+ // the registerFactory-injected rotating-provider below (this
+ // includes the single-key case — the old "group.length===1 → take
+ // the legacy path" branch missed cooldown / error classification
+ // for exactly this reason). Hand all provider creation to
+ // rotating-provider; for a single key the wrapper is just one
+ // closure (negligible cost) and we get a uniform error path.
});
const providers = new mod.ProviderRegistry(config);
@@ -447,10 +456,11 @@ async function buildRotatingProvider(
if (isExternal) {
return buildExternalProvider(candProviderId, choice.apiKey, candModelId);
}
- // pi-ai catalog 没有 OAuth 变体(`minimax-portal[-cn]`),但 OAuth 端
- // 与对应 API-key 端(`minimax[-cn]`)走同一 baseUrl + api 协议,access
- // token 直接当 Bearer 用。借 API-key 的 Model 元数据当 customModel,
- // 跳过 catalog 查询。
+ // The pi-ai catalog has no OAuth variant (`minimax-portal[-cn]`),
+ // but the OAuth endpoint shares baseUrl + api protocol with the
+ // corresponding API-key endpoint (`minimax[-cn]`); the access
+ // token can be used directly as a Bearer. Reuse the API-key
+ // Model metadata as customModel and skip the catalog lookup.
const customModel = aliasedPiModel(mod, candProviderId, candModelId);
return mod.createPiProvider({
provider: candProviderId,
@@ -474,9 +484,12 @@ async function buildRotatingProvider(
}
/**
- * pi-ai catalog 不识别的 OAuth provider 别名 → API-key 同源 provider。
- * 同源 = 同 baseUrl + 同 api 协议;OAuth access token 走 Bearer,与 API key
- * 在 HTTP 层无差。映射为空时返回 undefined,让原路径走 catalog 查询。
+ * Aliases for OAuth provider ids that are unknown to the pi-ai catalog →
+ * the same-origin API-key provider. Same origin = same baseUrl + same api
+ * protocol; an OAuth access token rides as a Bearer, indistinguishable
+ * from an API key at the HTTP layer. Returns undefined when no alias is
+ * registered, letting the caller fall through to the original catalog
+ * lookup.
*/
const PI_PROVIDER_ALIAS: Readonly<Record<string, string>> = {
'minimax-portal-cn': 'minimax-cn',
@@ -506,11 +519,14 @@ export function isMetacognitionEnabled(): boolean {
}
/**
- * 构造 pi-ai `onPayload` 回调:pi-ai 把 `buildParams` 产物交上来之后、发请求
- * 之前触发。命中"model.api 属于支持列表 + 用户没配付费搜索"时,往 `params.tools`
- * 追加模型原生 web search tool schema;同时写 info 日志。
+ * Builds a pi-ai `onPayload` callback: pi-ai invokes it after handing us
+ * the result of `buildParams` and before sending the request. When both
+ * "model.api is in the supported list" and "the user has no paid search
+ * profile configured" hold, we append the model's native web search tool
+ * schema to `params.tools` and write an info log.
*
- * 不命中就原封返回 params(pi-ai 看到 undefined 也不会覆盖,所以空操作也合法)。
+ * On a miss we return params unchanged (pi-ai treats an undefined return
+ * as no-op, so a no-op return is also legal).
*/
function buildNativeSearchOnPayload(
providerId: string,
diff --git a/src/main/model/core-agent/search-adapters.ts b/src/main/model/core-agent/search-adapters.ts
index 35fba9b3..7f83b379 100644
--- a/src/main/model/core-agent/search-adapters.ts
+++ b/src/main/model/core-agent/search-adapters.ts
@@ -133,16 +133,18 @@ async function braveApiSearch(profile: SearchProfile, query: string, count: numb
};
}
-// ── 百度 AI 搜索 (千帆) ─────────────────────────────────────────────────
+// ── Baidu AI Search (Qianfan) ───────────────────────────────────────────
/**
- * 百度智能云千帆 AI 搜索:
+ * Baidu Cloud Qianfan AI Search:
* Endpoint: POST https://qianfan.baidubce.com/v2/ai_search
- * 鉴权:Authorization: Bearer <API Key>(千帆 API Key,控制台「API Key 管理」获取)
- * 文档:https://cloud.baidu.com/doc/qianfan-api/s/em82g4tlk
+ * Auth: Authorization: Bearer <API Key> (Qianfan API Key, obtained from
+ * the "API Key Management" page of the console).
+ * Docs: https://cloud.baidu.com/doc/qianfan-api/s/em82g4tlk
*
- * 注:百度该接口请求体里只需要 `messages`(用户 query),返回结构是
- * `references[]`,每项 `{title, url, snippet}` —— 直接映射即可。
+ * Note: this endpoint only needs `messages` (the user query) in the
+ * request body; the response shape is `references[]`, each entry
+ * `{title, url, snippet}` — a direct mapping.
*/
async function baiduAiSearch(profile: SearchProfile, query: string, count: number): Promise<SearchAdapterResult> {
const body = JSON.stringify({
@@ -174,23 +176,25 @@ async function baiduAiSearch(profile: SearchProfile, query: string, count: numbe
};
}
-// ── 秘塔 AI 搜索 (Metaso) ───────────────────────────────────────────────
+// ── Metaso AI Search ────────────────────────────────────────────────────
/**
- * 秘塔 AI 搜索:
+ * Metaso AI Search:
* Endpoint: POST https://api.metaso.cn/search
- * 鉴权:Authorization: Bearer <api-key>
- * 文档/控制台:https://metaso.cn/
+ * Auth: Authorization: Bearer <api-key>
+ * Docs / console: https://metaso.cn/
*
- * 请求体核心字段(核对 2026-04):
+ * Request body core fields (verified 2026-04):
* - q (string, required)
* - scope: 'webpage' | 'document' | 'scholar' | 'podcast' | 'video' | 'image'
- * 默认 'webpage'
+ * (default 'webpage')
* - size (number, optional)
* - includeSummary (boolean, optional)
*
- * 响应字段名秘塔不同环境下不完全一致(references / results / data 都能见到;
- * 单条里 title/url/snippet/content/summary 也存在简写差异),所以做多键 fallback。
+ * Response field names vary across Metaso environments (references /
+ * results / data are all observed; per-entry title/url/snippet/content/
+ * summary also have abbreviation differences), so we do multi-key
+ * fallback.
*/
async function metasoSearch(profile: SearchProfile, query: string, count: number): Promise<SearchAdapterResult> {
const body = JSON.stringify({
diff --git a/src/main/model/core-agent/search-tools.ts b/src/main/model/core-agent/search-tools.ts
index 0083922d..f95f450a 100644
--- a/src/main/model/core-agent/search-tools.ts
+++ b/src/main/model/core-agent/search-tools.ts
@@ -5,7 +5,7 @@
* Resolution order on every call:
* 1. If the user configured ANY paid search API key (`searchProfiles`),
* route the query through the first usable adapter (Tavily / Serper /
- * Brave / 百度 AI 搜索). On success → return; on failure → fall
+ * Brave / Baidu AI Search). On success → return; on failure → fall
* through to step 2 with a noted error.
* 2. Otherwise, delegate to the keyless Brave/Bing HTML scraper exposed
* by core-agent as `runBuiltinWebSearch` — same behavior as before
diff --git a/src/main/model/core-agent/session-store.ts b/src/main/model/core-agent/session-store.ts
index 81204518..a8c995ad 100644
--- a/src/main/model/core-agent/session-store.ts
+++ b/src/main/model/core-agent/session-store.ts
@@ -3,19 +3,25 @@
* `PersistentSession` backed by a JSONL file under
* `data/<user_id>/cloud/sessions/<session_id>.jsonl`.
*
- * session_id 统一规则(见 CLAUDE.md §5):
+ * session_id format (see CLAUDE.md §5):
* `<uid>-<kind>-<tail>`
- * uid 必在第一段;不符合格式的 id 一律拒绝,防止 extract/organizer 早期那种
- * "第一段塞成 feature 名" 的 bug 再复发。
- * 当前在用 kind:gconv(群聊指挥官)/ gmember(群内 agent)/ skill / agent /
- * extract-img / reflect / memory-extract / anon
- * builders:features/group_chat/state.ts 的 buildGconvSessionId / buildGmemberSessionId、
- * features/agents.ts 的 defaultAgentEditSessionId、features/skills.ts 的 skill chat 同理。
- * 历史品牌前缀在启动期由 features/users.ts 的迁移工具一次性剥掉,
- * 到这里时不应再出现;任何带前缀的 id 都视作非法。
+ * uid MUST be the first segment; ids that don't fit are rejected
+ * outright, to prevent regressions like the early extract/organizer
+ * bug where the first segment was stuffed with a feature name.
+ * Currently-used kinds: gconv (group-chat commander) / gmember
+ * (group-chat agent) / skill / agent / extract-img / reflect /
+ * memory-extract / anon.
+ * Builders: features/group_chat/state.ts's buildGconvSessionId /
+ * buildGmemberSessionId; features/agents.ts's
+ * defaultAgentEditSessionId; features/skills.ts's skill chat is
+ * analogous.
+ * Legacy brand prefixes are stripped once at startup by the
+ * migration tool in features/users.ts and should not appear here;
+ * any id carrying such a prefix is treated as illegal.
*
- * session jsonl 仅承载 LLM 视角(含 tool_use / tool_result / compaction),与
- * `<uid>/cloud/chats/<cid>.jsonl`(UI 视角)是两份独立文件。
+ * session jsonl only carries the LLM-facing view (including tool_use /
+ * tool_result / compaction); it's a separate file from
+ * `<uid>/cloud/chats/<cid>.jsonl` (the UI-facing view).
*/
import * as path from 'node:path';
diff --git a/src/main/model/provider_catalog.ts b/src/main/model/provider_catalog.ts
index 625581dc..96f484e4 100644
--- a/src/main/model/provider_catalog.ts
+++ b/src/main/model/provider_catalog.ts
@@ -36,14 +36,15 @@ export interface CatalogEntry {
oauthOnly?: boolean; // if true, hide the API-key path entirely
/** Per-provider prerequisite note shown on the card + the add-key form.
* Used when the same "brand" has two independent billing/auth surfaces
- * (e.g. Moonshot 开放平台按量付费 vs. Kimi Coding Plan 月付订阅) so users
+ * (e.g. Moonshot pay-as-you-go open platform vs. Kimi Coding Plan
+ * monthly subscription) so users
* can tell which one they have before wasting a key. Keep it short —
* one sentence max, UI shows it with a warning-style accent.
*
* **Value is an i18n key** (e.g. `provider.moonshot.note_paygo`), not raw
* text. Renderer resolves via `t()` so the hint follows UI language. */
subscriptionNote?: string;
- /** Mark a provider as the recommended default. UI shows a "推荐 / Recommended"
+ /** Mark a provider as the recommended default. UI shows a "Recommended"
* suffix on the picker label. Purely cosmetic — does not change selection
* defaults or routing. */
recommended?: boolean;
@@ -51,13 +52,14 @@ export interface CatalogEntry {
// ── Ordered catalog (dropdown order = array order) ──────────────────────
//
-// Group 0: recommended default (DeepSeek 直连 — 国内速度 + 价格优势)
+// Group 0: recommended default (DeepSeek direct — best China latency + price)
// Group 1: global frontier labs (Anthropic, OpenAI, Google)
// Group 2: China mainstream (Zhipu GLM, Moonshot Kimi, MiniMax)
// Group 3: aggregators (OpenRouter)
export const CATALOG: readonly CatalogEntry[] = [
- // DeepSeek 直连(pi-ai 0.68.1 不带,走 external-providers.ts 的 openai-completions 适配)
+ // DeepSeek direct (not in pi-ai 0.68.1; routed through the
+ // openai-completions adapter in external-providers.ts).
{ id: 'deepseek', label: 'DeepSeek', docsUrl: 'https://platform.deepseek.com/api_keys', recommended: true },
{ id: 'openai-codex', label: 'OpenAI Codex', oauthOnly: true },
@@ -66,11 +68,14 @@ export const CATALOG: readonly CatalogEntry[] = [
{ id: 'anthropic', label: 'Anthropic', docsUrl: 'https://console.anthropic.com/settings/keys' },
{ id: 'zai', label: 'Zhipu GLM', docsUrl: 'https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys', region: 'cn' },
- // Moonshot 有两条独立计费的 endpoint:
- // - `moonshot` → https://api.moonshot.cn/v1 (OpenAI 兼容,按量付费开放平台)
- // - `kimi-coding` → https://api.kimi.com/coding (Anthropic 协议,Kimi 编程订阅月付专用)
- // 两条都绑在同一 Moonshot 账号上但鉴权/额度完全独立,一张 key 不能两边通用。
- // UI 上分成两张独立卡片,各自带 `subscriptionNote` 提示前提条件。
+ // Moonshot has two independently-billed endpoints:
+ // - `moonshot` → https://api.moonshot.cn/v1 (OpenAI-compatible,
+ // pay-as-you-go open platform).
+ // - `kimi-coding` → https://api.kimi.com/coding (Anthropic protocol,
+ // monthly subscription for Kimi Coding only).
+ // Both bind to the same Moonshot account but have separate auth and
+ // quota — a single key cannot be used on both. The UI shows them as
+ // two separate cards, each with its own `subscriptionNote`.
{ id: 'moonshot', label: 'Moonshot', docsUrl: 'https://platform.moonshot.cn/console/api-keys', region: 'cn',
subscriptionNote: 'provider.moonshot.note_paygo' },
{ id: 'kimi-coding', label: 'Moonshot Coding Plan', docsUrl: 'https://platform.moonshot.cn/console/api-keys', region: 'cn',
@@ -82,7 +87,7 @@ export const CATALOG: readonly CatalogEntry[] = [
{ id: 'minimax-portal-cn', label: 'MiniMax (CN)', oauthOnly: true, region: 'cn' },
{ id: 'minimax-cn', label: 'MiniMax', docsUrl: 'https://platform.minimaxi.com/user-center/basic-information/interface-key', region: 'cn' },
- // 豆包 / 火山方舟
+ // Doubao / Volcengine Ark
{ id: 'doubao', label: 'Doubao', docsUrl: 'https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey', region: 'cn',
subscriptionNote: '' },
@@ -99,10 +104,11 @@ export const CATALOG: readonly CatalogEntry[] = [
// which keeps the last 2 version bands from pi-ai's raw list.
export const CURATED_MODELS: Readonly<Record<string, readonly { id: string; name: string }[]>> = {
- // Anthropic 直连:id 用 dash 形式(pi-ai 0.68.1 的 provider="anthropic" 用
- // claude-<tier>-<major>-<minor>)。Opus 4.5–4.7、Sonnet 4.5/4.6、Haiku 4.5
- // 是 pi-ai 0.68.1 实际存在的 id;sonnet-4-7 / haiku-4-6/4-7 在 pi-ai 里不
- // 存在(2026-04 核对),已剔除。
+ // Anthropic direct: ids use dash form (pi-ai 0.68.1's
+ // provider="anthropic" uses claude-<tier>-<major>-<minor>). Opus 4.5–4.7,
+ // Sonnet 4.5/4.6 and Haiku 4.5 are real ids in pi-ai 0.68.1; sonnet-4-7
+ // and haiku-4-6/4-7 do not exist in pi-ai (verified 2026-04) and have
+ // been removed.
anthropic: [
{ id: 'claude-opus-4-7', name: 'Claude Opus 4.7' },
{ id: 'claude-opus-4-6', name: 'Claude Opus 4.6' },
@@ -132,10 +138,11 @@ export const CURATED_MODELS: Readonly<Record<string, readonly { id: string; name
{ id: 'gpt-5.4-mini', name: 'GPT-5.4 Mini' },
],
- // Google Gemini 直连。pi-ai 0.68.1 的 provider="google" 只列出带 -preview
- // 后缀的 3.x 条目(Google 当前 3.x 仍在预览阶段),稳定版最高到 2.5。旧
- // 版 catalog 写的 `gemini-3.1-pro` / `gemini-3-pro` / `gemini-3.0-flash`
- // 是幻觉 id(pi-ai 不认),已全部改为真实 id。
+ // Google Gemini direct. pi-ai 0.68.1's provider="google" only lists 3.x
+ // entries with the -preview suffix (Google's 3.x is still in preview);
+ // the stable line caps at 2.5. The old catalog had hallucinated ids
+ // `gemini-3.1-pro` / `gemini-3-pro` / `gemini-3.0-flash` which pi-ai
+ // does not recognize — all replaced with real ids.
google: [
{ id: 'gemini-3.1-pro-preview', name: 'Gemini 3.1 Pro (preview)' },
{ id: 'gemini-3.1-flash-lite-preview', name: 'Gemini 3.1 Flash Lite (preview)' },
@@ -151,19 +158,23 @@ export const CURATED_MODELS: Readonly<Record<string, readonly { id: string; name
{ id: 'glm-5v-turbo', name: 'GLM-5V Turbo' },
],
- // Moonshot 开放平台 — https://api.moonshot.cn/v1 (OpenAI 兼容,按量付费)。
- // pi-ai 0.68.1 没注册这个 provider,我们通过 `model/core-agent/external-providers.ts`
- // 手构 `Model<"openai-completions">` 直接调 pi-ai 的低阶 API。
- // id 取自 platform.kimi.com/docs/models(2026-04 核对)。
- // 只收录当代主力 K2.5 / K2.6(id 带点);上一代 K2 preview 系列 2026-05-25 EOL
- // 不再列出,避免新建凭证默认选到将停服的模型。
+ // Moonshot open platform — https://api.moonshot.cn/v1 (OpenAI-compatible,
+ // pay-as-you-go). pi-ai 0.68.1 does not register this provider; we
+ // hand-build a `Model<"openai-completions">` via
+ // `model/core-agent/external-providers.ts` and call pi-ai's low-level API
+ // directly. Ids are sourced from platform.kimi.com/docs/models
+ // (verified 2026-04). Only the current flagship K2.5 / K2.6 are listed
+ // (their ids contain a dot); the previous-gen K2 preview series EOLs
+ // 2026-05-25 and is intentionally omitted so new credentials don't default
+ // to a model that is about to be retired.
moonshot: [
{ id: 'kimi-k2.6', name: 'Kimi K2.6' },
{ id: 'kimi-k2.5', name: 'Kimi K2.5' },
],
- // Kimi Coding Plan — https://api.kimi.com/coding (Anthropic 协议,月付订阅专用)
- // pi-ai 0.68.1 的 provider id 是 `kimi-coding`;新增 `k2p6` (K2.6)。
+ // Kimi Coding Plan — https://api.kimi.com/coding (Anthropic protocol,
+ // monthly subscription only). pi-ai 0.68.1's provider id is
+ // `kimi-coding`; `k2p6` (K2.6) was added.
'kimi-coding': [
{ id: 'k2p6', name: 'Kimi K2.6' },
{ id: 'kimi-for-coding', name: 'Kimi For Coding' },
@@ -186,19 +197,25 @@ export const CURATED_MODELS: Readonly<Record<string, readonly { id: string; name
{ id: 'MiniMax-M2.7-highspeed', name: 'MiniMax M2.7 Highspeed' },
],
- // DeepSeek V4 直连(OpenAI 兼容协议,base url https://api.deepseek.com/v1)。
- // 2026-04-24 发布;旧 id `deepseek-chat` / `deepseek-reasoner` 官方明确将
- // deprecate,分别对应 v4-flash 的非推理 / 推理模式。这里只收正式 id。
- // 来源:https://api-docs.deepseek.com/quick_start/pricing (2026-04 核对)。
+ // DeepSeek V4 direct (OpenAI-compatible protocol, base url
+ // https://api.deepseek.com/v1). Released 2026-04-24; the old ids
+ // `deepseek-chat` / `deepseek-reasoner` are explicitly deprecated by the
+ // vendor — they map to v4-flash's non-reasoning / reasoning modes
+ // respectively. We only list the official ids here.
+ // Source: https://api-docs.deepseek.com/quick_start/pricing (verified 2026-04).
deepseek: [
{ id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro' },
{ id: 'deepseek-v4-flash', name: 'DeepSeek V4 Flash' },
],
- // 豆包 Seed 2.0(火山方舟,OpenAI 兼容协议,base url https://ark.cn-beijing.volces.com/api/v3)。
- // 2026-02-15 发布。Pro = 旗舰多模态,Lite = 性价比档。Mini / Code 子档暂
- // 不收(Mini 边缘场景、Code 编程专用,常规 chat 主线列两档够了)。
- // 火山方舟也支持用户自建接入点(ep-xxxx)—— 自建 id 直接在 entry 表手填覆盖即可。
+ // Doubao Seed 2.0 (Volcengine Ark, OpenAI-compatible, base url
+ // https://ark.cn-beijing.volces.com/api/v3). Released 2026-02-15.
+ // Pro = flagship multimodal, Lite = budget tier. Mini / Code subtiers
+ // are intentionally not listed (Mini is edge-only, Code is programming-
+ // specific; two tiers are enough for the chat main line).
+ // Volcengine Ark also supports user-defined endpoints (ep-xxxx) —
+ // those custom ids can be entered directly in the credential form to
+ // override.
doubao: [
{ id: 'doubao-seed-2-0-pro-260215', name: 'Doubao Seed 2.0 Pro' },
{ id: 'doubao-seed-2-0-lite-260215', name: 'Doubao Seed 2.0 Lite' },
@@ -385,18 +402,22 @@ export interface ImageGenCapability {
}
export const IMAGE_GEN_BY_PROVIDER: Readonly<Record<string, ImageGenCapability>> = {
- // OpenAI GPT Image 2(2026-04-21 发布;HTTP 接口与 gpt-image-1 完全兼容,
- // 仍走 /v1/images/generations + /v1/images/edits)。
+ // OpenAI GPT Image 2 (released 2026-04-21; HTTP interface is fully
+ // compatible with gpt-image-1 and still uses /v1/images/generations +
+ // /v1/images/edits).
openai: { model: 'gpt-image-2', api: 'openai', supportsEdit: true },
- // Google Nano Banana 2 = `gemini-3.1-flash-image-preview`(preview 后缀
- // 是官方 model id 的一部分,不能去掉)。Pro 版叫 Nano Banana Pro
- // (`gemini-3-pro-image-preview`),本期先收 Flash —— 速度 + 价格更平衡。
+ // Google Nano Banana 2 = `gemini-3.1-flash-image-preview` (the -preview
+ // suffix is part of the official model id and must not be stripped).
+ // The Pro variant is Nano Banana Pro (`gemini-3-pro-image-preview`); we
+ // currently only ship Flash — better balance of speed and cost.
google: { model: 'gemini-3.1-flash-image-preview', api: 'gemini', supportsEdit: true },
- // 火山方舟 Seedream 4.5(doubao-seedream-4-5-251128,2025-11-28 production)。
- // OpenAI-compatible images endpoint (POST /api/v3/images/generations),
- // 文生图 / 图生图 / 多图组合都共用这一个 endpoint:body 不带 `image` 字段
- // 就是文生图,带 `image: string | string[]`(URL 或 data URI)就是图生图。
- // 旧的 seedream-3-0-t2i-250415 已下线(404)。
+ // Volcengine Ark Seedream 4.5 (doubao-seedream-4-5-251128, production
+ // 2025-11-28). OpenAI-compatible images endpoint
+ // (POST /api/v3/images/generations); text-to-image, image-to-image and
+ // multi-image composition all share this endpoint — without an `image`
+ // field in the body it's text-to-image, with `image: string | string[]`
+ // (URL or data URI) it's image-to-image. The old
+ // seedream-3-0-t2i-250415 has been retired (404).
doubao: { model: 'doubao-seedream-4-5-251128', api: 'doubao', supportsEdit: true },
};
diff --git a/src/main/paths.ts b/src/main/paths.ts
index 9c918b12..009f6635 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -11,17 +11,17 @@
* main/ ← index.ts + preload.js + features/...
* renderer/ builtin/ resources/ core-agent/
* data/ ← WS_ROOT (dev default); userData/data in prod
- * users.json ← 本机 uid 注册表 + current_user_id
- * logs/ ← 本机日志(全局按天滚动)
- * builtin/ ← 本机公共 builtin 运行时副本(启动 hash 同步自 src/builtin/)
+ * users.json ← Local uid registry + current_user_id
+ * logs/ ← Local logs (rolled daily, global)
+ * builtin/ ← Local public builtin runtime copy (hash-synced from src/builtin/ at startup)
* agents/<agent_id>/
* skills/<skill_id>/
* <user_id>/
- * cloud/ ← ☁️ 云同步域(账号体系落地后按 uid / 组织 / 团队同步)
+ * cloud/ ← Cloud-sync domain (synced per uid / org / team once accounts are integrated)
* chats/ chat_attachments/ sessions/ contexts/ memory/
* agents/<agent_id>/ skills/<skill_id>/ meta/<agent_id>/
* config/preferences.json
- * local/ ← 🔒 本机域(永不同步)
+ * local/ ← Machine-private domain (never synced)
* config/ ← auth-profiles.json + web-search-cache.json
* search/ ← contexts / chats inverted idx (agent / skill bodies queried in-memory at request time)
*
@@ -42,25 +42,29 @@ export const APP_ROOT = PC_ROOT;
export const PROJECT_ROOT = path.resolve(PC_ROOT, '..'); // Orkas
// ── Data root (env > dev default) ────────────────────────────────────────
-// 磁盘目录名是 `data/`;常量名仍叫 WS_ROOT("workspace root" 的历史缩写,
-// 内部 TS 符号,不参与 user-facing 命名)。env var `ORKAS_WORKSPACE_ROOT`
-// 同样保留旧名以便 deploy 端无感升级。
+// The on-disk directory name is `data/`; the constant is still named WS_ROOT
+// (a historical abbreviation of "workspace root" — it's an internal TS symbol
+// and not part of any user-facing naming). The env var `ORKAS_WORKSPACE_ROOT`
+// likewise keeps its old name so deployments upgrade transparently.
export const WS_ROOT = process.env.ORKAS_WORKSPACE_ROOT
? path.resolve(process.env.ORKAS_WORKSPACE_ROOT)
: path.join(PC_ROOT, 'data');
-// ── Top-level (本机全局,多 uid 共享) ────────────────────────────────────
-// 本机 uid 注册表:{ current_user_id, users: [{user_id, created_at}, ...] }
+// ── Top-level (machine-global, shared across uids) ───────────────────────
+// Machine-local uid registry: { current_user_id, users: [{user_id, created_at}, ...] }
export const USERS_FILE = path.join(WS_ROOT, 'users.json');
-// 本机日志(按天滚动,全局一份,多 uid 共享)
+// Machine-local logs (daily rolling, single global file shared across uids).
export const LOGS_DIR = path.join(WS_ROOT, 'logs');
-// Builtin 运行时副本:启动时由 `src/builtin/` 按 hash 同步到这里,
-// 所有 uid 共享读取;loader 扫描路径为 `[<uid>/cloud/{skills,agents}, <BUILTIN_{SKILLS,AGENTS}_DIR>]`。
+// Builtin runtime copy: hash-synced from `src/builtin/` at startup; all uids
+// read from here. The loader scans
+// `[<uid>/cloud/{skills,agents}, <BUILTIN_{SKILLS,AGENTS}_DIR>]`.
export const BUILTIN_ROOT = path.join(WS_ROOT, 'builtin');
export const BUILTIN_AGENTS_DIR = path.join(BUILTIN_ROOT, 'agents');
export const BUILTIN_SKILLS_DIR = path.join(BUILTIN_ROOT, 'skills');
-// builtin agent 同样目录形态:`<BUILTIN_AGENTS_DIR>/<aid>/agent.json`。
-// runtime 子目录(meta / skills)只存在于 user cloud 侧,builtin 侧不携带。
+// Builtin agents follow the same directory shape:
+// `<BUILTIN_AGENTS_DIR>/<aid>/agent.json`. The runtime sub-directories
+// (meta / skills) only exist on the user cloud side; the builtin side does
+// not carry them.
export const builtinAgentDir = (agentId: string) => path.join(BUILTIN_AGENTS_DIR, agentId);
export const builtinAgentDefinitionFile = (agentId: string) => path.join(builtinAgentDir(agentId), 'agent.json');
@@ -74,9 +78,10 @@ export const userChatsDir = (uid: string) => path.join(userCloudRoot(u
export const userSkillChatDir = (uid: string, sid: string) => path.join(userChatsDir(uid), 'skill', sid);
export const userAgentChatDir = (uid: string, aid: string) => path.join(userChatsDir(uid), 'agent', aid);
-// Group-chat per-conversation附属目录树。`<cid>.jsonl` 在 userChatsDir 同级;
-// 该目录承载群级元数据(members/state/plan)+ 每个 actor 的可见性切片。
-// 详见 features/group_chat/ 与 CLAUDE.md §5。
+// Group-chat per-conversation companion directory tree. `<cid>.jsonl` sits
+// at userChatsDir level alongside this directory; this directory holds
+// group-level metadata (members/state/plan) plus per-actor visibility slices.
+// See features/group_chat/ and CLAUDE.md §5.
export const groupChatDir = (uid: string, cid: string) => path.join(userChatsDir(uid), cid);
export const groupChatMembersFile = (uid: string, cid: string) => path.join(groupChatDir(uid, cid), 'members.json');
export const groupChatStateFile = (uid: string, cid: string) => path.join(groupChatDir(uid, cid), 'state.json');
@@ -93,12 +98,15 @@ export const chatAttachmentDir = (uid: string, cid: string) => path.join(us
export const userSessionsDir = (uid: string) => path.join(userCloudRoot(uid), 'sessions');
export const userSessionFile = (uid: string, sessionId: string) => path.join(userSessionsDir(uid), `${sessionId}.jsonl`);
-// 已整理知识库(contexts 两区的 organized 区)
+// Curated knowledge base (the "organized" region of the historical
+// two-region contexts design).
export const userContextsDir = (uid: string) => path.join(userCloudRoot(uid), 'contexts');
-// 知识库本地向量库(纳入云同步域,与文本内容同目录树;冲突时 mtime 胜出)。
-// 隐藏子目录 `.kb/` 避开 contexts 的用户可见列表(listContextsTree 已过滤 dot)。
-// 运行时 WAL/SHM 旁落文件不纳入同步。
+// Local vector store for the knowledge base (part of the cloud-sync domain,
+// stored in the same directory tree as the text content; on conflict the
+// newer mtime wins). The hidden sub-directory `.kb/` keeps it out of the
+// contexts user-visible listing (listContextsTree filters dotfiles).
+// Runtime WAL/SHM sidecar files are excluded from sync.
export const userKbDir = (uid: string) => path.join(userContextsDir(uid), '.kb');
export const userKbVectorDbPath = (uid: string) => path.join(userKbDir(uid), 'vector.db');
export const userKbConfigPath = (uid: string) => path.join(userKbDir(uid), 'config.json');
@@ -108,18 +116,21 @@ export const userMemoryDir = (uid: string) => path.join(userCloudRoot(uid), 'm
export const userMemoryFile = (uid: string) => path.join(userMemoryDir(uid), 'MEMORY.md');
export const userProfileFile = (uid: string) => path.join(userMemoryDir(uid), 'USER.md');
-// 用户自定义 agents / skills(业务语义 kind='custom';loader 扫描时 cloud 优先)。
-// agent 走目录形态:`agents/<aid>/{agent.json, meta/, skills/}` —— 详见
-// CLAUDE.md §4 + docs/plans/agent-as-directory.md。spec 是用户给的、meta 与
-// skills 是 runtime 动态产物(元认知 + agent 自演进 skill)。
+// User-custom agents / skills (business kind = 'custom'; the loader scans
+// cloud first). Agents use the directory shape
+// `agents/<aid>/{agent.json, meta/, skills/}` — see CLAUDE.md §4 +
+// docs/plans/agent-as-directory.md. The spec comes from the user; meta and
+// skills are runtime-dynamic products (metacognition + the agent's
+// self-evolved skills).
export const userAgentsDir = (uid: string) => path.join(userCloudRoot(uid), 'agents');
export const userSkillsDir = (uid: string) => path.join(userCloudRoot(uid), 'skills');
export const agentDir = (uid: string, agentId: string) => path.join(userAgentsDir(uid), agentId || '_default');
export const agentDefinitionFile = (uid: string, agentId: string) => path.join(agentDir(uid, agentId), 'agent.json');
-// Agent metacognition (per-agent self-assessment + learning strategies)。
-// 写入靠 features/metacognition.ts;reflection-trigger 自动触发 +
-// `metacognition` tool 让 agent 自维护。
+// Agent metacognition (per-agent self-assessment + learning strategies).
+// Writes go through features/metacognition.ts; reflection-trigger fires
+// automatically and the `metacognition` tool lets the agent maintain it
+// itself.
export const agentMetaDir = (uid: string, agentId: string) => path.join(agentDir(uid, agentId), 'meta');
export const agentCompetenceFile = (uid: string, agentId: string) => path.join(agentMetaDir(uid, agentId), 'COMPETENCE.md');
export const agentStrategiesFile = (uid: string, agentId: string) => path.join(agentMetaDir(uid, agentId), 'LEARNING_STRATEGIES.md');
@@ -138,33 +149,39 @@ export const userPreferencesFile = (uid: string) => path.join(userCloudConfigDir
// Same dir + cloud-sync policy as preferences.json; only `false` is stored.
export const userComponentEnabledFile = (uid: string) => path.join(userCloudConfigDir(uid), 'component-enabled.json');
-// ── Local-only per-user (不同步) ─────────────────────────────────────────
+// ── Local-only per-user (never synced) ───────────────────────────────────
-// 本机凭证 + provider 缓存:CORE_AGENT_AUTH_DIR 由 activateUser() pin 到这里,
-// core-agent 的 auth store 与 web-search provider cache 都落在同一目录。
+// Local credentials + provider cache: CORE_AGENT_AUTH_DIR is pinned here by
+// activateUser(); both core-agent's auth store and the web-search provider
+// cache land in this same directory.
export const userLocalConfigDir = (uid: string) => path.join(userLocalRoot(uid), 'config');
export const userAuthProfilesFile = (uid: string) => path.join(userLocalConfigDir(uid), 'auth-profiles.json');
export const userWebSearchCache = (uid: string) => path.join(userLocalConfigDir(uid), 'web-search-cache.json');
export const userReflectionStateFile = (uid: string) => path.join(userLocalConfigDir(uid), 'reflection-state.json');
-// 本地搜索索引(派生数据,reconcile 自愈,永不同步)。
-// 当前只为主对话 + 知识库建持久化倒排;智能体 / 技能本体改成 listAgents /
-// listSkills 内存即查(数据集小、UI 语言切换不用重建索引)。
+// Local search index (derived data, self-healing via reconcile, never synced).
+// Only the main conversation + knowledge base get a persistent inverted
+// index; agents / skills themselves are searched in-memory via listAgents /
+// listSkills (small datasets — switching UI language doesn't require an
+// index rebuild).
export const userSearchDir = (uid: string) => path.join(userLocalRoot(uid), 'search');
export const userContextsIndexPath = (uid: string) => path.join(userSearchDir(uid), 'contexts.idx.json');
export const userChatsIndexPath = (uid: string) => path.join(userSearchDir(uid), 'chats.idx.json');
-// 超大工具输出(>50K 字符)落盘副本:tool_result 里只留 preview + 文件引用,
-// 模型真要看完整原文时调 read_file(path) 拉回。按 session_id 分子目录,
-// 启动期 `sweepToolResults(uid)` 按 mtime 清 7 天以上。永不同步。
+// Spill copy for oversized tool output (>50K chars): the tool_result keeps
+// only a preview + file reference; the model can pull back the full text
+// via read_file(path). One subdirectory per session_id; startup
+// `sweepToolResults(uid)` cleans entries older than 7 days by mtime.
+// Never synced.
export const userToolResultsDir = (uid: string) => path.join(userLocalRoot(uid), 'tool-results');
export const sessionToolResultsDir = (uid: string, sessionId: string) =>
path.join(userToolResultsDir(uid), sessionId);
-// workspace / 外部路径文件的按需预处理缓存(features/file_indexer.ts)。
-// key = sha1(absPath).slice(0,16) 作为子目录名;每条目含 meta.json /
-// chunk.NNN.md / image.jpg / processed.<taskHash>.md 四类产物。
-// 永不同步 —— 源路径是本机绝对路径。
+// On-demand preprocessing cache for workspace / external path files
+// (features/file_indexer.ts). The subdirectory name is
+// sha1(absPath).slice(0,16); each entry contains four kinds of artifacts:
+// meta.json, chunk.NNN.md, image.jpg, and processed.<taskHash>.md.
+// Never synced — the source paths are local-absolute.
export const userFileCacheDir = (uid: string) => path.join(userLocalRoot(uid), 'file_cache');
// Run-history root for local CLI agent dispatches
@@ -188,33 +205,37 @@ export const userLocalCliSessionsDir = (uid: string) =>
export const localCliSessionsFile = (uid: string, cid: string) =>
path.join(userLocalCliSessionsDir(uid), `${cid}.json`);
-// 用户本机工作区选择(features/user_workspace.ts):用户挑的文件夹绝对路径 +
-// 最近列表。绝对路径本机相关,不同步。
+// Per-user local workspace selection (features/user_workspace.ts): the
+// absolute path of the folder the user picked + a recents list. Absolute
+// paths are machine-specific, so this is never synced.
export const userWorkspaceConfigFile = (uid: string) => path.join(userLocalRoot(uid), 'workspace.json');
// ── Build-time resources (shipped with installer, read-only) ────────────
-// 95MB ONNX embedding model 走 electron-builder 的 `extraResources`,
-// 不经 asar;dev / 打包两条路径不同:
+// The 95MB ONNX embedding model ships via electron-builder's `extraResources`
+// (it does not go through asar); dev and packaged builds have different paths:
// dev: PC/resources/embedding-model/
// packed: <app>/Contents/Resources/embedding-model/ (darwin)
// <app>/resources/embedding-model/ (win/linux)
-// 这里故意不依赖 electron.app —— 便于单测/脚本环境使用。`process.resourcesPath`
-// 只在 Electron runtime 存在;dev 下走仓库布局。
+// We deliberately don't depend on electron.app here — keeps the function
+// usable from unit tests / scripts. `process.resourcesPath` only exists in
+// the Electron runtime; in dev we fall back to the repo layout.
export function embeddingModelDir(): string {
const rp = (process as unknown as { resourcesPath?: string }).resourcesPath;
if (rp && !rp.includes(`${path.sep}node_modules${path.sep}electron${path.sep}`)) {
- // 打包态:process.resourcesPath 指向 app.Resources
+ // Packaged: process.resourcesPath points to app.Resources.
return path.join(rp, 'embedding-model');
}
- // dev 态(Electron 跑 electron-stub 时 resourcesPath 指向 electron 自身,
- // 上面那一行会过滤掉;其它 tsx / node 脚本里 resourcesPath 不存在)。
+ // Dev (when Electron runs electron-stub, resourcesPath points to electron
+ // itself — filtered out by the line above; in other tsx / node scripts
+ // resourcesPath simply does not exist).
return path.join(PC_ROOT, 'resources', 'embedding-model');
}
// ── Builtin source dirs (shipped, read-only in packaged app) ─────────────
-// 源码全部收在 SRC_ROOT 下,`builtin/` 也随之;打包时 electron-builder 按
-// `src/builtin/**` glob 打入 asar。用户 override ORKAS_BUILTIN_ROOT 时仍
-// 用原样,不经 SRC_ROOT。
+// All source lives under SRC_ROOT, and `builtin/` follows; electron-builder
+// globs `src/builtin/**` into asar at packaging time. When the user
+// overrides ORKAS_BUILTIN_ROOT, the path is used as-is and does not go
+// through SRC_ROOT.
export const BUILTIN_SKILLS_SOURCE = process.env.ORKAS_BUILTIN_ROOT
? path.join(path.resolve(process.env.ORKAS_BUILTIN_ROOT), 'skills')
: path.join(SRC_ROOT, 'builtin', 'skills');
@@ -231,7 +252,8 @@ export const DEFAULT_USER_WORKSPACE = process.env.ORKAS_WORKSPACE_ROOT
: path.join(PC_ROOT, 'userWorkSpace');
// ── Init: mkdir the top-level skeleton ───────────────────────────────────
-// 只建顶层公共目录;uid 子目录由 `features/users.activateUser(uid)` 按需 mkdir。
+// Only the top-level shared directories are created here; per-uid sub-trees
+// are mkdir'd on demand by `features/users.activateUser(uid)`.
export function ensureTopLevelLayout(): void {
for (const d of [LOGS_DIR, BUILTIN_AGENTS_DIR, BUILTIN_SKILLS_DIR, DEFAULT_USER_WORKSPACE]) {
fs.mkdirSync(d, { recursive: true });
@@ -242,7 +264,8 @@ export function ensureTopLevelLayout(): void {
ensureTopLevelLayout();
// ── Per-user layout (called by activateUser) ─────────────────────────────
-// 单 uid 目录骨架:所有 `<uid>/cloud/*` + `<uid>/local/*` 子目录。
+// Single-uid directory skeleton: every `<uid>/cloud/*` + `<uid>/local/*`
+// sub-directory.
export function ensureUserLayout(uid: string): void {
const dirs = [
userChatsDir(uid),
@@ -253,8 +276,9 @@ export function ensureUserLayout(uid: string): void {
userMemoryDir(uid),
userAgentsDir(uid),
userSkillsDir(uid),
- // userMetaDir 已废弃 —— per-agent meta 落 `agents/<aid>/meta/` 子目录,
- // agent 创建时按需 mkdir,不需要顶层占位。
+ // userMetaDir is deprecated — per-agent meta now lands in the
+ // `agents/<aid>/meta/` sub-directory, mkdir'd on demand at agent
+ // creation time, so no top-level placeholder is required.
userCloudConfigDir(uid),
userLocalConfigDir(uid),
userSearchDir(uid),
diff --git a/src/main/util/migrate-agent-layout.ts b/src/main/util/migrate-agent-layout.ts
index f799101f..eaca6410 100644
--- a/src/main/util/migrate-agent-layout.ts
+++ b/src/main/util/migrate-agent-layout.ts
@@ -1,23 +1,28 @@
/**
- * 一次性数据迁移:把每个 agent 的 spec(原 `<uid>/cloud/agents/<aid>.json`)+
- * 元认知输出(原 `<uid>/cloud/meta/<aid>/{COMPETENCE,LEARNING_STRATEGIES}.md`)
- * 搬到统一的 agent 目录 `<uid>/cloud/agents/<aid>/`:
+ * One-shot data migration: move each agent's spec (was
+ * `<uid>/cloud/agents/<aid>.json`) plus its metacognition output (was
+ * `<uid>/cloud/meta/<aid>/{COMPETENCE,LEARNING_STRATEGIES}.md`) into the
+ * unified agent directory `<uid>/cloud/agents/<aid>/`:
*
* <uid>/cloud/agents/<aid>/
- * ├── agent.json ← 来自 <uid>/cloud/agents/<aid>.json
+ * ├── agent.json ← from <uid>/cloud/agents/<aid>.json
* └── meta/
- * ├── COMPETENCE.md ← 来自 <uid>/cloud/meta/<aid>/COMPETENCE.md
- * └── LEARNING_STRATEGIES.md ← 同上
+ * ├── COMPETENCE.md ← from <uid>/cloud/meta/<aid>/COMPETENCE.md
+ * └── LEARNING_STRATEGIES.md ← same
*
- * 最后删空的顶层 `meta/` 目录。
+ * Finally remove the now-empty top-level `meta/` directory.
*
- * 详见 docs/plans/agent-as-directory.md。
+ * See docs/plans/agent-as-directory.md for the full design.
*
- * 设计要点:
- * - 启动期 idempotent:`<uid>/local/.migrations` 盖章 `agent-as-directory-v1` 防重跑
- * - 旧 `<aid>.json` 与新 `<aid>/agent.json` 共存时优先认新格式(说明上一次跑了一半)
- * - 找不到对应 agent 的 meta 子目录会 log.warn 但不阻塞迁移
- * - 迁移失败任意一项不会卡住别的;盖章只在整个流程跑完后落盘
+ * Design notes:
+ * - Idempotent at startup: stamps `<uid>/local/.migrations` with
+ * `agent-as-directory-v1` to prevent re-runs.
+ * - When the old `<aid>.json` coexists with the new `<aid>/agent.json`
+ * (last run was interrupted), the new format wins.
+ * - A missing meta sub-directory for an agent emits log.warn but does not
+ * block the migration.
+ * - Per-item failures don't block the rest; the stamp is only written
+ * after the whole flow completes.
*/
import * as fs from 'node:fs';
@@ -31,8 +36,8 @@ const log = createLogger('migrate');
const MIGRATION_TAG = 'agent-as-directory-v1';
function migrationsFile(uid: string): string {
- // userLocalConfigDir = <uid>/local/config;上一层就是 <uid>/local/。
- // 与 migrate-session-ids 共用同一个 .migrations 文件,多 tag 一行一条。
+ // userLocalConfigDir = <uid>/local/config; one level up is <uid>/local/.
+ // Shares the .migrations file with migrate-session-ids — one tag per line.
return path.join(path.dirname(userLocalConfigDir(uid)), '.migrations');
}
@@ -70,7 +75,7 @@ export function migrateAgentLayout(uid: string): MigrationStats {
const agentsRoot = userAgentsDir(uid);
const oldMetaRoot = path.join(userCloudRoot(uid), 'meta');
- // 1. 扫 agents/<aid>.json,搬到 agents/<aid>/agent.json
+ // 1. Scan agents/<aid>.json and move it to agents/<aid>/agent.json
if (fs.existsSync(agentsRoot)) {
let entries: fs.Dirent[] = [];
try {
@@ -85,7 +90,8 @@ export function migrateAgentLayout(uid: string): MigrationStats {
const newDir = path.join(agentsRoot, aid);
const newFile = path.join(newDir, 'agent.json');
if (fs.existsSync(newFile)) {
- // 上一次跑了一半 / 用户手动建过新格式 → 认新格式,删旧 flat file
+ // Previous run was interrupted, or the user hand-created the new
+ // format → keep the new format, drop the old flat file.
try {
fs.unlinkSync(oldFile);
log.info(`migrate: dropped redundant flat ${oldFile} (new agent.json already exists)`);
@@ -106,7 +112,8 @@ export function migrateAgentLayout(uid: string): MigrationStats {
}
}
- // 2. 扫旧的 cloud/meta/<aid>/,搬到 cloud/agents/<aid>/meta/
+ // 2. Scan the old cloud/meta/<aid>/ tree and move it to
+ // cloud/agents/<aid>/meta/.
if (fs.existsSync(oldMetaRoot)) {
let entries: fs.Dirent[] = [];
try {
@@ -132,15 +139,16 @@ export function migrateAgentLayout(uid: string): MigrationStats {
fs.renameSync(src, dst);
stats.metaMoved += 1;
}
- // src 空了 → 删 src 目录
+ // src is now empty → remove the src directory.
try { fs.rmdirSync(srcDir); }
- catch { /* 残留留着,下一次再清 */ }
+ catch { /* leave the leftover for the next run to clean up */ }
} catch (err) {
log.warn(`migrate: meta agent ${aid} failed: ${(err as Error).message}`);
stats.warnings += 1;
}
}
- // 顶层 meta/ 整体删除(rmdirSync 只在空时成功,有残留会保留;无碍)
+ // Remove the top-level meta/ directory wholesale (rmdirSync only succeeds
+ // when empty; leftovers are kept silently — fine).
try { fs.rmdirSync(oldMetaRoot); }
catch { /* keep */ }
}
diff --git a/src/main/util/migrate-session-ids.ts b/src/main/util/migrate-session-ids.ts
index 3b37a12f..08aeb0c6 100644
--- a/src/main/util/migrate-session-ids.ts
+++ b/src/main/util/migrate-session-ids.ts
@@ -1,19 +1,27 @@
/**
- * 一次性数据迁移:把 session jsonl 文件名上的历史品牌前缀剥掉。
+ * One-shot data migration: strip the legacy brand prefix from session jsonl
+ * filenames.
*
- * 旧版本曾把 session_id 写成 `<brand>-<uid>-<kind>-<tail>` 的形式;当前规范
- * 统一为 `<uid>-<kind>-<tail>`(无品牌前缀,避免任何分叉/改名再断历史)。
+ * Older builds wrote session_ids as `<brand>-<uid>-<kind>-<tail>`; the
+ * current canonical form is `<uid>-<kind>-<tail>` (no brand prefix, so any
+ * future fork or rename can't break history again).
*
- * 迁移策略:
- * 1. 扫 `<uid>/cloud/sessions/*.jsonl`
- * 2. 命中 `^<legacy-prefix>-<uid>-(.+)\.jsonl$` 重命名为 `<uid>-$1.jsonl`
- * 3. 已经是新格式的 → 跳过
- * 4. 同名冲突(极罕见,理论上同一 sid 不会两份)→ log.warn 后跳过,让人工处理
- * 5. `<uid>/local/.migrations` 写一行 `decouple-session-id-from-brand-v1` 防重跑
+ * Migration strategy:
+ * 1. Scan `<uid>/cloud/sessions/*.jsonl`
+ * 2. Match `^<legacy-prefix>-<uid>-(.+)\.jsonl$` and rename to
+ * `<uid>-$1.jsonl`
+ * 3. Already-new-format files are skipped
+ * 4. Same-name conflicts (extremely rare — in theory there should not
+ * be two copies of one sid) are log.warn'd and skipped for manual
+ * handling
+ * 5. `<uid>/local/.migrations` is stamped with a single line
+ * `decouple-session-id-from-brand-v1` to prevent re-runs
*
- * 历史 kind(`organizer` / `sub` / `conv`)不在白名单,但迁移仅看前缀不看 kind,
- * 所以这些老会话也会被一并去前缀。它们的 jsonl 内容仍然有效(用户可以打开
- * 历史群聊看记录),只是新代码不会再生成这种 kind。
+ * Legacy kinds (`organizer` / `sub` / `conv`) aren't on the whitelist, but
+ * since the migration only looks at the prefix and not the kind, those
+ * sessions also get the prefix stripped. Their jsonl content is still
+ * valid (users can open old group-chat history); new code just no
+ * longer generates those kinds.
*/
import * as fs from 'node:fs';
diff --git a/src/main/util/tool-result-cap.ts b/src/main/util/tool-result-cap.ts
index a7554206..6c913a5b 100644
--- a/src/main/util/tool-result-cap.ts
+++ b/src/main/util/tool-result-cap.ts
@@ -1,20 +1,21 @@
/**
- * Tool-result size cap + oversized-output persistence (仿 Claude Code 的
- * `maxResultSizeChars` + `<persisted-output>` 机制)。
+ * Tool-result size cap + oversized-output persistence (mirrors Claude Code's
+ * `maxResultSizeChars` + `<persisted-output>` mechanism).
*
- * 每个 AgentTool 在 runner.ts 工具组装的最后一步统一过 `wrapToolWithCap`。
- * 三级处理:
- * len ≤ maxChars → 原样透传
- * maxChars < len ≤ PERSIST → 就地截断 + 尾标
- * len > PERSIST → 落盘到 tool-results/<sid>/<name>.<id>.txt,
- * tool_result 改写成 <persisted-output> 包
- * 的 preview + 引用;模型真要看原文调
- * read_file(path) 拉回
+ * Every AgentTool is wrapped by `wrapToolWithCap` as the last step of tool
+ * assembly in runner.ts. Three-tier handling:
+ * len ≤ maxChars → pass through unchanged
+ * maxChars < len ≤ PERSIST → in-place truncation + trailing marker
+ * len > PERSIST → spill to tool-results/<sid>/<name>.<id>.txt,
+ * rewrite tool_result into a <persisted-output>
+ * wrapper (preview + reference); the model can
+ * pull the original back via read_file(path)
*
- * Read-类工具(`read_file` / `kb_read`)上限 = Infinity,装饰器直接返回原工具
- * 不介入 —— 这些输出的文件内容模型可能反复核对,不能被清掉。
+ * Read-class tools (`read_file` / `kb_read`) have a cap of Infinity and the
+ * decorator returns the original tool untouched — the model may re-inspect
+ * file content repeatedly, so it must not be wiped.
*
- * 纯函数 util:只用 Node stdlib,不 import features/ / model/。
+ * Pure-function util: Node stdlib only, never imports features/ or model/.
*/
import * as fs from 'fs';
@@ -27,13 +28,15 @@ const log = createLogger('util/tool-result-cap');
// ── Config ───────────────────────────────────────────────────────────────
-/** 每工具允许回灌上下文的最大字符数。表外走 DEFAULT_MAX_RESULT_CHARS。
- * Infinity = 豁免装饰器,直接透传。常量照抄 Claude Code 源码:
+/** Per-tool maximum characters allowed back into the context. Tools not in the
+ * table use DEFAULT_MAX_RESULT_CHARS.
+ * Infinity = decorator exempt, pass-through. Constants copied from Claude Code:
* src/tools/BashTool/BashTool.tsx:424 = 30_000
* src/tools/GrepTool/GrepTool.ts:164 = 20_000
* src/tools/FileReadTool/FileReadTool.ts:342 = Infinity
- * 其它 = 100_000
- * PDF / write_file 设小值因为它们只返回路径/状态字符串,没必要给 100K 余量。
+ * others = 100_000
+ * PDF / write_file get small values because they only return path/status
+ * strings — no point giving them 100K headroom.
*/
export const MAX_RESULT_CHARS_BY_TOOL: Record<string, number> = {
read_file: Infinity,
@@ -52,35 +55,41 @@ export const MAX_RESULT_CHARS_BY_TOOL: Record<string, number> = {
export const DEFAULT_MAX_RESULT_CHARS = 100_000;
-/** 超过此阈值触发落盘(仿 Claude Code src/constants/toolLimits.ts:13 = 50_000)。
- * 阈值 < maxChars 的工具(bash 30K / grep 20K)永远不会走落盘分支——
- * 它们在 maxChars 就截断了。只有 maxChars ≥ 50K 的工具(web_fetch 100K 等)
- * 才有机会落盘。 */
+/** Threshold above which we spill to disk (mirrors Claude Code
+ * src/constants/toolLimits.ts:13 = 50_000).
+ * Tools whose maxChars < threshold (bash 30K / grep 20K) never reach the
+ * spill branch — they get truncated at maxChars. Only tools with
+ * maxChars ≥ 50K (web_fetch 100K etc.) can ever spill. */
export const PERSIST_THRESHOLD = 50_000;
-/** 落盘后回灌给模型的 preview:开头 + 结尾(中间用 `[N chars omitted]` 占位)。
- * 2000 / 500 的比例偏向头部——tool 输出大多前缀信息量密度高。 */
+/** Preview returned to the model after a spill: head + tail (with
+ * `[N chars omitted]` placeholder in the middle). The 2000 / 500 ratio
+ * favors the head — tool outputs usually have higher information density
+ * near the start. */
const PREVIEW_HEAD = 2000;
const PREVIEW_TAIL = 500;
// ── Wrapping ─────────────────────────────────────────────────────────────
export interface WrapOpts {
- /** 该工具的 maxChars 上限。Infinity → 装饰器直接返回原工具。 */
+ /** maxChars cap for this tool. Infinity → decorator returns the original
+ * tool directly. */
maxChars: number;
- /** 落盘目录(一般是 `sessionToolResultsDir(uid, sessionId)`)。
- * 装饰器不关心 uid / sessionId,调用方组装好传进来。
- * 目录按需 mkdir,不预先强制存在。 */
+ /** Spill directory (typically `sessionToolResultsDir(uid, sessionId)`).
+ * The decorator does not care about uid / sessionId; the caller assembles
+ * the path and passes it in. The directory is mkdir'd on demand, not
+ * required to exist beforehand. */
toolResultsDir: string;
}
export function wrapToolWithCap(tool: AgentTool, opts: WrapOpts): AgentTool {
- // Infinity = 豁免(read_file / kb_read):模型可能对同一文件内容反复核对,
- // 不能被截 / 落盘。
+ // Infinity = exempt (read_file / kb_read): the model may repeatedly
+ // re-check the same file contents, so they must not be truncated / spilled.
if (!Number.isFinite(opts.maxChars)) return tool;
- // per-session 目录的 basename 正好是 session_id —— 不额外传 sessionId
- // 参数保持装饰器接口最小,日志里又能标明来源。
+ // The per-session directory's basename IS the session_id — keeping the
+ // decorator interface minimal (no extra sessionId parameter) while still
+ // letting the logs identify the source.
const sid = path.basename(opts.toolResultsDir);
return {
@@ -93,28 +102,32 @@ export function wrapToolWithCap(tool: AgentTool, opts: WrapOpts): AgentTool {
const len = content.length;
if (len <= opts.maxChars) return result;
- // 错误结果:只截断不落盘 —— 错误 stderr 值得回灌一段给模型定位,但整条
- // 大文本落盘成孤儿文件没价值。
+ // Error result: truncate only, never spill — error stderr is worth
+ // feeding back a slice for the model to triage, but spilling huge
+ // error text as orphan files has no value.
if (result.isError) {
log.info(`truncated (error) tool=${tool.name} session=${sid} len=${len} cap=${opts.maxChars} removed=${len - opts.maxChars}`);
return { ...result, content: truncate(content, opts.maxChars, tool.name) };
}
- // 正常结果但超阈值未到落盘线:就地截断 + 尾标。
+ // Normal result over cap but below the spill threshold: in-place
+ // truncation + trailing marker.
if (len <= PERSIST_THRESHOLD) {
log.info(`truncated tool=${tool.name} session=${sid} len=${len} cap=${opts.maxChars} removed=${len - opts.maxChars}`);
return { ...result, content: truncate(content, opts.maxChars, tool.name) };
}
- // 正常结果超过落盘线:原文落盘,返回 <persisted-output> 引用。
+ // Normal result over the spill threshold: spill the full text and
+ // return a <persisted-output> reference.
try {
const absPath = persistToolResult(opts.toolResultsDir, tool.name, content);
log.info(`persisted tool=${tool.name} session=${sid} size=${len} path=${absPath}`);
return { ...result, content: buildPersistedOutputMarker(absPath, tool.name, content) };
} catch (err) {
- // 磁盘写入失败降级为就地截断 —— 模型至少拿到前 maxChars 字符,
- // 比彻底截断更有用。warn 级别是因为这是实际的 I/O 异常(磁盘满 /
- // 权限丢),用户能从日志里追根溯源。
+ // Disk-write failure degrades to in-place truncation — the model
+ // at least gets the first maxChars characters, which is more useful
+ // than a hard cut. warn level because this is a real I/O exception
+ // (disk full / permission lost) and the user can trace it from logs.
log.warn(`persist failed, falling back to truncate tool=${tool.name} session=${sid} size=${len}: ${(err as Error).message}`);
return {
...result,
@@ -169,9 +182,10 @@ export function buildPersistedOutputMarker(
// ── Sweep ────────────────────────────────────────────────────────────────
-/** 启动期清扫:删除 mtime 超过 `maxAgeDays` 的子目录 / 文件。Best-effort
- * (nothrow):目录不存在、某个文件读不到 stat,都安静跳过。每个 uid
- * 激活时调一次(users.ts::activateUser)。 */
+/** Startup sweep: deletes sub-directories / files whose mtime is older than
+ * `maxAgeDays`. Best-effort (nothrow): missing directory or unstattable
+ * entries are silently skipped. Called once per uid activation
+ * (users.ts::activateUser). */
export function sweepToolResults(userToolResultsDir: string, maxAgeDays = 7): void {
if (!fs.existsSync(userToolResultsDir)) return;
const cutoffMs = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 7a5cc14f..4abee743 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -1,5 +1,5 @@
<!doctype html>
-<html lang="zh-CN">
+<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
@@ -13,33 +13,33 @@
<img class="logo-icon" src="../resources/icons/logo.png" alt="" draggable="false" />
<div class="logo-text">Orkas</div>
</div>
- <button class="sidebar-search-btn" id="sidebar-search-btn" data-i18n-title="sidebar.search_title" title="全局搜索 (⌘K)">
+ <button class="sidebar-search-btn" id="sidebar-search-btn" data-i18n-title="sidebar.search_title" title="Global search (⌘K)">
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="11" cy="11" r="7"></circle>
<path d="m21 21-4.3-4.3"></path>
</svg>
- <span class="sidebar-search-label" data-i18n="sidebar.search">搜索</span>
+ <span class="sidebar-search-label" data-i18n="sidebar.search">Search</span>
<span class="sidebar-search-kbd">⌘K</span>
</button>
<div class="sidebar-actions">
- <button class="sidebar-btn primary" id="new-chat-btn" data-i18n="sidebar.new_chat">总指挥</button>
- <button class="sidebar-btn" id="agents-btn" data-i18n="sidebar.agents">智能体</button>
- <button class="sidebar-btn" id="skills-btn" data-i18n="sidebar.skills">技能库</button>
- <button class="sidebar-btn" id="contexts-btn" data-i18n="sidebar.contexts">知识库</button>
+ <button class="sidebar-btn primary" id="new-chat-btn" data-i18n="sidebar.new_chat">Commander</button>
+ <button class="sidebar-btn" id="agents-btn" data-i18n="sidebar.agents">Agents</button>
+ <button class="sidebar-btn" id="skills-btn" data-i18n="sidebar.skills">Skills</button>
+ <button class="sidebar-btn" id="contexts-btn" data-i18n="sidebar.contexts">Knowledge</button>
</div>
<div class="sidebar-section">
- <div class="sidebar-section-title" data-i18n="sidebar.conversations">对话记录</div>
+ <div class="sidebar-section-title" data-i18n="sidebar.conversations">Conversations</div>
<div class="conversation-list" id="conversation-list">
- <div class="conv-empty" data-i18n="sidebar.conv_empty">暂无对话</div>
+ <div class="conv-empty" data-i18n="sidebar.conv_empty">No conversations yet</div>
</div>
</div>
<div class="sidebar-footer-actions">
- <button class="sidebar-footer-btn" id="settings-btn" data-i18n-title="sidebar.settings_title" title="设置">
+ <button class="sidebar-footer-btn" id="settings-btn" data-i18n-title="sidebar.settings_title" title="Settings">
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="3"></circle>
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.01a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h.01a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.01a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
</svg>
- <span data-i18n="sidebar.settings">设置</span>
+ <span data-i18n="sidebar.settings">Settings</span>
</button>
</div>
</aside>
@@ -48,8 +48,8 @@
<!-- New Chat Landing -->
<section class="panel active" id="panel-new-chat">
<div class="new-chat-center">
- <div class="new-chat-title" data-i18n="new_chat.title">指挥智能体为你干活</div>
- <div class="new-chat-subtitle" data-i18n="new_chat.subtitle">输入你的问题或任务</div>
+ <div class="new-chat-title" data-i18n="new_chat.title">Command agents to get things done</div>
+ <div class="new-chat-subtitle" data-i18n="new_chat.subtitle">Type your question or task</div>
<div class="new-chat-input-wrapper">
<div class="new-chat-input-area">
<!-- Floats above the input box. Attachments + workspace chip
@@ -60,20 +60,20 @@
<div class="chat-attachments" id="new-chat-attachments" style="display:none"></div>
<div class="chat-input-toolbar"></div>
</div>
- <textarea id="new-chat-input" data-i18n-placeholder="new_chat.input_placeholder" placeholder="输入消息..." rows="2"></textarea>
+ <textarea id="new-chat-input" data-i18n-placeholder="new_chat.input_placeholder" placeholder="Type a message..." rows="2"></textarea>
<div class="chat-bottom-bar">
- <button type="button" class="chat-attach-btn" id="new-chat-attach-btn" data-i18n-title="new_chat.attach_title" title="上传附件(文本/PDF/Word/图片)">+</button>
- <button type="button" class="chat-recipient-chip" id="new-chat-recipient-chip" data-i18n-title="chat.recipient_picker_title" title="切换接收者">
- <span class="chat-recipient-prefix" data-i18n="chat.recipient_label">给:</span>
- <span class="chat-recipient-name" id="new-chat-recipient-name" data-i18n="chat.recipient_commander">指挥官</span>
+ <button type="button" class="chat-attach-btn" id="new-chat-attach-btn" data-i18n-title="new_chat.attach_title" title="Upload attachment (text / PDF / Word / image / video)">+</button>
+ <button type="button" class="chat-recipient-chip" id="new-chat-recipient-chip" data-i18n-title="chat.recipient_picker_title" title="Switch recipient (commander / agent)">
+ <span class="chat-recipient-prefix" data-i18n="chat.recipient_label">To: </span>
+ <span class="chat-recipient-name" id="new-chat-recipient-name" data-i18n="chat.recipient_commander">Commander</span>
</button>
<div class="chat-skill-chip" id="new-chat-skill-chip" data-target="new-chat" style="display:none">
<span class="chip-label"></span>
- <span class="chip-close" data-i18n-title="chat.chip_remove_title" title="移除">×</span>
+ <span class="chip-close" data-i18n-title="chat.chip_remove_title" title="Remove">×</span>
</div>
<input type="file" id="new-chat-attach-input" multiple style="display:none"
accept=".md,.markdown,.txt,.csv,.tsv,.json,.yaml,.yml,.log,.pdf,.docx,.png,.jpg,.jpeg,.webp,.gif,text/plain,text/markdown,text/csv,application/json,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/png,image/jpeg,image/webp,image/gif" />
- <button id="new-chat-send-btn" class="chat-send-btn" data-i18n-title="new_chat.send_title" title="发送">
+ <button id="new-chat-send-btn" class="chat-send-btn" data-i18n-title="new_chat.send_title" title="Send">
<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"></path></svg>
</button>
</div>
@@ -86,13 +86,13 @@
<section class="panel" id="panel-conversation">
<div class="chat-container">
<div id="chat-history" class="chat-history">
- <div class="empty" data-i18n="chat.empty">无对话记录...</div>
+ <div class="empty" data-i18n="chat.empty">No messages yet...</div>
</div>
<div class="chat-input-wrapper">
<div class="chat-queue" id="chat-queue" style="display:none">
<div class="chat-queue-header">
- <span class="chat-queue-label"><span data-i18n="chat.queue_label">待发送</span> <span class="chat-queue-count" id="chat-queue-count">0</span></span>
- <span class="chat-queue-hint" data-i18n="chat.queue_hint">可拖动排序 · 编辑 · 删除</span>
+ <span class="chat-queue-label"><span data-i18n="chat.queue_label">Queued</span> <span class="chat-queue-count" id="chat-queue-count">0</span></span>
+ <span class="chat-queue-hint" data-i18n="chat.queue_hint">Drag to reorder · Edit · Delete</span>
</div>
<div class="chat-queue-list" id="chat-queue-list"></div>
</div>
@@ -107,8 +107,8 @@
Expanded body opens UPWARD (bottom: 100%) over the
chat-history. See modules/plan-rail.js. -->
<div id="plan-rail" class="plan-rail" style="display:none">
- <div class="plan-rail-header" data-i18n-title="plan.toggle_title" title="折叠/展开">
- <span class="plan-rail-title">📋 <span data-i18n="plan.title">执行计划</span></span>
+ <div class="plan-rail-header" data-i18n-title="plan.toggle_title" title="Collapse / Expand">
+ <span class="plan-rail-title">📋 <span data-i18n="plan.title">Execution Plan</span></span>
<span class="plan-rail-progress" id="plan-rail-progress"></span>
<span class="plan-rail-toggle" id="plan-rail-toggle">▴</span>
</div>
@@ -118,20 +118,20 @@
<div class="chat-input-toolbar"></div>
</div>
<div class="chat-quote-preview" id="chat-quote-preview" style="display:none"></div>
- <textarea id="chat-input" data-i18n-placeholder="chat.input_placeholder" placeholder="继续对话..." rows="2"></textarea>
+ <textarea id="chat-input" data-i18n-placeholder="chat.input_placeholder" placeholder="Continue the conversation..." rows="2"></textarea>
<div class="chat-bottom-bar">
- <button type="button" class="chat-attach-btn" id="chat-attach-btn" data-i18n-title="chat.attach_title" title="上传附件(文本/PDF/Word/图片)">+</button>
- <button type="button" class="chat-recipient-chip" id="chat-recipient-chip" data-i18n-title="chat.recipient_picker_title" title="切换接收者">
- <span class="chat-recipient-prefix" data-i18n="chat.recipient_label">给:</span>
- <span class="chat-recipient-name" id="chat-recipient-name" data-i18n="chat.recipient_commander">指挥官</span>
+ <button type="button" class="chat-attach-btn" id="chat-attach-btn" data-i18n-title="chat.attach_title" title="Upload attachment (text / PDF / Word / image / video)">+</button>
+ <button type="button" class="chat-recipient-chip" id="chat-recipient-chip" data-i18n-title="chat.recipient_picker_title" title="Switch recipient (commander / agent)">
+ <span class="chat-recipient-prefix" data-i18n="chat.recipient_label">To: </span>
+ <span class="chat-recipient-name" id="chat-recipient-name" data-i18n="chat.recipient_commander">Commander</span>
</button>
<div class="chat-skill-chip" id="chat-skill-chip" data-target="conversation" style="display:none">
<span class="chip-label"></span>
- <span class="chip-close" data-i18n-title="chat.chip_remove_title" title="移除">×</span>
+ <span class="chip-close" data-i18n-title="chat.chip_remove_title" title="Remove">×</span>
</div>
<input type="file" id="chat-attach-input" multiple style="display:none"
accept=".md,.markdown,.txt,.csv,.tsv,.json,.yaml,.yml,.log,.pdf,.docx,.png,.jpg,.jpeg,.webp,.gif,text/plain,text/markdown,text/csv,application/json,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/png,image/jpeg,image/webp,image/gif" />
- <button id="chat-send-btn" class="chat-send-btn" data-i18n-title="chat.send_title" title="发送">
+ <button id="chat-send-btn" class="chat-send-btn" data-i18n-title="chat.send_title" title="Send">
<svg class="send-icon" viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"></path></svg>
<svg class="stop-icon" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"></rect></svg>
</button>
@@ -146,19 +146,19 @@
<!-- Grid view (default) -->
<div class="skills-grid-view" id="skills-grid-view">
<div class="skills-grid-header">
- <span data-i18n="skills.title">技能库</span>
- <button class="btn btn-sm" id="create-skill-btn" data-i18n="skills.add">+ 添加</button>
+ <span data-i18n="skills.title">Skills</span>
+ <button class="btn btn-sm" id="create-skill-btn" data-i18n="skills.add">+ Add</button>
</div>
<div class="skills-grid-scroll">
<div class="skills-group" id="skills-grid-custom-group" style="display:none">
- <div class="skills-group-label" data-i18n="skills.custom_group">自定义</div>
+ <div class="skills-group-label" data-i18n="skills.custom_group">Custom</div>
<div class="skills-grid" id="skills-grid-custom"></div>
</div>
<div class="skills-group" id="skills-grid-builtin-group" style="display:none">
- <div class="skills-group-label" data-i18n="skills.builtin_group">内置</div>
+ <div class="skills-group-label" data-i18n="skills.builtin_group">Built-in</div>
<div class="skills-grid" id="skills-grid-builtin"></div>
</div>
- <div class="skills-empty" id="skills-empty" data-i18n="skills.empty">暂无技能</div>
+ <div class="skills-empty" id="skills-empty" data-i18n="skills.empty">No skills yet</div>
</div>
</div>
@@ -168,7 +168,7 @@
<div class="skills-detail-breadcrumb">
<button type="button" class="skills-back-btn" id="skills-back-btn">
<span aria-hidden="true">←</span>
- <span data-i18n="skills.back">返回技能库</span>
+ <span data-i18n="skills.back">Back to skills</span>
</button>
</div>
<div class="skills-detail-content" id="skills-detail-content" style="display:none">
@@ -176,32 +176,32 @@
<h1 class="skills-doc-title" id="skills-detail-name" data-editable="false"></h1>
<span class="skills-doc-source" id="skills-detail-source"></span>
<div class="skills-doc-actions" id="skills-detail-actions">
- <button class="btn-icon-use" id="skill-use-btn" data-i18n-title="skills.use_tooltip" data-i18n-aria-label="skills.use_tooltip" aria-label="使用">
+ <button class="btn-icon-use" id="skill-use-btn" data-i18n-title="skills.use_tooltip" data-i18n-aria-label="skills.use_tooltip" aria-label="Use this skill">
<svg class="icon-play" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><polygon points="5,3 5,13 13,8" fill="currentColor"/></svg>
</button>
- <button class="btn btn-sm" id="skill-edit-btn" data-i18n="skills.edit">编辑</button>
- <button class="btn btn-sm" id="skill-enabled-btn" data-i18n="component.disable">禁用</button>
- <button class="btn btn-sm" id="skill-promote-btn" style="display:none" data-i18n="skills.promote_to_builtin">设为内置</button>
- <button class="btn btn-sm btn-danger" id="skill-delete-btn" data-i18n="skills.delete">删除</button>
+ <button class="btn btn-sm" id="skill-edit-btn" data-i18n="skills.edit">Edit</button>
+ <button class="btn btn-sm" id="skill-enabled-btn" data-i18n="component.disable">Disable</button>
+ <button class="btn btn-sm" id="skill-promote-btn" style="display:none" data-i18n="skills.promote_to_builtin">Make built-in (dev)</button>
+ <button class="btn btn-sm btn-danger" id="skill-delete-btn" data-i18n="skills.delete">Delete</button>
</div>
</div>
<section class="skills-doc-section" id="skills-section-summary">
- <h3 class="skills-doc-section-label" data-i18n="skills.label_summary">简介</h3>
+ <h3 class="skills-doc-section-label" data-i18n="skills.label_summary">Summary</h3>
<div class="skills-doc-section-body" id="skills-detail-summary"></div>
</section>
<section class="skills-doc-section" id="skills-section-extra" style="display:none">
- <h3 class="skills-doc-section-label" data-i18n="skills.label_extra">其他属性</h3>
+ <h3 class="skills-doc-section-label" data-i18n="skills.label_extra">Other attributes</h3>
<div class="skills-doc-section-body" id="skills-detail-extra"></div>
</section>
<section class="skills-doc-section skills-usage-section">
<h3 class="skills-doc-section-label skills-usage-label">
- <span data-i18n="skills.label_usage">使用说明</span>
+ <span data-i18n="skills.label_usage">Usage</span>
<button type="button" class="skills-source-toggle" id="skills-source-toggle" aria-expanded="false">
<span class="skills-source-toggle-caret" aria-hidden="true">▶</span>
- <span data-i18n="skills.label_source">查看源码</span>
+ <span data-i18n="skills.label_source">View source</span>
</button>
</h3>
<div class="skills-source-panel" id="skills-source-panel" style="display:none">
@@ -214,19 +214,19 @@
<!-- Inline chat for custom skill editing -->
<div class="skills-chat-col" id="skills-chat-col" style="display:none">
<div class="skills-chat-toolbar">
- <button id="skill-chat-clear-btn" class="skill-chat-link" data-i18n-title="skills.clear_chat_title" title="清空当前技能的对话记录" data-i18n="skills.clear_chat">清空</button>
+ <button id="skill-chat-clear-btn" class="skill-chat-link" data-i18n-title="skills.clear_chat_title" title="Clear the edit chat for this skill" data-i18n="skills.clear_chat">Clear</button>
</div>
<div class="skills-chat-messages" id="skills-chat-messages"></div>
<div class="chat-queue" id="skills-chat-queue" style="display:none">
<div class="chat-queue-header">
- <span class="chat-queue-label"><span data-i18n="chat.queue_label">待发送</span> <span class="chat-queue-count" id="skills-chat-queue-count">0</span></span>
- <span class="chat-queue-hint" data-i18n="chat.queue_hint">可拖动排序 · 编辑 · 删除</span>
+ <span class="chat-queue-label"><span data-i18n="chat.queue_label">Queued</span> <span class="chat-queue-count" id="skills-chat-queue-count">0</span></span>
+ <span class="chat-queue-hint" data-i18n="chat.queue_hint">Drag to reorder · Edit · Delete</span>
</div>
<div class="chat-queue-list" id="skills-chat-queue-list"></div>
</div>
<div class="skills-chat-input-area">
- <textarea id="skills-chat-input" data-i18n-placeholder="skills.chat_input_placeholder" placeholder="描述需要修改的内容..." rows="1"></textarea>
- <button id="skills-chat-send-btn" class="chat-send-btn" data-i18n-title="chat.send_title" title="发送">
+ <textarea id="skills-chat-input" data-i18n-placeholder="skills.chat_input_placeholder" placeholder="Describe what to change..." rows="1"></textarea>
+ <button id="skills-chat-send-btn" class="chat-send-btn" data-i18n-title="chat.send_title" title="Send">
<svg class="send-icon" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"></path></svg>
<svg class="stop-icon" viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"></rect></svg>
</button>
@@ -240,19 +240,19 @@
<!-- Grid view (default) -->
<div class="agents-grid-view" id="agents-grid-view">
<div class="agents-grid-header">
- <span data-i18n="agents.title">智能体</span>
- <button class="btn btn-sm" id="create-agent-btn" data-i18n="agents.create_btn">+ 创建</button>
+ <span data-i18n="agents.title">Agents</span>
+ <button class="btn btn-sm" id="create-agent-btn" data-i18n="agents.create_btn">+ Create</button>
</div>
<div class="agents-grid-scroll">
<div class="agents-group" id="agents-grid-custom-group" style="display:none">
- <div class="agents-group-label" data-i18n="agents.custom_group">自定义</div>
+ <div class="agents-group-label" data-i18n="agents.custom_group">Custom</div>
<div class="agents-grid" id="agents-grid-custom"></div>
</div>
<div class="agents-group" id="agents-grid-builtin-group" style="display:none">
- <div class="agents-group-label" data-i18n="agents.builtin_group">内置</div>
+ <div class="agents-group-label" data-i18n="agents.builtin_group">Built-in</div>
<div class="agents-grid" id="agents-grid-builtin"></div>
</div>
- <div class="agents-empty" id="agents-empty" data-i18n="agents.empty">暂无智能体</div>
+ <div class="agents-empty" id="agents-empty" data-i18n="agents.empty">No agents yet</div>
</div>
</div>
@@ -262,7 +262,7 @@
<div class="agents-detail-breadcrumb">
<button type="button" class="agents-back-btn" id="agents-back-btn">
<span aria-hidden="true">←</span>
- <span data-i18n="agents.back">返回智能体</span>
+ <span data-i18n="agents.back">Back to agents</span>
</button>
</div>
<div class="agents-detail-content" id="agents-detail-content" style="display:none">
@@ -272,27 +272,27 @@
<div class="agents-detail-name" id="agents-detail-name" contenteditable="false"></div>
<span class="agents-detail-source" id="agents-detail-source"></span>
<div class="detail-actions" id="agents-detail-actions">
- <button class="btn-icon-use" id="agent-use-btn" data-i18n-title="agents.use_tooltip" data-i18n-aria-label="agents.use_tooltip" aria-label="使用">
+ <button class="btn-icon-use" id="agent-use-btn" data-i18n-title="agents.use_tooltip" data-i18n-aria-label="agents.use_tooltip" aria-label="Use this agent">
<svg class="icon-play" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><polygon points="5,3 5,13 13,8" fill="currentColor"/></svg>
</button>
- <button class="btn btn-sm" id="agent-edit-btn" data-i18n="agents.edit_btn_edit">编辑</button>
- <button class="btn btn-sm" id="agent-enabled-btn" data-i18n="component.disable">禁用</button>
- <button class="btn btn-sm" id="agent-promote-btn" style="display:none" data-i18n="agents.promote_to_builtin">设为内置</button>
- <button class="btn btn-sm btn-danger" id="agent-delete-btn" data-i18n="agents.delete">删除</button>
+ <button class="btn btn-sm" id="agent-edit-btn" data-i18n="agents.edit_btn_edit">Edit</button>
+ <button class="btn btn-sm" id="agent-enabled-btn" data-i18n="component.disable">Disable</button>
+ <button class="btn btn-sm" id="agent-promote-btn" style="display:none" data-i18n="agents.promote_to_builtin">Make built-in (dev)</button>
+ <button class="btn btn-sm btn-danger" id="agent-delete-btn" data-i18n="agents.delete">Delete</button>
</div>
</div>
</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">External agent</div>
<div class="agents-detail-runtime" id="agents-detail-runtime"></div>
</div>
<div class="agents-detail-section">
- <div class="agents-detail-label" data-i18n="agents.label_desc">简介</div>
+ <div class="agents-detail-label" data-i18n="agents.label_desc">Summary</div>
<div class="agents-detail-desc" id="agents-detail-desc" contenteditable="false"></div>
</div>
<div class="agents-detail-section agents-detail-section-workflow">
- <div class="agents-detail-label" data-i18n="agents.label_workflow">工作流程</div>
+ <div class="agents-detail-label" data-i18n="agents.label_workflow">Workflow</div>
<div class="agents-detail-workflow markdown-body" id="agents-detail-workflow" contenteditable="false"></div>
</div>
</div>
@@ -301,19 +301,19 @@
<!-- Inline chat for agent editing -->
<div class="agents-chat-col" id="agents-chat-col" style="display:none">
<div class="agents-chat-toolbar">
- <button id="agent-chat-clear-btn" class="agent-chat-link" data-i18n-title="agents.clear_chat_title" title="清空当前智能体的对话记录" data-i18n="agents.clear_chat">清空</button>
+ <button id="agent-chat-clear-btn" class="agent-chat-link" data-i18n-title="agents.clear_chat_title" title="Clear the edit chat for this agent" data-i18n="agents.clear_chat">Clear</button>
</div>
<div class="agents-chat-messages" id="agents-chat-messages"></div>
<div class="chat-queue" id="agents-chat-queue" style="display:none">
<div class="chat-queue-header">
- <span class="chat-queue-label"><span data-i18n="chat.queue_label">待发送</span> <span class="chat-queue-count" id="agents-chat-queue-count">0</span></span>
- <span class="chat-queue-hint" data-i18n="chat.queue_hint">可拖动排序 · 编辑 · 删除</span>
+ <span class="chat-queue-label"><span data-i18n="chat.queue_label">Queued</span> <span class="chat-queue-count" id="agents-chat-queue-count">0</span></span>
+ <span class="chat-queue-hint" data-i18n="chat.queue_hint">Drag to reorder · Edit · Delete</span>
</div>
<div class="chat-queue-list" id="agents-chat-queue-list"></div>
</div>
<div class="agents-chat-input-area">
- <textarea id="agents-chat-input" data-i18n-placeholder="agents.chat_input_placeholder" placeholder="描述需要调整的内容..." rows="1"></textarea>
- <button id="agents-chat-send-btn" class="chat-send-btn" data-i18n-title="chat.send_title" title="发送">
+ <textarea id="agents-chat-input" data-i18n-placeholder="agents.chat_input_placeholder" placeholder="Describe what to adjust..." rows="1"></textarea>
+ <button id="agents-chat-send-btn" class="chat-send-btn" data-i18n-title="chat.send_title" title="Send">
<svg class="send-icon" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"></path></svg>
<svg class="stop-icon" viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"></rect></svg>
</button>
@@ -327,10 +327,10 @@
<div class="contexts-layout">
<div class="contexts-tree-col" id="contexts-tree-col">
<div class="contexts-section-header">
- <span class="contexts-section-title" data-i18n="contexts.title">知识库</span>
+ <span class="contexts-section-title" data-i18n="contexts.title">Knowledge Base</span>
<button type="button" class="ctx-row-menu-btn ctx-root-menu-btn" id="ctx-root-menu-btn"
- data-i18n-title="contexts.menu.more_actions" title="更多操作"
- data-i18n-aria-label="contexts.menu.more_actions" aria-label="更多操作">⋯</button>
+ data-i18n-title="contexts.menu.more_actions" title="More actions"
+ data-i18n-aria-label="contexts.menu.more_actions" aria-label="More actions">⋯</button>
<input type="file" id="ctx-file-input" multiple
accept=".md,.markdown,.txt,.csv,.tsv,.json,.yaml,.yml,.log,.pdf,.docx,.png,.jpg,.jpeg,.webp,.gif,text/markdown,text/plain,text/csv,application/json,application/x-yaml,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/png,image/jpeg,image/webp,image/gif"
style="display:none" />
@@ -340,12 +340,12 @@
<span id="ctx-upload-status-label"></span>
</div>
<div class="contexts-tree" id="contexts-tree">
- <div class="empty" data-i18n="contexts.empty">知识库为空</div>
+ <div class="empty" data-i18n="contexts.empty">Knowledge base is empty</div>
</div>
</div>
<div class="contexts-editor-col" id="contexts-editor-col">
<div class="contexts-editor-empty" id="contexts-editor-empty">
- <div data-i18n="contexts.editor_empty">选择左侧文件查看</div>
+ <div data-i18n="contexts.editor_empty">Select a file on the left</div>
</div>
<div class="contexts-viewer-wrap" id="contexts-viewer-wrap" style="display:none">
<div class="contexts-editor-header">
@@ -362,11 +362,11 @@
<section class="panel" id="panel-settings">
<div class="settings-container">
<div class="settings-header">
- <h2 data-i18n="settings.title">设置</h2>
+ <h2 data-i18n="settings.title">Settings</h2>
<div class="settings-version" id="settings-version"></div>
</div>
<div class="settings-body">
- <div class="settings-section-head" data-i18n="settings.section.general">通用</div>
+ <div class="settings-section-head" data-i18n="settings.section.general">General</div>
<div class="settings-group">
<div class="settings-group-head">
@@ -386,82 +386,82 @@
<div class="settings-group">
<div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.commander_avatar.title">指挥官头像</div>
- <div class="settings-group-sub" data-i18n="settings.commander_avatar.sub">点击头像选择新的图标和颜色。</div>
+ <div class="settings-group-title" data-i18n="settings.commander_avatar.title">Commander avatar</div>
+ <div class="settings-group-sub" data-i18n="settings.commander_avatar.sub">Click the avatar to pick a new icon and color.</div>
</div>
<div class="settings-row">
<span class="settings-commander-avatar-slot" id="settings-commander-avatar"></span>
- <span class="settings-status muted" id="settings-commander-avatar-hint" data-i18n="settings.commander_avatar.hint">点击左侧头像修改</span>
+ <span class="settings-status muted" id="settings-commander-avatar-hint" data-i18n="settings.commander_avatar.hint">Click the avatar on the left to change it</span>
</div>
</div>
<div class="settings-group">
<div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.localexec.title">本机执行 (Local Execution)</div>
- <div class="settings-group-sub" data-i18n="settings.localexec.sub">授权后,智能体可以在你的电脑上执行 shell 命令、读写工作区内的文件、以及使用内置的 Markdown/HTML → PDF 生成能力。用于安装命令行工具(brew/npm/pip)、运行构建、转换文件等。未授权时以上工具会自动拒绝执行。</div>
+ <div class="settings-group-title" data-i18n="settings.localexec.title">Local Execution</div>
+ <div class="settings-group-sub" data-i18n="settings.localexec.sub">Once granted, agents may run shell commands, read/write workspace files, and generate PDFs. Without permission those tools refuse to run.</div>
</div>
<div class="settings-row">
- <span class="settings-status" id="settings-localexec-status" data-i18n="settings.localexec.status_loading">加载中…</span>
- <button class="btn btn-sm btn-primary" id="settings-localexec-toggle" data-i18n="settings.localexec.btn_grant">授权本机执行</button>
+ <span class="settings-status" id="settings-localexec-status" data-i18n="settings.localexec.status_loading">Loading…</span>
+ <button class="btn btn-sm btn-primary" id="settings-localexec-toggle" data-i18n="settings.localexec.btn_grant">Grant local execution</button>
</div>
</div>
<div class="settings-group">
<div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.metacognition.title">元认知级别的 Agent 自演进</div>
- <div class="settings-group-sub" data-i18n="settings.metacognition.sub">开启后,每个 Agent 会在工作一段时间后自动复盘最近的表现,总结经验、调整自己的工作方式,下次接到任务时表现更好。称为「元认知」是因为 Agent 不只在做任务,还会反思「自己做得怎样、下次怎么做更好」——这种对自身认知过程的认知就是元认知。关闭后 Agent 不再自动复盘。</div>
+ <div class="settings-group-title" data-i18n="settings.metacognition.title">Metacognition-level Agent Self-Evolution</div>
+ <div class="settings-group-sub" data-i18n="settings.metacognition.sub">When on, each agent periodically reviews its recent performance, draws lessons, and adjusts how it works so it does better next time. We call it "meta-cognitive" because the agent doesn't just do tasks — it also reasons about "how am I doing, and how could I do better next time?" That cognition about its own cognition is metacognition. Turn off to stop the self-review.</div>
</div>
<div class="settings-row">
<label class="settings-toggle">
<input type="checkbox" id="settings-metacognition-toggle" />
- <span data-i18n="settings.metacognition.toggle">启动</span>
+ <span data-i18n="settings.metacognition.toggle">Enable</span>
</label>
<span class="settings-status muted" id="settings-metacognition-status"></span>
</div>
</div>
- <div class="settings-section-head" data-i18n="settings.section.models">模型与凭证</div>
- <div class="settings-section-note" data-i18n="settings.section.models_note">所有 API Key 与 OAuth 令牌只保存在本机,不上云、不外发。</div>
+ <div class="settings-section-head" data-i18n="settings.section.models">Models & credentials</div>
+ <div class="settings-section-note" data-i18n="settings.section.models_note">API keys and OAuth tokens are stored locally only — never synced or sent off-device.</div>
<div class="settings-group">
<div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.add_auth_title">添加模型授权</div>
- <div class="settings-group-sub" data-i18n="settings.add_auth_sub">选择提供商和模型,然后添加一个 API Key 或 OAuth 账号。</div>
+ <div class="settings-group-title" data-i18n="settings.add_auth_title">Add model authorization</div>
+ <div class="settings-group-sub" data-i18n="settings.add_auth_sub">Pick a provider and model, then add an API key or OAuth account.</div>
</div>
<div class="settings-row">
- <label data-i18n="settings.provider">提供商</label>
+ <label data-i18n="settings.provider">Provider</label>
<div class="ai-select" id="settings-picker-provider"></div>
</div>
<div class="settings-row">
- <label data-i18n="settings.model">模型</label>
+ <label data-i18n="settings.model">Model</label>
<div class="ai-select" id="settings-picker-model"></div>
</div>
<div class="settings-row">
- <button class="btn btn-primary" id="settings-add-entry-btn" data-i18n="settings.add_account">+ 添加账号</button>
+ <button class="btn btn-primary" id="settings-add-entry-btn" data-i18n="settings.add_account">+ Add account</button>
<span class="settings-status" id="settings-picker-status"></span>
</div>
</div>
<div class="settings-group">
<div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.configured_title">已配置(按优先级)</div>
- <div class="settings-group-sub" data-i18n="settings.configured_sub">第一项是默认模型;当前一项不可用时自动兜底到下一项。拖动调整顺序。</div>
+ <div class="settings-group-title" data-i18n="settings.configured_title">Configured (by priority)</div>
+ <div class="settings-group-sub" data-i18n="settings.configured_sub">The first entry is the default model; later entries are the fallback chain. Drag to reorder.</div>
</div>
<div class="settings-entries" id="settings-entries">
- <div class="settings-empty" data-i18n="settings.loading">加载中…</div>
+ <div class="settings-empty" data-i18n="settings.loading">Loading…</div>
</div>
</div>
- <div class="settings-section-head" data-i18n="settings.section.tools">工具能力</div>
- <div class="settings-section-note" data-i18n="settings.section.tools_note">搜索与图片 API Key 只保存在本机,不上云、不外发。</div>
+ <div class="settings-section-head" data-i18n="settings.section.tools">Tool capabilities</div>
+ <div class="settings-section-note" data-i18n="settings.section.tools_note">Search and image-gen API keys are stored locally only — never synced or sent off-device.</div>
<div class="settings-group">
<div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.search.title">搜索 API Key</div>
- <div class="settings-group-sub" data-i18n="settings.search.sub">优先级:搜索 API &gt; 模型原生搜索 &gt; 内置免费搜索。</div>
+ <div class="settings-group-title" data-i18n="settings.search.title">Search API Key</div>
+ <div class="settings-group-sub" data-i18n="settings.search.sub">Priority: paid API &gt; model-native search &gt; built-in keyless scraper.</div>
</div>
<div class="settings-row">
- <label data-i18n="settings.search.provider">服务商</label>
+ <label data-i18n="settings.search.provider">Provider</label>
<div class="ai-select" id="settings-search-provider"></div>
</div>
<div class="settings-row">
@@ -469,21 +469,21 @@
<input type="text" class="form-input" id="settings-search-key-input" autocomplete="off" spellcheck="false" />
</div>
<div class="settings-row">
- <button class="btn btn-primary" id="settings-search-add-btn" data-i18n="settings.search.add">+ 添加搜索 Key</button>
+ <button class="btn btn-primary" id="settings-search-add-btn" data-i18n="settings.search.add">+ Add search key</button>
<span class="settings-status" id="settings-search-status"></span>
</div>
<div class="settings-entries" id="settings-search-entries">
- <div class="settings-empty" data-i18n="settings.loading">加载中…</div>
+ <div class="settings-empty" data-i18n="settings.loading">Loading…</div>
</div>
</div>
<div class="settings-group">
<div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.image.title">图片生成 API Key</div>
- <div class="settings-group-sub" data-i18n="settings.image.sub">用于对话中的 generate_image 工具。与"模型与凭证"区域相互独立——这里填的 Key 只用于图片生成,不影响聊天模型。未配置时自动回退到聊天 Key(若聊天 Key 是 OpenAI / Google)。</div>
+ <div class="settings-group-title" data-i18n="settings.image.title">Image generation API Key</div>
+ <div class="settings-group-sub" data-i18n="settings.image.sub">API for the generate_image tool. Falls back to chat keys when those target OpenAI or Google.</div>
</div>
<div class="settings-row">
- <label data-i18n="settings.image.provider">服务商</label>
+ <label data-i18n="settings.image.provider">Provider</label>
<div class="ai-select" id="settings-image-provider"></div>
</div>
<div class="settings-row">
@@ -491,11 +491,11 @@
<input type="text" class="form-input" id="settings-image-key-input" autocomplete="off" spellcheck="false" />
</div>
<div class="settings-row">
- <button class="btn btn-primary" id="settings-image-add-btn" data-i18n="settings.image.add">+ 添加图片 Key</button>
+ <button class="btn btn-primary" id="settings-image-add-btn" data-i18n="settings.image.add">+ Add image key</button>
<span class="settings-status" id="settings-image-status"></span>
</div>
<div class="settings-entries" id="settings-image-entries">
- <div class="settings-empty" data-i18n="settings.loading">加载中…</div>
+ <div class="settings-empty" data-i18n="settings.loading">Loading…</div>
</div>
</div>
</div>
@@ -508,26 +508,26 @@
<!-- Create Agent Modal -->
<div class="modal-overlay" id="agent-modal">
<div class="modal">
- <h3 data-i18n="agent_modal.title">新建智能体</h3>
+ <h3 data-i18n="agent_modal.title">New agent</h3>
- <!-- Mode tabs: 创建 (in-process) / 外接 (cli runtime). Mirrors the
+ <!-- Mode tabs: Create (in-process) / External (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>
+ <button type="button" class="skill-modal-tab is-active" data-agent-tab="create" data-i18n="agent_modal.tab_create">Create</button>
+ <button type="button" class="skill-modal-tab" data-agent-tab="external" data-i18n="agent_modal.tab_external">External</button>
</div>
<!-- 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="例如:代码审查助手" />
+ <label data-i18n="agent_modal.name">Name</label>
+ <input type="text" id="agent-name-input" data-i18n-placeholder="agent_modal.name_placeholder" placeholder="e.g. Code Review Assistant" />
</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>
+ <label><span data-i18n="agent_modal.desc">Summary</span> <span class="form-hint" data-i18n="agent_modal.desc_hint">One line on what it does — the AI will generate a workflow from this</span></label>
+ <textarea id="agent-desc-input" rows="4" data-i18n-placeholder="agent_modal.desc_placeholder" placeholder="e.g. Review my code before commit, focus on logic bugs and security issues..."></textarea>
</div>
</div>
@@ -537,23 +537,23 @@
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>
+ <label data-i18n="agent_modal.ext_cli_label">Agent</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" />
+ <label data-i18n="agent_modal.ext_name">Name</label>
+ <input type="text" id="agent-ext-name-input" data-i18n-placeholder="agent_modal.ext_name_placeholder" placeholder="e.g. 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>
+ <label data-i18n="agent_modal.ext_desc">Summary</label>
+ <textarea id="agent-ext-desc-input" rows="4" data-i18n-placeholder="agent_modal.ext_desc_placeholder" placeholder="(auto-filled when a CLI is picked; can be overridden)"></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>
- <button class="btn btn-primary" id="agent-save-btn" onclick="saveAgentModal()" data-i18n="common.confirm">确认</button>
+ <button class="btn" onclick="closeAgentModal()" data-i18n="common.cancel">Cancel</button>
+ <button class="btn btn-primary" id="agent-save-btn" onclick="saveAgentModal()" data-i18n="common.confirm">Confirm</button>
</div>
</div>
</div>
@@ -561,43 +561,43 @@
<!-- Create/Edit Skill Modal -->
<div class="modal-overlay" id="skill-modal">
<div class="modal">
- <h3 id="skill-modal-title" data-i18n="skill_modal.title_create">新建技能</h3>
+ <h3 id="skill-modal-title" data-i18n="skill_modal.title_create">New skill</h3>
<input type="hidden" id="skill-edit-id" value="" />
<!-- Import-method tabs. Only shown in create mode (hidden when editing). -->
<div class="skill-modal-tabs" id="skill-modal-tabs">
- <button type="button" class="skill-modal-tab is-active" data-skill-tab="manual" data-i18n="skill_modal.tab_manual">手动</button>
- <button type="button" class="skill-modal-tab" data-skill-tab="url" data-i18n="skill_modal.tab_url">从 URL 导入</button>
- <button type="button" class="skill-modal-tab" data-skill-tab="dir" data-i18n="skill_modal.tab_dir">从文件夹导入</button>
+ <button type="button" class="skill-modal-tab is-active" data-skill-tab="manual" data-i18n="skill_modal.tab_manual">Manual</button>
+ <button type="button" class="skill-modal-tab" data-skill-tab="url" data-i18n="skill_modal.tab_url">From URL</button>
+ <button type="button" class="skill-modal-tab" data-skill-tab="dir" data-i18n="skill_modal.tab_dir">From folder</button>
</div>
<!-- Manual panel (default) -->
<div class="skill-modal-panel is-active" data-skill-panel="manual">
<div class="form-row">
- <label><span data-i18n="skill_modal.name">名称(英文)</span><span class="form-hint" data-i18n="skill_modal.name_hint">字母开头,可含数字/-/_ 和单个空格</span></label>
- <input type="text" id="skill-name" data-i18n-placeholder="skill_modal.name_placeholder" placeholder="例如:web-summary" />
+ <label><span data-i18n="skill_modal.name">Name (English)</span><span class="form-hint" data-i18n="skill_modal.name_hint">Starts with a letter; digits, -, _, and one space allowed</span></label>
+ <input type="text" id="skill-name" data-i18n-placeholder="skill_modal.name_placeholder" placeholder="e.g. web-summary" />
</div>
<div class="form-row">
- <label data-i18n="skill_modal.description">简介</label>
- <textarea id="skill-description" rows="4" data-i18n-placeholder="skill_modal.desc_placeholder" placeholder="一句话说明这个技能做什么、什么时候用..."></textarea>
+ <label data-i18n="skill_modal.description">Summary</label>
+ <textarea id="skill-description" rows="4" data-i18n-placeholder="skill_modal.desc_placeholder" placeholder="One line on what this skill does and when to use it..."></textarea>
</div>
</div>
- <!-- URL import panel: name/简介 由模型在导入会话里自动产出 -->
+ <!-- URL import panel: name/summary are produced by the model during the import chat -->
<div class="skill-modal-panel" data-skill-panel="url">
<div class="form-row">
- <label><span data-i18n="skill_modal.url">URL</span><span class="form-hint" data-i18n="skill_modal.url_hint">clawhub、github、技能介绍等链接</span></label>
+ <label><span data-i18n="skill_modal.url">URL</span><span class="form-hint" data-i18n="skill_modal.url_hint">clawhub / GitHub / skill intro pages, etc.</span></label>
<input type="text" id="skill-url-input" data-i18n-placeholder="skill_modal.url_placeholder" placeholder="https://..." />
</div>
</div>
- <!-- Dir import panel: name/简介 由模型在导入会话里自动产出 -->
+ <!-- Dir import panel: name/summary are produced by the model during the import chat -->
<div class="skill-modal-panel" data-skill-panel="dir">
<div class="form-row">
- <label><span data-i18n="skill_modal.dir">源目录</span><span class="form-hint" data-i18n="skill_modal.dir_hint">文件最多 100 个 / 总大小最多 50 MiB</span></label>
+ <label><span data-i18n="skill_modal.dir">Source folder</span><span class="form-hint" data-i18n="skill_modal.dir_hint">Max 100 files / 50 MiB total</span></label>
<div class="skill-dir-pick-row">
- <button type="button" class="btn btn-sm" id="skill-dir-pick-btn" onclick="pickSkillImportDir()" data-i18n="skill_modal.dir_pick_btn">选择文件夹</button>
- <span class="skill-dir-selected" id="skill-dir-selected" data-i18n="skill_modal.dir_none">(未选择)</span>
+ <button type="button" class="btn btn-sm" id="skill-dir-pick-btn" onclick="pickSkillImportDir()" data-i18n="skill_modal.dir_pick_btn">Pick folder</button>
+ <span class="skill-dir-selected" id="skill-dir-selected" data-i18n="skill_modal.dir_none">(not picked)</span>
</div>
<input type="hidden" id="skill-dir-path" value="" />
</div>
@@ -605,8 +605,8 @@
<div class="form-msg" id="skill-form-msg"></div>
<div class="modal-actions">
- <button class="btn" onclick="closeSkillModal()" data-i18n="common.cancel">取消</button>
- <button class="btn btn-primary" id="skill-save-btn" onclick="saveSkill()" data-i18n="common.confirm">确认</button>
+ <button class="btn" onclick="closeSkillModal()" data-i18n="common.cancel">Cancel</button>
+ <button class="btn btn-primary" id="skill-save-btn" onclick="saveSkill()" data-i18n="common.confirm">Confirm</button>
</div>
</div>
</div>
@@ -614,31 +614,31 @@
<!-- Agent picker popup (new-chat only) -->
<div class="skill-picker" id="agent-picker" style="display:none">
<div class="skill-picker-header">
- <input type="text" id="agent-picker-search" data-i18n-placeholder="agent_picker.search_placeholder" placeholder="搜索智能体..." autocomplete="off" />
+ <input type="text" id="agent-picker-search" data-i18n-placeholder="agent_picker.search_placeholder" placeholder="Search agents..." autocomplete="off" />
</div>
<div class="skill-picker-list" id="agent-picker-list"></div>
</div>
<div class="agent-row-menu" id="agent-row-menu" style="display:none">
- <div class="agent-row-menu-item" data-action="edit" data-i18n="agents.edit">编辑</div>
- <div class="agent-row-menu-item is-danger" data-action="delete" data-i18n="agents.delete">删除</div>
+ <div class="agent-row-menu-item" data-action="edit" data-i18n="agents.edit">Edit</div>
+ <div class="agent-row-menu-item is-danger" data-action="delete" data-i18n="agents.delete">Delete</div>
</div>
<!-- Knowledge-base "new directory" modal. Text-file creation no longer
- goes through this modal — + 文本 creates an "未命名.md" inline and
+ goes through this modal — + Text creates an "Untitled.md" inline and
drops the tree into rename mode + the viewer into edit mode. -->
<div class="modal-overlay" id="ctx-new-modal">
<div class="modal">
- <h3 data-i18n="contexts.new.modal_title_dir">新建目录</h3>
+ <h3 data-i18n="contexts.new.modal_title_dir">New Folder</h3>
<div class="form-row ctx-new-target" id="ctx-new-target"></div>
<div class="form-row">
- <label data-i18n="contexts.new.dir_name">目录名</label>
+ <label data-i18n="contexts.new.dir_name">Folder name</label>
<input type="text" id="ctx-new-name" placeholder="notes" autocomplete="off" />
</div>
<div class="form-msg" id="ctx-new-msg"></div>
<div class="modal-actions">
- <button class="btn" onclick="closeCtxNewModal()" data-i18n="common.cancel">取消</button>
- <button class="btn btn-primary" onclick="saveCtxNew()" data-i18n="common.confirm">确认</button>
+ <button class="btn" onclick="closeCtxNewModal()" data-i18n="common.cancel">Cancel</button>
+ <button class="btn btn-primary" onclick="saveCtxNew()" data-i18n="common.confirm">Confirm</button>
</div>
</div>
</div>
@@ -646,10 +646,10 @@
<!-- Unauthorized banner -->
<div class="access-denied" id="access-denied">
<div class="access-denied-box">
- <div class="access-denied-title">无权访问</div>
+ <div class="access-denied-title">Access denied</div>
<div class="access-denied-msg">
- 请在访问地址后追加 <code>?password=&lt;访问密码&gt;</code><br />
- 密码在服务启动日志或 <code>data/users/_password.json</code> 中。
+ Append <code>?password=&lt;access-password&gt;</code> to the URL.<br />
+ The password is in the server startup log or <code>data/users/_password.json</code>.
</div>
</div>
</div>
@@ -657,20 +657,20 @@
<!-- KB location picker (chat archive + any future drop-to-KB flow) -->
<div class="modal-overlay" id="kb-picker-modal">
<div class="modal kb-picker">
- <h3 id="kb-picker-title" data-i18n="kb_picker.title">保存到知识库</h3>
+ <h3 id="kb-picker-title" data-i18n="kb_picker.title">Save to knowledge base</h3>
<div class="form-row">
- <label><span data-i18n="kb_picker.name">文件名</span> <span class="form-hint" data-i18n="kb_picker.name_hint">不含扩展名将自动补 .md</span></label>
+ <label><span data-i18n="kb_picker.name">Filename</span> <span class="form-hint" data-i18n="kb_picker.name_hint">Missing extension will be auto-filled as .md</span></label>
<input type="text" id="kb-picker-name" autocomplete="off" />
</div>
<div class="form-row">
- <label data-i18n="kb_picker.folder">选择目录</label>
+ <label data-i18n="kb_picker.folder">Choose folder</label>
<div class="kb-picker-tree" id="kb-picker-tree"></div>
<div class="kb-picker-target" id="kb-picker-target"></div>
</div>
<div class="form-msg" id="kb-picker-msg"></div>
<div class="modal-actions">
- <button class="btn" onclick="closeKbPicker()" data-i18n="common.cancel">取消</button>
- <button class="btn btn-primary" onclick="confirmKbPicker()" data-i18n="common.confirm">确认</button>
+ <button class="btn" onclick="closeKbPicker()" data-i18n="common.cancel">Cancel</button>
+ <button class="btn btn-primary" onclick="confirmKbPicker()" data-i18n="common.confirm">Confirm</button>
</div>
</div>
</div>
@@ -678,7 +678,7 @@
<!-- Add-account modal (settings page) -->
<div class="modal-overlay" id="add-account-modal">
<div class="modal add-account-modal">
- <h3 id="add-account-title" data-i18n="add_account.title">新增账号</h3>
+ <h3 id="add-account-title" data-i18n="add_account.title">Add account</h3>
<div class="add-account-body" id="add-account-body"></div>
<div class="modal-actions" id="add-account-actions"></div>
</div>
@@ -687,12 +687,12 @@
<!-- OAuth login flow modal -->
<div class="modal-overlay" id="oauth-flow-modal">
<div class="modal oauth-flow-modal">
- <h3 id="oauth-flow-title" data-i18n="oauth_flow.title">OAuth 登录</h3>
+ <h3 id="oauth-flow-title" data-i18n="oauth_flow.title">OAuth sign-in</h3>
<div class="oauth-flow-body" id="oauth-flow-body">
- <div class="oauth-flow-stage" data-i18n="oauth_flow.preparing">正在准备授权…</div>
+ <div class="oauth-flow-stage" data-i18n="oauth_flow.preparing">Preparing authorization…</div>
</div>
<div class="modal-actions">
- <button class="btn" id="oauth-flow-cancel-btn" data-i18n="common.cancel">取消</button>
+ <button class="btn" id="oauth-flow-cancel-btn" data-i18n="common.cancel">Cancel</button>
</div>
</div>
</div>
@@ -705,22 +705,22 @@
<circle cx="11" cy="11" r="7"></circle>
<path d="m21 21-4.3-4.3"></path>
</svg>
- <input type="text" id="search-input" data-i18n-placeholder="search.input_placeholder" placeholder="搜索聊天记录、知识库内容…" autocomplete="off" spellcheck="false" />
- <button class="search-close-btn" id="search-close-btn" data-i18n-title="search.close_title" title="关闭 (Esc)">
+ <input type="text" id="search-input" data-i18n-placeholder="search.input_placeholder" placeholder="Search chats and knowledge base…" autocomplete="off" spellcheck="false" />
+ <button class="search-close-btn" id="search-close-btn" data-i18n-title="search.close_title" title="Close (Esc)">
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 6 6 18M6 6l12 12"></path>
</svg>
</button>
</div>
<div class="search-tabs" id="search-tabs" role="tablist">
- <button class="search-tab is-active" data-tab="all" data-i18n="search.tab.all">全部</button>
- <button class="search-tab" data-tab="chat" data-i18n="search.tab.chat">对话</button>
- <button class="search-tab" data-tab="agent" data-i18n="search.tab.agent">智能体</button>
- <button class="search-tab" data-tab="skill" data-i18n="search.tab.skill">技能</button>
- <button class="search-tab" data-tab="context" data-i18n="search.tab.context">知识库</button>
+ <button class="search-tab is-active" data-tab="all" data-i18n="search.tab.all">All</button>
+ <button class="search-tab" data-tab="chat" data-i18n="search.tab.chat">Chats</button>
+ <button class="search-tab" data-tab="agent" data-i18n="search.tab.agent">Agents</button>
+ <button class="search-tab" data-tab="skill" data-i18n="search.tab.skill">Skills</button>
+ <button class="search-tab" data-tab="context" data-i18n="search.tab.context">Knowledge</button>
</div>
<div class="search-body" id="search-body">
- <div class="search-empty" data-i18n="search.empty_hint">输入关键词开始搜索</div>
+ <div class="search-empty" data-i18n="search.empty_hint">Type a keyword to start searching</div>
</div>
</div>
</div>
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 8b400df1..bfafce21 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -9,7 +9,7 @@ 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 "外接 · <Brand>" label for an agent runtime
+/** Look up the localized "External · <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. */
@@ -52,14 +52,19 @@ async function loadAgents(forceRefresh) {
const data = await res.json();
if (data.ok) {
// Sort once on cache fill so picker + grid share the order.
- // Order: custom 组在前,组内按"汉字按拼音首字母 + 拉丁/数字/符号原样"
- // 拼成 sort key 后字符串字典序。Electron 自带 small ICU,Intl.Collator
- // 不识别 zh pinyin tailoring(co-pinyin / zh-Hans-CN 都不行),会让中
- // 文堆一起、英文堆一起,所以靠 vendor/pinyin-firstletter 的查表把
- // '悲观'→'bg' / 'Claude'→'claude' / 'Orkas'→'orkas' 后再比,得到
- // 'agent < 悲(b) < 本(b) < claude < 乐(l) < orkas < 全(q)' 这种
- // 用户预期的混排。后端 listAgents 内部按 agent_id(12 位随机 nanoid)
- // 排,用户感知里等于"乱",这里覆盖掉。
+ // Order: custom group first, then within each group sort by a key
+ // built from "Chinese chars → pinyin first letter, Latin / digits
+ // / punctuation pass through unchanged" and compare as a plain
+ // string. Electron ships small ICU; Intl.Collator does not
+ // recognize zh pinyin tailoring (neither co-pinyin nor
+ // zh-Hans-CN works), so Chinese ends up clumped together and
+ // Latin clumped together. We use vendor/pinyin-firstletter's
+ // table to map e.g. '悲观' → 'bg' / 'Claude' → 'claude' /
+ // 'Orkas' → 'orkas' before comparing, yielding the user-expected
+ // mixed-script ordering ('agent < 悲(b) < 本(b) < claude < 乐(l)
+ // < orkas < 全(q)'). Without this, the backend's listAgents
+ // internal sort (by agent_id, a 12-char nanoid) feels random to
+ // users. The override here fixes that.
_agentsCache = (data.agents || []).slice().sort((a, b) => {
if (a.source !== b.source) return a.source === 'custom' ? -1 : 1;
const ka = pinyinSortKey(a.name || a.agent_id || '');
@@ -67,11 +72,15 @@ async function loadAgents(forceRefresh) {
return ka < kb ? -1 : ka > kb ? 1 : 0;
});
renderAgentsList(_agentsCache);
- // 老 spec 没存头像时回填到磁盘 —— 跨设备一致用 seed 派生(同一
- // agent_id 在任何机器都派生出同一组合,避免云同步时两端各写不同
- // 值导致冲突)。已经有 icon+color 的 entry 直接跳过,所以反复
- // 调用 loadAgents 不会重复写。后台异步即可,不阻塞渲染:渲染层
- // 自己也会用 seed 兜底,跟回填值一致,所以肉眼不会看到任何变化。
+ // Backfill avatars to disk when older specs lack them — derive
+ // from the seed for cross-device consistency (the same agent_id
+ // produces the same icon/color combination on every machine, so
+ // cloud sync won't see two ends writing different values and
+ // colliding). Entries that already have icon + color are
+ // skipped, so repeated loadAgents calls don't re-write.
+ // Asynchronous so it doesn't block rendering — the render layer
+ // also seeds an avatar fallback whose value matches what we
+ // backfill, so the user sees no visual change.
_backfillMissingAvatars(_agentsCache).catch((e) => {
_agentsLog.warn('avatar backfill failed', e);
});
@@ -100,8 +109,9 @@ async function _backfillMissingAvatars(agents) {
a.color = res.agent.color;
}
} catch (e) {
- // 失败也无所谓 —— 渲染层 seed 兜底依然会出同一组合,
- // 下次 loadAgents 再尝试。
+ // Failure here doesn't matter — the render layer's seed-based
+ // fallback still produces the same combination, and the next
+ // loadAgents call will retry.
_agentsLog.warn(`backfill ${a.agent_id} failed`, e);
}
}
@@ -458,8 +468,10 @@ function _renderAgentDetail(agent, editing) {
if (!editing && !localizedDesc) descEl.innerHTML = unsetHtml;
// Detail header actions, fixed order:
- // 使用(icon) / 编辑 / 启用-禁用 / 内置(custom+dev) / 删除
- // Edit mode hides everything except the 完成 button (the relabeled 编辑).
+ // use (icon) / edit / enable-disable / promote-to-builtin
+ // (custom + dev) / delete
+ // Edit mode hides everything except the "done" button (the relabeled
+ // "edit" button).
const useBtn = document.getElementById('agent-use-btn');
const enableBtn = document.getElementById('agent-enabled-btn');
const promoteBtn = document.getElementById('agent-promote-btn');
@@ -642,9 +654,10 @@ function _renderAgentDetailAvatar(agent) {
});
}
-/** Per-agent 启用 / 禁用 button in the detail header. Clone-replace to drop
- * any prior click handler bound to a stale agent id. The button label
- * flips between 启用 / 禁用 (whichever the click would do). */
+/** Per-agent enable / disable button in the detail header.
+ * Clone-replace to drop any prior click handler bound to a stale
+ * agent id. The button label flips between "enable" and "disable"
+ * (whichever the click would do). */
function _renderAgentEnabledButton(agent) {
const oldBtn = document.getElementById('agent-enabled-btn');
if (!oldBtn) return;
@@ -707,7 +720,7 @@ async function _enterAgentEditMode() {
async function _exitAgentEditMode() {
_agentEditing = false;
- // Abort any in-flight reply so 完成 stops the stream immediately. The
+ // Abort any in-flight reply so the "done" button stops the stream immediately. The
// agent chat controller is a singleton; leaving it pending also leaks the
// streaming-button state into the next agent's edit panel.
try { _agentChatCtrl?.abort(); } catch (_) { /* ignore */ }
@@ -748,7 +761,7 @@ function _scheduleAgentFieldSave(field, value) {
}
let _pendingAgentField = null;
-// `validate` is only true when the user explicitly commits (clicks 完成 →
+// `validate` is only true when the user explicitly commits (clicks "done" →
// `_exitAgentEditMode`). Typing-debounced and blur-triggered flushes pass
// false: a bad name silently skips the save (the DOM keeps the user's
// in-progress text) instead of popping a uiAlert mid-keystroke.
@@ -805,21 +818,22 @@ async function _flushAgentFieldSave({ validate = false } = {}) {
}
}
-// ─── Create agent (modal-first, two tabs: 创建 / 外接) ───
+// ─── Create agent (modal-first, two tabs: Create / External) ───
//
-// "创建" (default tab) — manual authoring of an in-process agent. The
-// LLM-driven edit chat opens immediately on save so the workflow can
-// be refined.
+// "Create" (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
+// "External" — bind a local CLI as the runtime. The CLI selector sits
+// at the top (default "not selected"); 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).
+// nothing applied yet (untouched-default state, or the "create" tab).
function _switchAgentTab(tab) {
const tabs = document.querySelectorAll('#agent-modal-tabs [data-agent-tab]');
@@ -885,8 +899,8 @@ function _applyExternalCliDefaults(cliType, { force = false } = {}) {
|| (prev && descEl.value === prevDescLocalized);
if (cliType === null) {
- // Reverted to 未选择 — only clear fields that still hold the
- // previous CLI's defaults. Keep user-typed text.
+ // Reverted to "not selected" — only clear fields that still hold
+ // the previous CLI's defaults. Keep user-typed text.
if (nameUntouched) nameEl.value = '';
if (descUntouched) descEl.value = '';
} else {
@@ -1179,7 +1193,7 @@ async function _loadAgentChatHistory(agentId) {
_ensureAgentChatController();
await _agentChatCtrl.loadHistory();
// Custom empty-state message for fresh agents — controller's default is
- // "无对话记录..."; replace it with an agent-specific prompt when empty.
+ // "no messages..."; replace it with an agent-specific prompt when empty.
const container = document.getElementById('agents-chat-messages');
const empty = container?.querySelector('.empty');
const defaultEmptyText = t('chat.empty');
@@ -1195,15 +1209,16 @@ async function clearAgentChat() {
await _agentChatCtrl.clear();
}
-// ─── "使用" flow: new normal conversation seeded with "运行 <name>" ───
+// ─── "Use" flow: new normal conversation seeded with "run <name>" ───
/**
- * Run an agent: creates a fresh normal conversation, navigates to it, then
- * auto-sends a short user-visible message ("运行 <name>"). The model sees
- * the same visible text and recognises it as a run-agent directive per
- * chat_commander.md rule 0 (instruction following) — no hidden backend injection.
+ * Run an agent: creates a fresh normal conversation, navigates to it,
+ * then auto-sends a short user-visible message ("run <name>"). The
+ * model sees the same visible text and recognises it as a run-agent
+ * directive per chat_commander.md rule 0 (instruction following) — no
+ * hidden backend injection.
*
- * `seedText` is the user-visible content. Defaults to "运行 <name>".
+ * `seedText` is the user-visible content. Defaults to "run <name>".
*/
async function useAgent(agentId, seedText) {
if (!ensureModelConfigured()) return;
@@ -1221,7 +1236,7 @@ async function useAgent(agentId, seedText) {
// from the first user message, same rule as every other conv-creation
// entry point (new-chat panel, commander @-mention). Optimistic title
// is the run-prefix message itself so the sidebar entry shows the
- // user's intent ("运行 <name>") instead of bare agent name; this
+ // user's intent ("run <name>") instead of bare agent name; this
// matches what backend `autoTitle` will persist on the same `visible`.
const res = await apiFetch('/api/conversations/create', {
method: 'POST',
@@ -1248,7 +1263,8 @@ async function useAgent(agentId, seedText) {
}
async function useSkill(skillId, skillName) {
- // Skill 使用:跳转到新对话页,预选该技能,等用户输入。
+ // Skill "use" flow: navigate to the new-chat page with the skill
+ // pre-selected and wait for user input.
_agentsLog.info('use skill', { skill_id: skillId, skill_name: skillName || skillId });
setView('new-chat');
setChatSkill('new-chat', skillName || skillId);
@@ -1430,7 +1446,7 @@ function _moveAgentPickerActive(delta) {
// Route an agent selection to the right behaviour based on which button
// triggered the picker:
-// - conversation toolbar → send/queue "运行 <name>" in the CURRENT conv.
+// - conversation toolbar → send/queue "run <name>" in the CURRENT conv.
// Never opens a new conv. No hidden backend injection — the model reads
// the visible message and follows chat_commander.md rule 0.
// - new-chat toolbar → create a new normal conv + run agent (useAgent)
@@ -1541,9 +1557,9 @@ function bindAgentPickers() {
};
// Backspace right after a `@<name>` token (with or without the trailing
// space the picker inserts) should remove the whole mention as one unit
- // — character-by-character deletion of `@张三 ` is annoying when the
- // user picked the wrong agent. Match the same charset as the bus
- // mention regex so `@中文名字` works.
+ // — character-by-character deletion of a mention like `@<CJK-name> `
+ // is annoying when the user picked the wrong agent. Match the same
+ // charset as the bus mention regex so CJK names work.
const MENTION_DELETE_RE = /@[A-Za-z0-9_一-鿿-]+ ?$/u;
const onBackspaceMention = (e) => {
if (e.key !== 'Backspace') return;
diff --git a/src/renderer/modules/avatar-picker.js b/src/renderer/modules/avatar-picker.js
index 70acdd5c..d2f4589f 100644
--- a/src/renderer/modules/avatar-picker.js
+++ b/src/renderer/modules/avatar-picker.js
@@ -1,16 +1,22 @@
// ─── Avatar picker (combined icon + color popover) ───────────────────────
//
-// 单一弹窗,里面两行:图标 grid + 颜色 grid。每选一项就触发回调,UI 立刻
-// 反映新组合。复用 `window.positionPickerPopover` 做定位(智能体/技能/agent
-// picker 用的同一套),保持视觉一致。
+// Single popover containing two rows: icon grid + color grid. Each
+// selection fires the callback and the UI updates immediately to
+// reflect the new combination. Reuses `window.positionPickerPopover`
+// for layout (the same helper agent/skill/agent picker uses), so the
+// visual style stays consistent.
//
-// 入口:openAvatarPicker(anchorEl, current, opts, onChange)
-// anchorEl: 锚点元素,用于定位
-// current: { icon, color },用于高亮当前选中
+// Entry: openAvatarPicker(anchorEl, current, opts, onChange)
+// anchorEl: the anchor element used for positioning.
+// current: { icon, color }, used to highlight the current pick.
// opts:
-// allowCommanderCombo: false —— true 时不过滤 crown / gold(指挥官设置)
-// hideIcons: false —— true 时只展示颜色行(指挥官头像图标固定为 crown)
-// onChange: ({ icon, color }) => void,每次选择都会触发
+// allowCommanderCombo: false — when true, crown / gold are not
+// filtered out (used by the
+// commander avatar settings).
+// hideIcons: false — when true, only the color row is
+// rendered (the commander avatar's
+// icon is always crown).
+// onChange: ({ icon, color }) => void, fires on every selection.
let _avatarPickerEl = null;
let _avatarPickerCurrent = null;
@@ -26,11 +32,11 @@ function _ensureAvatarPickerDom() {
el.style.display = 'none';
el.innerHTML = `
<div class="avatar-picker-section" data-role="icon-section">
- <div class="avatar-picker-label" data-i18n="avatar.icon_label">图标</div>
+ <div class="avatar-picker-label" data-i18n="avatar.icon_label">Icon</div>
<div class="avatar-picker-grid" data-role="icon-grid"></div>
</div>
<div class="avatar-picker-section">
- <div class="avatar-picker-label" data-i18n="avatar.color_label">颜色</div>
+ <div class="avatar-picker-label" data-i18n="avatar.color_label">Color</div>
<div class="avatar-picker-grid" data-role="color-grid"></div>
</div>
`;
diff --git a/src/renderer/modules/avatar.js b/src/renderer/modules/avatar.js
index c1bbced7..cd0cc083 100644
--- a/src/renderer/modules/avatar.js
+++ b/src/renderer/modules/avatar.js
@@ -1,25 +1,31 @@
// ─── Avatar (icon + color) for AI actors ─────────────────────────────────
//
-// 头像 catalog(15 图标 + 16 颜色 + 指挥官默认)的真相源在
-// `src/main/data/avatars.json`,启动时一次性走 IPC 拉过来缓存。所有渲染
-// helper 都从缓存读,**不再硬编码任何 SVG 或 hex**。
+// The avatar catalog (15 icons + 16 colors + commander default) has its
+// single source of truth at `src/main/data/avatars.json`; we fetch it
+// once via IPC at startup and cache it locally. Every render helper
+// reads the cache — **no SVG or hex is hardcoded anywhere else**.
//
-// 缺省回退:某 agent 还没存头像时按 `agent_id` 哈希出确定性组合 ——
-// 跨设备同一 agent_id 派生同一组合,云同步不会因两端各自随机而冲突。
+// Default fallback: when an agent has no stored avatar yet, derive a
+// deterministic combination by hashing `agent_id`. The same agent_id
+// derives the same combination on every device, so cloud sync does not
+// see two ends pick differently and collide.
//
-// 渲染统一走 renderAvatarHtml(...),DOM / .avatar-circle 样式一份,卡片、
-// 详情、聊天行、设置页都用同一 helper。
+// Rendering goes through renderAvatarHtml(...). The DOM and
+// .avatar-circle CSS are shared, so cards, detail pages, chat rows,
+// and the settings page all use the same helper.
let AVATAR_ICONS = [];
let AVATAR_COLORS = [];
-let COMMANDER_DEFAULT = { icon: 'crown', color: 'gold' }; // 兜底,IPC 完成后会被覆盖
+let COMMANDER_DEFAULT = { icon: 'crown', color: 'gold' }; // fallback, overwritten once the IPC fetch lands
let _avatarCatalogReady = false;
let _avatarCatalogPromise = null;
-/** 启动期调用一次 —— 拉 catalog 缓存到本地。boot.js 在渲染任何头像之前
- * await 它,确保 sync helper(renderAvatarHtml / randomAgentAvatar / …)
- * 调用时已就绪。重复调用安全,第二次起直接 resolve。 */
+/** Call once at startup — fetch the catalog and cache it locally.
+ * boot.js awaits this before rendering any avatar so the sync helpers
+ * (renderAvatarHtml / randomAgentAvatar / …) are ready by the time
+ * they're called. Safe to call multiple times — subsequent calls
+ * resolve immediately. */
async function initAvatarCatalog() {
if (_avatarCatalogReady) return;
if (_avatarCatalogPromise) { await _avatarCatalogPromise; return; }
@@ -36,7 +42,8 @@ async function initAvatarCatalog() {
_avatarCatalogReady = true;
}
} catch (_) {
- // 拉不到就继续用空数组 —— 渲染层会全部走 seed 兜底(视觉降级)。
+ // On fetch failure, leave the arrays empty — the render layer
+ // will fall back to seed-based avatars (a visual degradation).
} finally {
_avatarCatalogPromise = null;
}
@@ -48,7 +55,8 @@ function _isCommanderCombo(icon, color) {
return icon === COMMANDER_DEFAULT.icon || color === COMMANDER_DEFAULT.color;
}
-/** 智能体随机头像:从非指挥官池里挑一对 (icon, color)。 */
+/** Random agent avatar: pick a (icon, color) pair from the
+ * non-commander pool. */
function randomAgentAvatar() {
const icons = AVATAR_ICONS.filter((i) => i.id !== COMMANDER_DEFAULT.icon);
const colors = AVATAR_COLORS.filter((c) => c.id !== COMMANDER_DEFAULT.color);
@@ -58,7 +66,8 @@ function randomAgentAvatar() {
return { icon: i.id, color: c.id };
}
-// 简单 djb2,足够给 agent_id 散开到非指挥官的图标 / 颜色池上。
+// Simple djb2 hash — sufficient to spread agent_id across the
+// non-commander icon / color pools.
function _hash(str) {
let h = 5381;
const s = String(str || '');
@@ -66,8 +75,10 @@ function _hash(str) {
return h >>> 0;
}
-/** 由 seed 派生稳定的 (icon, color)。同一 seed 任何机器都得到同一组合,
- * 适合做"老 spec 缺字段时的回填"以及渲染兜底。 */
+/** Derive a stable (icon, color) from a seed. The same seed produces
+ * the same combination on every machine, which is good for both
+ * "backfill when an old spec lacks the fields" and as a render
+ * fallback. */
function avatarFromSeed(seed) {
const icons = AVATAR_ICONS.filter((i) => i.id !== COMMANDER_DEFAULT.icon);
const colors = AVATAR_COLORS.filter((c) => c.id !== COMMANDER_DEFAULT.color);
@@ -79,9 +90,11 @@ function avatarFromSeed(seed) {
};
}
-/** 解析任意 (iconId, colorId) 到可渲染的视觉数据。catalog 里查不到的
- * 字段(脏数据 / 未来重命名 token)按 fallbackSeed 派生;都没给就退化成
- * 指挥官默认色(极端情况,正常路径不会触发)。 */
+/** Resolve any (iconId, colorId) to renderable visual data. Fields
+ * that aren't in the catalog (dirty data / future-renamed tokens)
+ * derive from fallbackSeed; if neither side is given, fall back to
+ * the commander default (an edge case — never triggered on the
+ * normal path). */
function resolveAvatar(iconId, colorId, fallbackSeed) {
let resolvedIcon = AVATAR_ICONS.find((i) => i.id === iconId);
let resolvedColor = AVATAR_COLORS.find((c) => c.id === colorId);
@@ -91,7 +104,8 @@ function resolveAvatar(iconId, colorId, fallbackSeed) {
if (!resolvedColor) resolvedColor = AVATAR_COLORS.find((c) => c.id === fb.color);
}
if (!resolvedIcon || !resolvedColor) {
- // catalog 还没拉到(极端情况)——返回个空壳,渲染层至少不会崩。
+ // catalog hasn't been fetched yet (edge case) — return an empty
+ // shell so the render layer at least doesn't crash.
return { icon: '', color: '', iconSvg: '', bg: '#e5e7eb', fg: '#475569' };
}
return {
@@ -103,7 +117,8 @@ function resolveAvatar(iconId, colorId, fallbackSeed) {
};
}
-/** 就地把已有 .avatar-circle 元素的视觉换掉,不替换节点(保留点击监听)。 */
+/** Swap the visual data of an existing .avatar-circle element in
+ * place, without replacing the node (keeps click listeners). */
function applyAvatarToElement(el, iconId, colorId, seed) {
if (!el) return;
const a = resolveAvatar(iconId, colorId, seed || '');
@@ -117,7 +132,8 @@ function applyAvatarToElement(el, iconId, colorId, seed) {
: '';
}
-/** 生成头像 HTML 片段。用于卡片 / 详情 / 聊天行 / 设置页。
+/** Generate an avatar HTML fragment. Used by cards, the detail view,
+ * chat rows, and the settings page.
* opts: { size=28, seed='', clickable=false, extraClass='', dataAttrs={} } */
function renderAvatarHtml(iconId, colorId, opts = {}) {
const a = resolveAvatar(iconId, colorId, opts.seed || '');
diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.js
index 581f294a..e30c58cb 100644
--- a/src/renderer/modules/boot.js
+++ b/src/renderer/modules/boot.js
@@ -9,7 +9,7 @@ async function bootApp() {
await initI18n();
await initUser();
await initUserWorkspace();
- // 头像 catalog —— 必须在 loadAgents(会触发卡片渲染)之前就绪。
+ // Avatar catalog must be ready before loadAgents (which triggers card rendering).
await initAvatarCatalog();
await refreshModelGuard();
await loadConversations();
@@ -37,8 +37,10 @@ async function _stampSettingsVersion() {
// so we stub it to false here.
function isDevMode() { return false; }
-// 一次性把带历史品牌前缀的 localStorage key 迁移到无前缀形态。盖章后再
-// 启动 no-op,写在 boot 最前免得后面任何模块抢着读旧 key。
+// One-shot rename of legacy brand-prefixed localStorage keys
+// (`orkas_*` / `orkas.*`) to the unprefixed form. After stamping,
+// subsequent boots are no-ops. Placed at the very start of boot so no
+// other module reads a stale key first.
function _migrateLegacyLocalStorageKeys() {
try {
if (localStorage.getItem('_ls_brand_migration_v1')) return;
@@ -151,7 +153,7 @@ function setView(view, cid, opts = {}) {
// If this conversation has an in-flight stream and its bubble is still
// attached to #chat-history (sidebar tab toggle didn't wipe it), skip
// the reload — wiping would orphan the bubble while the active stream
- // closure keeps writing into the detached node, leaving "思考中…" stuck.
+ // closure keeps writing into the detached node, leaving the "thinking…" indicator stuck.
const pendingState = pendingConvs.get(cid);
const streamBubbleAlive = !!pendingState?.loadingEl?.isConnected;
@@ -194,7 +196,7 @@ function setView(view, cid, opts = {}) {
// the landing page is entered — the user explicitly asked for a clean
// slate here, so prior in-session picks don't leak forward.
if (typeof onEnterNewChatView === 'function') onEnterNewChatView();
- // Draft attachment chips (总指挥 pool under `main_chat/`): re-paint from
+ // Draft attachment chips (commander tab's pool under `main_chat/`): re-paint from
// the in-memory Map immediately, and re-sync with disk in case a prior
// session left files on disk without a dataUrl.
if (typeof _chatAttachRenderChips === 'function') _chatAttachRenderChips(DRAFT_CID);
diff --git a/src/renderer/modules/chat-input-form.js b/src/renderer/modules/chat-input-form.js
index 700d8e8a..709e2e1e 100644
--- a/src/renderer/modules/chat-input-form.js
+++ b/src/renderer/modules/chat-input-form.js
@@ -182,7 +182,7 @@
pathLabel.title = value;
pathLabel.classList.remove('is-empty');
} else {
- pathLabel.textContent = t('input.dir.none') || '(未选择)';
+ pathLabel.textContent = t('input.dir.none') || '(none selected)';
pathLabel.removeAttribute('title');
pathLabel.classList.add('is-empty');
}
@@ -191,25 +191,25 @@
const pickBtn = document.createElement('button');
pickBtn.type = 'button';
pickBtn.className = 'btn btn-sm form-field-dir-pick';
- pickBtn.textContent = t('input.dir.pick') || '选择目录…';
+ pickBtn.textContent = t('input.dir.pick') || 'Choose directory…';
const clearBtn = document.createElement('button');
clearBtn.type = 'button';
clearBtn.className = 'btn btn-sm form-field-dir-clear';
- clearBtn.textContent = t('input.dir.clear') || '清除';
+ clearBtn.textContent = t('input.dir.clear') || 'Clear';
pickBtn.disabled = disabled;
clearBtn.disabled = disabled;
pickBtn.addEventListener('click', async () => {
try {
const res = await window.orkas.invoke('common.pickDirectory', {
- title: field.label || '选择目录',
+ title: field.label || 'Choose a directory',
});
if (res && !res.cancelled && res.path) {
value = String(res.path);
renderPath();
- pickBtn.textContent = t('input.dir.change') || '更换…';
+ pickBtn.textContent = t('input.dir.change') || '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.
+ // "please wait for upload to finish" hint) even after the user picks a dir.
if (ctx && typeof ctx.onChange === 'function') ctx.onChange();
}
} catch (_) { /* user cancelled or no permission */ }
@@ -217,10 +217,10 @@
clearBtn.addEventListener('click', () => {
value = '';
renderPath();
- pickBtn.textContent = t('input.dir.pick') || '选择目录…';
+ pickBtn.textContent = t('input.dir.pick') || 'Choose directory…';
if (ctx && typeof ctx.onChange === 'function') ctx.onChange();
});
- if (value) pickBtn.textContent = t('input.dir.change') || '更换…';
+ if (value) pickBtn.textContent = t('input.dir.change') || 'Change…';
dirWrap.appendChild(pickBtn);
dirWrap.appendChild(clearBtn);
dirWrap.appendChild(pathLabel);
@@ -228,7 +228,7 @@
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
+ // button + show the "please wait for upload to finish" hint. Required-empty for a
// directory is reported by `_validate` on submit click, matching
// text / number / select.
} else {
@@ -428,7 +428,7 @@
function _formatSummaryLine(field, value) {
const fallback = t('chat.form.empty_value');
if (value === undefined || value === null) return fallback;
- if (field.type === 'boolean') return value === true ? '是' : '否';
+ if (field.type === 'boolean') return value === true ? 'yes' : 'no';
if (field.type === 'select') {
const opt = (field.options || []).find((o) => o.value === value);
return opt ? (opt.label || opt.value) : String(value);
@@ -477,7 +477,7 @@
//
// Submitted/readonly forms render *the same* widget — same fields, same
// controls, same layout — just with every input disabled and the
- // submit/reset buttons replaced by a "已提交 · time" stamp. This way the
+ // submit/reset buttons replaced by a "submitted · time" stamp. This way the
// bubble looks identical before and after submit, and the user always
// sees the structured form (not a degraded text summary) on refresh.
function renderChatInputForm(container, message, opts = {}) {
@@ -535,7 +535,7 @@
}
container.appendChild(bodyEl);
- // Submitted forms get a "已提交 · time" stamp instead of action buttons.
+ // Submitted forms get a "submitted · time" stamp instead of action buttons.
if (submitted) {
const stamp = document.createElement('div');
stamp.className = 'form-submitted-stamp';
diff --git a/src/renderer/modules/contexts.js b/src/renderer/modules/contexts.js
index 22ddeb9a..581371e0 100644
--- a/src/renderer/modules/contexts.js
+++ b/src/renderer/modules/contexts.js
@@ -9,10 +9,11 @@ let _ctxTree = []; // tree of {name, path, type:'dir'|'file', c
let _ctxExpanded = new Set(); // dir paths that are open
let _ctxActive = null; // {id, content} — currently opened file in right-pane
let _ctxPendingRename = null; // {path} — flagged for inline-rename on the
- // next renderCtxTree() (set by "新建文本"
- // after creating an untitled file so the
- // user can rename immediately, and by the
- // ⋯ menu's "重命名" item).
+ // next renderCtxTree() (set by the "new
+ // text file" action after creating an
+ // untitled file so the user can rename
+ // immediately, and by the ⋯ menu's
+ // "rename" item).
let _kbStatusByPath = {}; // {[path]: {status, chunks?, error?, kind?}}
let _kbEventsAbort = null;
@@ -199,7 +200,7 @@ function _renderCtxNodes(nodes, depth = 0) {
const active = _ctxActive && _ctxActive.id === n.path ? ' active' : '';
const ext = (n.name.split('.').pop() || '').toLowerCase();
const chip = _kbStatusChipHtml(n.path);
- // Inline-rename mode for a freshly-created "未命名.md" or for the rename
+ // Inline-rename mode for a freshly-created "untitled.md" or for the rename
// menu item — the label becomes an input autofocused with the stem
// selected. Committed on Enter / blur; Esc keeps the file as-is. See
// `_bindCtxTreeHandlers` for the handlers.
@@ -230,7 +231,7 @@ function _bindCtxTreeHandlers(container) {
const rel = wrap.dataset.path;
input.addEventListener('click', (e) => e.stopPropagation());
// Auto-select the stem (without extension) so the user overwrites the
- // "未命名" part but keeps ".md" if they just type.
+ // "untitled" stem but keeps ".md" if they just type.
const v = input.value;
const dot = v.lastIndexOf('.');
setTimeout(() => {
@@ -383,7 +384,7 @@ async function deleteCtxEntry(rel, kind) {
// Triggers in-place rename: flag the path and re-render so the label slot
// becomes an editable input. Commit handled by the existing inline-rename
// listeners in `_bindCtxTreeHandlers` → `_commitInlineRename`. Used by the
-// row ⋯ menu's "重命名" item.
+// row ⋯ menu's "rename" item.
function renameCtxEntry(rel /*, kind */) {
// For dirs being renamed: must be expanded so the row is rendered as an
// input. (Collapsed dirs whose ancestor is also collapsed wouldn't show.)
@@ -395,7 +396,7 @@ function renameCtxEntry(rel /*, kind */) {
// Open the per-row ⋯ popover menu. `kind` ∈ 'root' | 'dir' | 'file'.
// Menu items are dynamic per kind — file kind further subdivides on whether
-// the file is a text-editable type (controls the "编辑" item).
+// the file is a text-editable type (controls the "edit" item).
function _openCtxRowMenu(anchorBtn, kind, relPath) {
let menu = document.getElementById('ctx-row-menu');
if (!menu) {
@@ -571,9 +572,9 @@ async function _commitInlineRename(rel, nextBase) {
}
// Opens the "new directory" modal scoped to `parentDir` (relative, '' for
-// root). The old "新建" modal had tabs (dir / text) + a content textarea;
-// it's now directory-only — + 文本 creates a file inline (see
-// `createCtxNewTextFile`) without any modal.
+// root). The old "new" modal had tabs (dir / text) + a content
+// textarea; it's now directory-only — the "+ text" action creates a
+// file inline (see `createCtxNewTextFile`) without any modal.
async function promptCtxNewInDir(parentDir) {
_ctxNewTargetDir = parentDir || '';
document.getElementById('ctx-new-name').value = '';
@@ -622,12 +623,12 @@ async function saveCtxNew() {
}
window.saveCtxNew = saveCtxNew;
-// + 文本 handler — no modal. Writes an empty "未命名.md" (disambiguated if
+// "+ text" handler — no modal. Writes an empty "untitled.md" (disambiguated if
// one already exists in that dir), opens it in the right pane, flags it
// for inline rename on the next tree render, and immediately drops the
// viewer into edit mode so the user can start typing content.
async function createCtxNewTextFile(parentDir = '') {
- const stemBase = t('contexts.new.untitled_stem') || '未命名';
+ const stemBase = t('contexts.new.untitled_stem') || 'untitled';
// Collect sibling file names so we can uniquify if a conflict exists.
const siblings = _ctxListChildren(parentDir).map(n => n.name);
let stem = stemBase;
@@ -657,7 +658,7 @@ async function createCtxNewTextFile(parentDir = '') {
}
// Collect direct children of a dir path in the cached tree — used by
-// `createCtxNewTextFile` to uniquify "未命名.md" when a collision exists.
+// `createCtxNewTextFile` to uniquify "untitled.md" when a collision exists.
function _ctxListChildren(dirPath) {
if (!dirPath) return _ctxTree;
const parts = dirPath.split('/');
@@ -773,7 +774,7 @@ function _kindOfPath(rel) {
}
// Add every ancestor directory of `rel` to the expanded set. Called from
-// `openCtxFile` so deep-link navigation (global search → 知识库 file) unrolls
+// `openCtxFile` so deep-link navigation (global search → KB file) unrolls
// the tree to show where the file lives and why its row is marked active.
function _ctxExpandAncestors(rel) {
const parts = String(rel || '').split('/');
@@ -1038,8 +1039,8 @@ function initCtxBindings() {
e.stopPropagation();
_openCtxRowMenu(e.currentTarget, 'root', '');
});
- // Hidden file input — both root menu's "上传文件" and any folder row's
- // "上传文件" route through here. Target dir is stashed on dataset before
+ // Hidden file input — both the root menu's "upload file" item and any
+ // folder row's "upload file" route through here. Target dir is stashed on dataset before
// .click() so this single handler routes correctly.
document.getElementById('ctx-file-input')?.addEventListener('change', async (ev) => {
const input = ev.target;
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index 493f645a..d4d5fe63 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -175,7 +175,7 @@ if (typeof window !== 'undefined') {
// switching between conversations restores their distinct contexts) and
// stays sticky on view-enter — the only thing that overrides it is the
// auto-switch to a live interactive agent (see `_evaluateAutoRecipient`).
-// The new-chat ("指挥官") landing resets to commander only when its input
+// The new-chat (commander landing) resets to commander only when its input
// box is empty; otherwise the user's in-progress draft keeps its target.
const _COMMANDER = { kind: 'commander', id: '', name: '' };
const _RECIPIENT_LS_KEY = 'chat.recipientByCid';
@@ -270,7 +270,7 @@ function _renderRecipientChip(target) {
nameEl.removeAttribute('data-i18n');
} else {
nameEl.setAttribute('data-i18n', 'chat.recipient_commander');
- nameEl.textContent = (typeof t === 'function') ? t('chat.recipient_commander') : '指挥官';
+ nameEl.textContent = (typeof t === 'function') ? t('chat.recipient_commander') : 'Commander';
}
}
}
@@ -516,8 +516,10 @@ if (typeof window !== 'undefined') {
// "from-name" label rendered as a header chip on the bubble.
const GROUP_RESERVED = new Set(['user', 'commander']);
-// 指挥官头像偏好,懒加载缓存。聊天行渲染要用到 —— 第一次渲染前发一次 IPC,
-// 之后任何更新都同步刷这里。`null` = 未加载 / 取不到,渲染层自己回退到默认。
+// Commander avatar preference, lazy-loaded cache. Used by the chat row
+// renderer — fire one IPC before the first render, then refresh this
+// cache on every subsequent update. `null` = not loaded / unavailable;
+// the render layer falls back to the default itself.
let _commanderAvatarCache = null;
function _commanderAvatar() {
return _commanderAvatarCache || COMMANDER_DEFAULT;
@@ -529,7 +531,7 @@ async function _ensureCommanderAvatarLoaded() {
if (res?.ok && res.avatar) {
_commanderAvatarCache = { icon: res.avatar.icon, color: res.avatar.color };
}
- } catch (_) { /* 走默认 */ }
+ } catch (_) { /* fall back to default */ }
return _commanderAvatarCache || COMMANDER_DEFAULT;
}
function setCommanderAvatarCache(avatar) {
@@ -537,15 +539,17 @@ function setCommanderAvatarCache(avatar) {
_commanderAvatarCache = { icon: avatar.icon, color: avatar.color };
}
}
-/** 渲染消息行头像。fromId 已知非 'user'。 */
+/** Render the message row avatar. `fromId` is known to be non-'user'. */
function _renderActorAvatarHtml(fromId) {
if (fromId === 'commander') {
const a = _commanderAvatar();
return renderAvatarHtml(a.icon, a.color, { size: 28, seed: 'commander' });
}
- // 全局 agents registry 优先 —— 它始终是当前真相;群成员缓存只是入会时
- // 的快照,改名 / 改头像后不会跟着动,作为兜底覆盖"agent 已被删除、
- // registry 查不到"的旧会话场景。
+ // The global agents registry takes priority — it's always the current
+ // truth. The per-group member cache is just a join-time snapshot and
+ // does not follow rename / avatar changes, so it serves as fallback
+ // for legacy conversations whose agent has since been deleted from
+ // the registry.
let icon, color;
if (typeof _agentsCache !== 'undefined' && Array.isArray(_agentsCache)) {
const a = _agentsCache.find((x) => x && x.agent_id === fromId);
@@ -568,7 +572,7 @@ function _renderActorAvatarHtml(fromId) {
* (deleted agents whose old chats still need a label). */
function _groupActorLabel(fromId) {
if (fromId === 'user') return null;
- if (fromId === 'commander') return t('chat.from_commander') || '指挥官';
+ if (fromId === 'commander') return t('chat.from_commander') || 'Commander';
if (typeof _agentsCache !== 'undefined' && Array.isArray(_agentsCache)) {
const a = _agentsCache.find((x) => x && x.agent_id === fromId);
if (a && a.name) return a.name;
@@ -581,7 +585,7 @@ function _groupActorLabel(fromId) {
// Last resort: never leak the id. Show a neutral placeholder; the chip
// will repaint as soon as the cache catches up (state_changed handler
// refreshes _groupMembersCache).
- return t('chat.from_agent_unknown') || '智能体';
+ return t('chat.from_agent_unknown') || 'Agent';
}
const _groupMembersCache = new Map(); // cid → Actor[]
async function _refreshGroupMembers(cid) {
@@ -635,11 +639,11 @@ function _groupMsgToLegacy(gm) {
// ─── Chat attachments (pending-send pool per cid) ─────────────────────────
// User picks files via "+" → we upload them to `<cid>/` and remember them in
// this Map. On send we hand the filenames to the server; on success the list
-// for that cid is cleared (消息粒度). Each entry is {name, kind, bytes, dataUrl?}.
+// for that cid is cleared (per-message granularity). Each entry is {name, kind, bytes, dataUrl?}.
const _chatAttachments = new Map(); // cid → Array<{name, kind, bytes, dataUrl?}>
-// Draft cid used by 总指挥 (new-chat) tab — files land under
+// Draft cid used by the commander (new-chat) tab — files land under
// `data/<uid>/chat_attachments/main_chat/` until the user hits send, at which
// point the backend renames that dir to the freshly-minted conversation cid
// (see `adoptDraftAttachments`).
@@ -689,7 +693,7 @@ function _chatAttachClear(cid) {
_chatAttachRenderChips(cid);
}
-// cid → DOM host id for the chip row. Draft cid (总指挥) renders into the
+// cid → DOM host id for the chip row. Draft cid (commander tab) renders into the
// new-chat panel; any real cid renders into the active conversation panel
// only when it matches currentCid (stale states for other cids stay in the
// Map but aren't painted).
@@ -937,9 +941,10 @@ function _iconForProduced(name) {
function _renderMessageProducedHtml(absPaths) {
// Chip shows just the filename. The full absolute path lives only in
// `data-produced-path` for the click handler; tooltip is a static
- // localised "在文件夹中显示" hint instead of the raw OS path (which
- // exposes the user's home dir and is hostile UX in Chinese mixed-case).
- const hint = t('chat.produced_reveal_title') || '在文件夹中显示';
+ // localized "show in folder" hint instead of the raw OS path (which
+ // exposes the user's home directory and is hostile UX in mixed-locale
+ // contexts).
+ const hint = t('chat.produced_reveal_title') || 'Show in folder';
const items = absPaths.map((p) => {
const base = p.split(/[\\/]/).pop() || p;
const icon = _iconForProduced(base);
@@ -951,14 +956,14 @@ function _renderMessageProducedHtml(absPaths) {
return `<div class="chat-msg-produced">${items.join('')}</div>`;
}
-// Render a "查看详情" chip on an assistant bubble when a new agent was
+// Render a "view details" chip on an assistant bubble when a new agent was
// quick-created from that turn. Click → jump to agents tab + select the new
// agent. Same visual slot as produced chips (inside the bubble, below
// content), but in .is-custom green to signal "new custom artifact created".
function _renderMessageCreatedAgentHtml(payload) {
if (!payload || !payload.agent_id) return '';
const name = payload.name || payload.agent_id;
- // Label is intentionally neutral ("查看详情 / Open: …") — works for both
+ // Label is intentionally neutral ("view details / Open: …") — works for both
// `kind: 'created'` and `kind: 'updated'`; the commander's surrounding
// prose tells the user which one happened. Don't split the i18n key just
// to track the verb — the chip is a CTA into the agent panel, not a
@@ -1062,9 +1067,12 @@ function _initChatAttachInput() {
btn.dataset.bound = '1';
}
-// 总指挥 (new-chat) tab 的 "+" 按钮走同一套上传链路,只是传 DRAFT_CID 而不
-// 是某个会话的 cid。用户点发送后 handleNewChatSubmit 会调 adopt 把整个
-// `main_chat/` 目录改名成新会话的 cid,预处理缓存原地跟随无需重跑。
+// The commander (new-chat) tab's "+" button uses the same upload
+// pipeline; the only difference is that it passes DRAFT_CID instead of
+// a real conversation cid. After the user clicks send,
+// handleNewChatSubmit calls adopt to rename the whole `main_chat/`
+// directory to the freshly-minted cid; the pre-processing cache
+// follows in place and doesn't need to be rerun.
function _initNewChatAttachInput() {
const btn = document.getElementById('new-chat-attach-btn');
@@ -1151,7 +1159,7 @@ function renderConversationList() {
// ─── Conversation history render ───
-// Inline "创建智能体" entry that lives at the very end of the conversation
+// Inline "create agent" entry that lives at the very end of the conversation
// history — visually a divider with a small button in the middle, anchored
// to the last message. Hidden while a stream is in flight (the scroll-pin
// spacer is present then) so it doesn't tempt the user to sediment a
@@ -1189,11 +1197,15 @@ function _ensureConvCreateAgentInline() {
}
const hasUserMsg = !!container.querySelector('.chat-message.user');
const isStreaming = !!spacer;
- // 一旦有非 commander/user 的 agent 进入对话就隐藏入口 —— 多 agent 流里
- // "沉淀单一 agent" 的语义已不成立。两路证据都算:
- // 1) 群成员名册里出现 kind==='agent'(最权威:包含被 @ 但还没回话的);
- // 2) DOM 里出现过 _from / fromActor 既非空也非 commander/user 的发言
- // (兜底:成员缓存还没拉到时也能触发)。
+ // Once any agent (other than commander / user) joins the conversation,
+ // hide the entry — in a multi-agent flow the "promote a single agent"
+ // semantic no longer holds. Either signal counts:
+ // 1) The roster contains a member with kind === 'agent' (most
+ // authoritative — includes agents that were @-mentioned but
+ // haven't spoken yet).
+ // 2) The DOM contains an utterance whose _from / fromActor is
+ // non-empty and not commander/user (fallback that fires before
+ // the member cache loads).
const members = _groupMembersCache.get(currentCid) || [];
const hasAgentMember = members.some((a) => a && a.kind === 'agent');
const hasAgentMsg = hasAgentMember || Array.from(
@@ -1239,7 +1251,7 @@ async function loadConversationHistory(cid) {
// Members cache MUST be populated before we render history bubbles —
// appendChatMessage calls _groupActorLabel which uses this cache to
// resolve agent_id → name. Without the await we'd briefly show
- // "智能体" placeholders on first paint and repaint on refresh, ugly.
+ // generic "agent" placeholders on first paint and have to repaint on refresh, which is ugly.
await _refreshGroupMembers(cid);
// Conversation switch: drop any stale per-actor placeholders from a
// previous conv so they don't leak into this view (their DOM nodes
@@ -1250,7 +1262,7 @@ async function loadConversationHistory(cid) {
}
// Drop internal plan-step dispatch messages (commander → agent
// hand-off). The user already saw the plan announcement; surfacing
- // these adds noise like "@需求挖掘师 我要开发一个应用" in the user's view.
+ // these adds noise (e.g. "@<agent-name> <user request>") in the user's view.
// The agent's visibility slice still carries them so the agent has
// the dispatch text in its own context.
const history = (data.history || [])
@@ -1268,7 +1280,7 @@ async function loadConversationHistory(cid) {
}
// Detect unanswered user message (e.g. after page refresh while server was processing).
- // Only show the "思考中…" bubble if the server *really* still has this
+ // Only show the "thinking…" bubble if the server *really* still has this
// conversation in processing state AND the work started recently — a stale
// `processing: true` from a crashed prior run is swept on boot, but we
// also belt-and-braces check the flag here so no flash occurs.
@@ -1299,7 +1311,7 @@ async function loadConversationHistory(cid) {
// in closure and keeps dispatching deltas/final to that *specific* node
// — so we must re-attach the original node, not mint a fresh bubble.
// Minting a new one here (as before) stranded the stream: events kept
- // landing on the orphaned node and the new bubble stayed at "思考中…"
+ // landing on the orphaned node and the new bubble stayed at "thinking…"
// until stream end / polling rescue.
const state = pendingConvs.get(cid);
pollMsgCounts.set(cid, history.length);
@@ -1319,7 +1331,7 @@ async function loadConversationHistory(cid) {
startPolling(cid); // ensure polling is running as backup
}
- // Re-add the inline "创建智能体" entry BEFORE scrolling so it's part of
+ // Re-add the inline "create agent" entry BEFORE scrolling so it's part of
// scrollHeight when we jump to the bottom — otherwise the MutationObserver
// adds it post-scroll and it ends up below the visible area.
_ensureConvCreateAgentInline();
@@ -1400,13 +1412,13 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
? ''
: _groupActorLabel(message._from || (message._from_label ? '' : ''))
|| message._from_label
- || (t('chat.from_agent_unknown') || '智能体');
+ || (t('chat.from_agent_unknown') || 'Agent');
const avatarHtml = role === 'user' ? '' : _renderActorAvatarHtml(message._from);
const headerHtml = role === 'user'
? `<div class="chat-msg-header chat-msg-header-user"><span class="chat-msg-time">${formatTime(message.time || new Date().toISOString())}</span></div>`
: `<div class="chat-msg-header">${avatarHtml}<span class="chat-msg-from">${escapeHtml(headerName)}</span><span class="chat-msg-time">${formatTime(message.time || new Date().toISOString())}</span></div>`;
const planAnnHtml = message._plan_announcement
- ? `<div class="chat-plan-announce">📋 ${escapeHtml(t('chat.plan_announce') || '执行计划')}</div>` : '';
+ ? `<div class="chat-plan-announce">📋 ${escapeHtml(t('chat.plan_announce') || 'Plan')}</div>` : '';
// Below-bubble action row holds produced-file chips + created-agent chip
// + archive button (the legacy `.chat-meta` slot). Lives OUTSIDE the
// bubble so chips read as a footer, not as inline body content.
@@ -1447,7 +1459,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
}
}
// Archive button + persisted-process block only make sense for finalised
- // assistant replies (raw markdown, not an HTML placeholder like "思考中...").
+ // assistant replies (raw markdown, not an HTML placeholder like "thinking...").
if (role === 'assistant' && !isHtmlSnippet) {
if (archive) _attachBubbleArchiveBtn(msgDiv, () => rawContent);
if (Array.isArray(message.process) && message.process.length) {
@@ -1455,7 +1467,10 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
// trail IS the content the user already saw, hiding it behind a fold
// makes refresh look like "everything I watched stream is gone".
const bodyText = String(displayContent || '').trim();
- const isAbortStub = bodyText === '(已中断)' || bodyText === '';
+ // Match both possible forms — jsonl history can carry either depending
+ // on the UI language at the time of write (i18n key `model.aborted` →
+ // '(stopped)' in en, '(已中断)' in zh).
+ const isAbortStub = bodyText === '(已中断)' || bodyText === '(stopped)' || bodyText === '';
_renderPersistedProcess(msgDiv, message.process, { expanded: isAbortStub });
}
}
@@ -1518,13 +1533,14 @@ function _mountChatInputForm(host, msgDiv, message, opts) {
});
}
-// Insert a "过程信息" block above the assistant bubble content using the
-// items we stored at stream time. Collapsed by default so old threads
-// stay tidy; user can click ▶ to expand. Exception: when the bubble's
-// text body has no real reply (only "(已中断)" / empty abort placeholder
-// for a turn that never produced final text), the process trail IS the
-// content — auto-open it so refreshing doesn't appear to erase what the
-// user already watched stream in (tool calls / progress lines).
+// Insert a "process info" block above the assistant bubble content
+// using the items we stored at stream time. Collapsed by default so
+// old threads stay tidy; the user can click ▶ to expand. Exception:
+// when the bubble's text body has no real reply (only the "(stopped)"
+// abort placeholder or empty content for a turn that never produced
+// final text), the process trail IS the content — auto-open it so
+// refreshing doesn't appear to erase what the user already watched
+// stream in (tool calls / progress lines).
function _renderPersistedProcess(msgDiv, items, { expanded = false } = {}) {
const bubble = msgDiv.querySelector('.chat-bubble');
if (!bubble) return;
@@ -1643,7 +1659,7 @@ function applyQuotePrefix(raw, target) {
return raw ? `${block}\n\n${raw}` : block;
}
-// Attach a small "存档" button next to the time in the chat-meta row. Kept
+// Attach a small "archive" button next to the time in the chat-meta row. Kept
// outside the bubble so it never overlaps bubble content. `getContent` is a
// callback so it can return the latest text after streaming completes.
function _attachBubbleArchiveBtn(msgDiv, getContent) {
@@ -2009,10 +2025,13 @@ function _setChatScrollOffset(on, containerOrId = 'chat-history') {
spacer.className = 'chat-scroll-spacer';
container.appendChild(spacer);
}
- // 只补足"让最后一条 user 消息能滚到顶部"所需的高度——视口高度减去
- // (user 消息及其下方已有兄弟节点)。一律给一整屏会在回复尚短时留下
- // 大片空白;这里精算所需余量,回复短时就只剩一点点空白。-24 与
- // _scrollToMessageTop 的偏移对齐,给 floating 删除按钮留出位置。
+ // Only top up enough height to "let the last user message scroll to
+ // the top" — viewport height minus (the user message and any
+ // siblings already after it). Always reserving a full viewport leaves
+ // a big blank when the reply is short; this exact-fit calculation
+ // makes the blank shrink to almost nothing for short replies. The
+ // -24 matches _scrollToMessageTop's offset, leaving room for the
+ // floating delete button.
const userMsgs = container.querySelectorAll(':scope > .chat-message.user');
const lastUser = userMsgs[userMsgs.length - 1];
let needed = container.clientHeight - 24;
@@ -2102,7 +2121,7 @@ function _createStreamingAssistantMessage(container) {
// with a freshly-rendered one carrying the right name.
// Header is intentionally empty until we know who's actually working.
// The bus may route the user's `@<name>` message to commander OR an
- // agent depending on resolution; hard-coding "指挥官" misled the user
+ // agent depending on resolution; hard-coding "commander" misled the user
// when @-routing succeeded. Once the first state_changed event
// identifies the in-flight actor we'll fill the chip in (see
// _handleGroupBusEvent's state_changed branch).
@@ -2157,7 +2176,7 @@ function _processKindOf(text) {
}
function _streamingAppendProgress(msg, text) {
- // Keep the "思考中…" row visible alongside the process trace — hiding it
+ // Keep the "thinking…" row visible alongside the process trace — hiding it
// while only process info shows makes long tool runs look stuck. The row
// is cleared when the final reply (or an error) arrives.
const container = msg.querySelector('[data-role="process-container"]');
@@ -2191,7 +2210,7 @@ function _cancelPendingStreamRaf(msg) {
}
// Paint the final reply into a streaming bubble. Caller controls whether
-// to attach the 存档 button afterwards (not all scenes want it — skill and
+// to attach the archive button afterwards (not all scenes want it — skill and
// agent edit chats skip it by design).
function _streamingSetFinal(msg, text, { archive = false } = {}) {
_hideThinking(msg);
@@ -2221,18 +2240,26 @@ function _streamingSetFinal(msg, text, { archive = false } = {}) {
live.textContent = t('chat.stream_done');
}
- // Auto-collapse the process section so the finalised reply reads cleanly;
- // 但若整轮流式从未产生过 progress 行(比如模型直接一句回答,无推理 / 工具调
- // 用),保留起始的 display:none,不在气泡里显示空的「过程信息」起泡。
- // **例外**:如果 final body 只是 "(已中断)" 这种无实质内容的中断占位符,
- // 过程信息就是用户实际看到的全部输出——保持展开,否则 finalize 后视觉上
- // 等同于"流式时看的过程都没了"(用户原话),刷新更看不到。
+ // Auto-collapse the process section so the finalised reply reads
+ // cleanly. But if the entire streaming turn never produced a progress
+ // line (e.g. the model answered in one shot with no reasoning / tool
+ // calls), keep the initial display:none so we don't render an empty
+ // "process info" bubble.
+ // **Exception**: when the final body is just an empty/abort stub
+ // (i.e. the "(stopped)" placeholder for a turn that never produced
+ // real text), the process trail IS the user-visible output — keep
+ // it expanded; otherwise the user perceives it as "the process I
+ // just watched stream is gone after finalize", which gets worse on
+ // refresh.
const details = msg.querySelector('.stream-process');
if (details) {
const body = details.querySelector('.stream-process-body');
const hasProcess = !!body && body.children.length > 0;
const bodyText = String(display || '').trim();
- const isAbortStub = bodyText === '(已中断)' || bodyText === '';
+ // Match both possible forms — jsonl history can carry either depending
+ // on the UI language at the time of write (i18n key `model.aborted` →
+ // '(stopped)' in en, '(已中断)' in zh).
+ const isAbortStub = bodyText === '(已中断)' || bodyText === '(stopped)' || bodyText === '';
if (hasProcess && isAbortStub) {
details.open = true;
details.style.display = '';
@@ -2241,7 +2268,7 @@ function _streamingSetFinal(msg, text, { archive = false } = {}) {
details.style.display = '';
} else {
details.removeAttribute('open');
- // else: 保留 display:none(_createStreamingAssistantMessage 的初始值)
+ // else: keep display:none (the initial value set by _createStreamingAssistantMessage).
}
}
}
@@ -2255,9 +2282,11 @@ function _streamingSetError(msg, text) {
live.classList.remove('stream-process-live');
live.textContent = (live.textContent || '').replace(/^◐ /, '◯ ') || t('chat.stream_done');
}
- // 出错时也要保留已累积的过程信息:若 body 非空就显示(与 _streamingSetFinal /
- // _streamingMarkAborted 一致),不再等用户重进对话才从持久化 message.process
- // 补画出来。
+ // On error we also preserve the accumulated process info: if the
+ // body is non-empty we display it (matching _streamingSetFinal /
+ // _streamingMarkAborted), so the user no longer has to reopen the
+ // conversation to see it backfilled from the persisted
+ // message.process.
const details = msg.querySelector('.stream-process');
if (details) {
const body = details.querySelector('.stream-process-body');
@@ -2287,7 +2316,7 @@ function _streamingSetError(msg, text) {
}
// Mark the assistant bubble as user-interrupted. Preserves whatever partial
-// content streamed into the process pane; just stamps a "已中断" note.
+// content streamed into the process pane; just stamps a "stopped" note.
function _streamingMarkAborted(msg) {
_hideThinking(msg);
// Freeze any live preview line so it's not misread as still generating.
@@ -2327,8 +2356,10 @@ function _scrollToMessageTop(msgEl, containerId = 'chat-history') {
requestAnimationFrame(() => requestAnimationFrame(() => {
const containerRect = container.getBoundingClientRect();
const msgRect = msgEl.getBoundingClientRect();
- // 仅预留能让 floating 删除按钮(top:20px + ~33px 高)不贴住消息的最小
- // 间距;留白太大时容易看到上一条消息产生干扰。24px = 贴着删除按钮底沿。
+ // Reserve only enough margin so the floating delete button
+ // (top:20px + ~33px tall) doesn't sit flush against the message;
+ // a larger blank exposes the previous message and feels noisy.
+ // 24px lines up with the bottom of the delete button.
const offset = msgRect.top - containerRect.top + container.scrollTop - 24;
// Force auto behavior so the jump is immediate — the CSS default of
// scroll-behavior:smooth would otherwise animate and get interrupted by
@@ -2357,7 +2388,7 @@ function _scrollToMessageTop(msgEl, containerId = 'chat-history') {
// historyEndpoint(id): returns the URL for GET history
// clearEndpoint(id): (optional) URL for DELETE history
// features: {
-// archive: bool // attach 存档 button on final
+// archive: bool // attach archive button on final
// scrollPin: bool // pin newly-sent user message to top of viewport
// }
// hooks: {
@@ -2685,10 +2716,13 @@ function createChatController(config) {
const msgEl = _createStreamingAssistantMessage(historyEl);
if (hooks.onAssistantStart) hooks.onAssistantStart(msgEl, id);
- // 发送时把用户消息顶到可视区顶部就行;流式过程中和结束后都不要再主动
- // 滚动,否则会把用户中途上滑查看的位置强行拽回初始位置。
- // 配合 `has-scroll-offset` 预留 100vh 底部空间,保证短消息也能滚到顶部;
- // 由 controller 统一负责开关,避免各 scene 各自抄一份。
+ // On send, pin the user's message to the top of the viewport once;
+ // do NOT scroll during or after streaming — that would yank a user
+ // who scrolled up mid-stream back to the initial position.
+ // Paired with `has-scroll-offset` reserving 100vh of bottom
+ // space so even short messages can be scrolled to the top; the
+ // controller is responsible for toggling it so each scene doesn't
+ // copy-paste the same logic.
if (features.scrollPin) {
_setChatScrollOffset(true, historyEl);
_scrollToMessageTop(userMsgEl, historyEl.id);
@@ -2725,7 +2759,7 @@ function createChatController(config) {
try {
const ev = JSON.parse(dataLines.join('\n'));
// Post-abort events can still arrive while main's for-await drains
- // its buffer — drop them so the bubble stays frozen at "已中断"
+ // its buffer — drop them so the bubble stays frozen at the "stopped" state
// instead of accumulating more deltas / a final reply behind it.
if (pending?.aborted) continue;
_handleStreamEvent(id, msgEl, ev, { archive: features.archive });
@@ -2754,7 +2788,8 @@ function createChatController(config) {
_updateSendUI();
if (features.scrollPin) _setChatScrollOffset(false, historyEl);
if (hooks.onDone) hooks.onDone(msgEl, id, { aborted: wasAborted, errored: wasErrored });
- // 不再在流式结束时 re-pin — 尊重用户中途上滑后的阅读位置。
+ // No re-pin at stream end — respect the user's scroll position
+ // if they scrolled up mid-stream.
// Drain one queued message if any, matching main-chat behaviour.
if (features.queue) _qDispatchNext();
}
@@ -2766,7 +2801,7 @@ function createChatController(config) {
try { pending.controller.abort(); } catch (_) {}
// Main's for-await loop only checks `cancelled` between yields, so it
// can take a while to emit `done` — that means _streamingMarkAborted
- // (called from the catch block) runs late and the "思考中…" row stays
+ // (called from the catch block) runs late and the "thinking…" row stays
// visible. Mark the bubble now so the UI terminates on click, and rely
// on reader-loop gating (pending.aborted) to drop any stragglers.
if (pending.msgEl) {
@@ -2905,8 +2940,8 @@ function _setPlaceholderActor(ph, actorId) {
const chip = ph.querySelector('[data-role="from-chip"]');
if (chip && !chip.textContent) {
const label = actorId === 'commander'
- ? (t('chat.from_commander') || '指挥官')
- : (_groupActorLabel(actorId) || (t('chat.from_agent_unknown') || '智能体'));
+ ? (t('chat.from_commander') || 'Commander')
+ : (_groupActorLabel(actorId) || (t('chat.from_agent_unknown') || 'Agent'));
chip.textContent = label;
}
const avatarSlot = ph.querySelector('[data-role="from-avatar"]');
@@ -2995,7 +3030,7 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
if (bubble && !bubble.querySelector('.chat-plan-announce')) {
const lbl = document.createElement('div');
lbl.className = 'chat-plan-announce';
- lbl.textContent = `📋 ${t('chat.plan_announce') || '执行计划'}`;
+ lbl.textContent = `📋 ${t('chat.plan_announce') || 'Plan'}`;
bubble.insertBefore(lbl, bubble.firstChild);
}
}
@@ -3256,7 +3291,7 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
const hasProcess = !!processBody && processBody.children.length > 0;
if (hasProcess) {
// Freeze the bubble: hide thinking dots, leave process rail as
- // a folded "已完成思考" bubble. Empty final body = no main text.
+ // a folded "completed thinking" bubble. Empty final body = no main text.
if (typeof _streamingSetFinal === 'function') {
_streamingSetFinal(ph, '', { archive: false });
}
@@ -3274,7 +3309,7 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
}
}
-// Append the "查看详情" chip into a streaming bubble. Idempotent: duplicate
+// Append the "view details" chip into a streaming bubble. Idempotent: duplicate
// calls (relay event + final-event payload) are de-duped by checking for an
// existing `.chat-msg-created-agent` child.
function _mountCreatedAgentChip(msg, payload) {
@@ -3325,7 +3360,7 @@ function _stripSubmissionTagForDisplay(text) {
// Wrap placeholder text in an HTML `<em>` instead of markdown `_text_`:
// standard markdown requires word-boundary chars on each side of `_` for
// italic emphasis, and CJK glyphs don't count as word boundaries, so
-// `_中文占位_` renders with the underscores visible. `<em>` passes through
+// `_<CJK placeholder>_` renders with the underscores visible. `<em>` passes through
// renderMarkdownFull as-is (HTML inline tags are preserved by the markdown
// pipeline) and actually italicises the CJK text.
function _streamPlaceholderHtml(key) {
@@ -3380,7 +3415,7 @@ function _stripAgentFormBlockForStream(buf) {
// Progressive renderer — append an assistant text delta into the final
// bubble and re-render markdown. The first delta reveals the `[data-role=final]`
-// container; the "思考中" row stays visible BELOW the body until the terminal
+// container; the "thinking" row stays visible BELOW the body until the terminal
// `final` / error / aborted event lands (so the user sees "partial reply +
// still typing" instead of "partial reply + nothing happening"; the row is
// rendered after `.stream-final` in `_createStreamingAssistantMessage`).
@@ -3432,13 +3467,13 @@ function _streamingAppendFinalDelta(msg, piece) {
// Icon palette (Unicode Geometric Shapes per CLAUDE.md §8). Each glyph has
// exactly one semantic role — stick to this table when adding new streams:
//
-// ▶ 推理开始 ● 推理完成
-// ◆ 思考 ◇ 回复(最终)
-// ◐ 正在生成(live)
-// ■ 工具调用 ▣ 计划
-// ▷ 命令输出 ◉ 文件改动
-// ○ 等待确认 ◯ 错误
-// ▪ 其他/兜底
+// ▶ reasoning start ● reasoning done
+// ◆ thinking ◇ reply (final)
+// ◐ generating (live)
+// ■ tool call ▣ plan
+// ▷ command output ◉ file change
+// ○ awaiting confirmation ◯ error
+// ▪ other / fallback
function _formatEventLine(evt) {
if (!evt || typeof evt !== 'object') return null;
const { stream, data } = evt;
@@ -3576,7 +3611,7 @@ function _renderAgentEvent(msg, evt) {
// Used for streaming text (assistant deltas) that grows over time.
function _streamingUpdateLive(msg, prefix, text, appendDelta) {
// Assistant deltas are still "in progress" from the user's perspective —
- // leave the 思考中 row alone; it's cleared by _streamingSetFinal.
+ // leave the "thinking" row alone; it's cleared by _streamingSetFinal.
const container = msg.querySelector('[data-role="process-container"]');
if (container) container.style.display = '';
const body = msg.querySelector('[data-role="process"]');
@@ -3721,7 +3756,7 @@ function _updateConvSidebarBadge(cid, _unused) {
item.querySelector('.conv-status-badge')?.remove();
// Treat aborted-but-still-draining as not streaming. `pendingConvs` only
// clears when main emits `done`, which can trail the stop click; until then
- // the bubble already shows "已中断" so the streaming badge would lie.
+ // the bubble already shows the "stopped" state so the streaming badge would lie.
const state = pendingConvs.get(cid);
const pending = !!state && !state.aborted;
// Use _getQueue so a queue persisted in localStorage is picked up even if
@@ -3737,7 +3772,7 @@ function _updateConvSidebarBadge(cid, _unused) {
let html = '';
if (pending) {
html += '<span class="conv-status-dot"></span>';
- // html += '<span class="conv-status-text">回复中</span>';
+ // html += '<span class="conv-status-text">replying</span>';
if (queued > 0) html += `<span class="conv-status-count">+${queued}</span>`;
} else {
html += `<span class="conv-status-text">${escapeHtml(t('chat.status.pending_short'))}</span>`;
diff --git a/src/renderer/modules/dialogs.js b/src/renderer/modules/dialogs.js
index b81102fb..a958dd9e 100644
--- a/src/renderer/modules/dialogs.js
+++ b/src/renderer/modules/dialogs.js
@@ -1,10 +1,14 @@
// ─── Custom dialogs (replace native confirm/alert) ──────────────────────
// Native `confirm()` / `alert()` render OS-locale buttons ("OK"/"Cancel").
-// These helpers give us 取消 / 确认 every time and match the rest of the
-// modal UI. Both return a Promise — callers must `await`.
+// These helpers give us a localized cancel / confirm pair every time
+// and match the rest of the modal UI. Both return a Promise — callers
+// must `await`.
-// Pre-boot, `t()` may not yet have tables loaded — fall back to Chinese
-// source strings so the dialog never renders blank if triggered early.
+// Pre-boot, `t()` may not yet have tables loaded — fall back to a
+// Chinese source string so the dialog never renders blank if triggered
+// early. (The fallback string itself is intentionally left as Chinese
+// to match the historical default; the i18n key takes over once tables
+// load.)
function _dialogLabel(key, zhFallback) {
try { const v = t(key); return v === key ? zhFallback : v; } catch (_) { return zhFallback; }
}
@@ -14,8 +18,8 @@ function _uiShowDialog({ message, showCancel }) {
const overlay = document.createElement('div');
overlay.className = 'modal-overlay ui-dialog-overlay open';
const msgHtml = escapeHtml(String(message || '')).replace(/\n/g, '<br />');
- const cancelText = escapeHtml(_dialogLabel('common.cancel', '取消'));
- const okText = escapeHtml(_dialogLabel('common.confirm', '确认'));
+ const cancelText = escapeHtml(_dialogLabel('common.cancel', 'Cancel'));
+ const okText = escapeHtml(_dialogLabel('common.confirm', 'Confirm'));
overlay.innerHTML = `
<div class="modal ui-dialog" role="dialog" aria-modal="true">
<div class="ui-dialog-message">${msgHtml}</div>
@@ -59,15 +63,15 @@ function uiAlert(message) {
return _uiShowDialog({ message, showCancel: false }).then(() => {});
}
-// Text-input prompt with 取消 / 确认 buttons. Returns the entered string, or
+// Text-input prompt with cancel / confirm buttons. Returns the entered string, or
// null on cancel. Mirrors native `prompt()` semantics.
function uiPrompt(message, defaultValue = '') {
return new Promise((resolve) => {
const overlay = document.createElement('div');
overlay.className = 'modal-overlay ui-dialog-overlay open';
const msgHtml = escapeHtml(String(message || '')).replace(/\n/g, '<br />');
- const cancelText = escapeHtml(_dialogLabel('common.cancel', '取消'));
- const okText = escapeHtml(_dialogLabel('common.confirm', '确认'));
+ const cancelText = escapeHtml(_dialogLabel('common.cancel', 'Cancel'));
+ const okText = escapeHtml(_dialogLabel('common.confirm', 'Confirm'));
overlay.innerHTML = `
<div class="modal ui-dialog" role="dialog" aria-modal="true">
<div class="ui-dialog-message">${msgHtml}</div>
diff --git a/src/renderer/modules/local-agents.js b/src/renderer/modules/local-agents.js
index e3000452..bc7697ba 100644
--- a/src/renderer/modules/local-agents.js
+++ b/src/renderer/modules/local-agents.js
@@ -1,8 +1,8 @@
// ─── Local CLI agents (renderer side) ─────────────────────────────────
//
// Two surfaces share this module:
-// 1. The agent-modal "外接" tab — selector lists every detected CLI
-// (default: 未选择). Selecting one auto-fills name + description
+// 1. The agent-modal "external" tab — selector lists every detected CLI
+// (default: "not selected"). 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)
@@ -86,16 +86,17 @@ async function loadLocalCliEntries({ force = false } = {}) {
// ── External-tab CLI selector (create modal) ───────────────────────────
//
-// Sentinel value for "未选择" — distinct from empty string so a user who
+// Sentinel value for "not selected" — 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;
/**
- * 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
+ * Mount the External-tab CLI selector. Default option is "not
+ * selected"; detected CLIs follow. `onChange` fires with the chosen
+ * `LocalCliType` (string) or null when the user reverts to the "not
+ * selected" sentinel — 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
@@ -106,7 +107,7 @@ async function mountExternalCliSelect(onChange) {
if (!mount) return null;
const entries = await loadLocalCliEntries();
const available = entries.filter(e => e.available);
- const noneLabel = t('agent_modal.ext_cli_none') || '未选择';
+ const noneLabel = t('agent_modal.ext_cli_none') || '(none)';
const options = [
{ value: EXT_CLI_NONE, label: noneLabel },
...available.map(e => ({
@@ -131,7 +132,7 @@ async function mountExternalCliSelect(onChange) {
}
/** Read the currently-selected CLI type from the External tab, or null
- * when the user kept "未选择". */
+ * when the user kept the "not selected" sentinel. */
function getExternalCliValue() {
const v = _extCliSelectApi ? _extCliSelectApi.getValue() : EXT_CLI_NONE;
if (!v || v === EXT_CLI_NONE) return null;
@@ -139,7 +140,8 @@ function getExternalCliValue() {
}
/** Programmatically set the External-tab selector (used by edit form
- * to seed from the bound CLI). Pass null to revert to 未选择. */
+ * to seed from the bound CLI). Pass null to revert to the "not
+ * selected" sentinel. */
function setExternalCliValue(cliType) {
if (!_extCliSelectApi) return;
_extCliSelectApi.setValue(cliType || EXT_CLI_NONE);
diff --git a/src/renderer/modules/pinyin-firstletter.js b/src/renderer/modules/pinyin-firstletter.js
index 4cde5b77..08e99e65 100644
--- a/src/renderer/modules/pinyin-firstletter.js
+++ b/src/renderer/modules/pinyin-firstletter.js
@@ -1,23 +1,34 @@
-// 中文 → 拼音首字母 工具 (sort key only)。
+// Chinese → pinyin first-letter utility (sort key only).
//
-// Why: Electron 自带的是 small ICU,Intl.Collator 不带 zh pinyin tailoring,
-// 所有 -u-co-pinyin / 'zh-Hans-CN' 的形式都会静默回落到笔画/编码序,导致
-// 中英文混排排序时所有汉字堆一起、英文堆一起,用户感知就是"乱"。
-// 这里加载 vendor/pinyin-firstletter/data.js 提供的 Unicode → 首字母 表
-// (拼音首字母数据来自 pinyinjs / 小茗同学,MIT),把字符串展平成"按首
-// 字母拼起来"的 sort key,然后用普通字符串比较即可。
+// Why: Electron ships small ICU, and Intl.Collator does not include
+// zh pinyin tailoring, so all `-u-co-pinyin` / `'zh-Hans-CN'` forms
+// silently fall back to stroke / code-point order. The result is that
+// when CJK and ASCII names are mixed, every Chinese character clumps
+// together and every Latin name clumps together — users perceive this
+// as "random ordering".
+// We load the Unicode → first-letter table provided by
+// vendor/pinyin-firstletter/data.js (data sourced from pinyinjs by
+// Xiaoming, MIT) and flatten each string into a "concatenated
+// first-letters" sort key, then compare those keys with plain string
+// comparison.
//
-// 数据范围:CJK Unified Ideographs U+4E00..U+9FA5(覆盖 6763 一级 + 大多
-// 二级汉字),范围外的字符按原样保留(让标点/Latin/数字按 ASCII 序参与比较)。
-// 不读 polyphone 多音字表 —— 实测主表 dict.all 已经是"日常高频读音"
-// (乐→L 乐观、行→H 银行、长→Z 长大),polyphone 反而把次要读音排在
-// 第一位(乐 polyphone='YL',首读 yuè),覆盖会让"乐观大胆派"被排到 y 段
-// 而不是 l 段。排序场景不需要多音区分,直接用主表的高频读音最准。
+// Coverage: CJK Unified Ideographs U+4E00..U+9FA5 (6763 commonly-used
+// + most extended-use chars). Characters outside that range pass
+// through unchanged (so punctuation / Latin / digits participate via
+// ASCII order).
+// We deliberately do NOT load the polyphone table — empirically the
+// main table dict.all already encodes "the most common everyday
+// reading" (e.g. 乐→L for "乐观", 行→H for "银行", 长→Z for "长大"),
+// while polyphone tends to put a secondary reading first
+// (乐.polyphone='YL', primary yuè), so overriding would push entries
+// like "乐观大胆派" into the `y` bucket instead of `l`. For sorting
+// purposes the high-frequency main reading is what users expect.
const _BASE = 0x4E00;
function pinyinFirstLetter(ch) {
if (!ch) return '';
- // 走得到 vendor 数据则用,加载失败时退回原字符(让 sort 至少不崩)
+ // Use the vendor table when available; if loading failed, return the
+ // original character (so sort at least does not crash).
const dict = (typeof pinyin_dict_firstletter !== 'undefined') ? pinyin_dict_firstletter : null;
if (!dict || !dict.all) return ch;
const idx = ch.charCodeAt(0) - _BASE;
@@ -26,9 +37,13 @@ function pinyinFirstLetter(ch) {
return letter ? letter.toLowerCase() : ch;
}
-// 把整串展开成"按首字母拼起来"的 sort key。
-// 例:'悲观谨慎派' → 'bgjsp';'Agent Skill 评估官' → 'agent skill psg';
-// 'Claude Code' → 'claude code'。然后两个 key 用 < 直接比就是用户预期的字典序。
+// Flatten the whole string into a "concatenated first-letters" sort
+// key. Examples:
+// '悲观谨慎派' → 'bgjsp'
+// 'Agent Skill 评估官' → 'agent skill psg'
+// 'Claude Code' → 'claude code'
+// Comparing two keys with `<` then yields the dictionary order users
+// expect.
function pinyinSortKey(str) {
if (!str) return '';
let out = '';
diff --git a/src/renderer/modules/plan-rail.js b/src/renderer/modules/plan-rail.js
index b2a243cd..c9955369 100644
--- a/src/renderer/modules/plan-rail.js
+++ b/src/renderer/modules/plan-rail.js
@@ -7,7 +7,7 @@
* - Render every step with status icon + index + title + assignee
* - Show progress count `done/total` in the header
* - On `failed` steps (and only when state.in_flight is empty),
- * surface 重试 / 跳过 / 放弃 actions wired to IPC
+ * surface retry / skip / abort actions wired to IPC
* - On `pending` steps with `transient_attempts > 0`, render a small
* `🔁 N/2` badge so users see the auto-retry in flight (otherwise the
* transient retry would silently look like the step is just stuck)
@@ -57,9 +57,9 @@ function _buildStepHtml(step) {
: '';
const actions = _isStepActionable(step, _currentInFlight)
? `<div class="plan-rail-step-actions">
- <button type="button" class="btn btn-sm" data-action="retry" data-i18n="plan.action.retry">${escapeHtml(t('plan.action.retry') || '重试')}</button>
- <button type="button" class="btn btn-sm" data-action="skip" data-i18n="plan.action.skip">${escapeHtml(t('plan.action.skip') || '跳过')}</button>
- <button type="button" class="btn btn-sm btn-danger" data-action="abort" data-i18n="plan.action.abort">${escapeHtml(t('plan.action.abort') || '放弃整个计划')}</button>
+ <button type="button" class="btn btn-sm" data-action="retry" data-i18n="plan.action.retry">${escapeHtml(t('plan.action.retry') || 'Retry')}</button>
+ <button type="button" class="btn btn-sm" data-action="skip" data-i18n="plan.action.skip">${escapeHtml(t('plan.action.skip') || 'Skip')}</button>
+ <button type="button" class="btn btn-sm btn-danger" data-action="abort" data-i18n="plan.action.abort">${escapeHtml(t('plan.action.abort') || 'Abandon plan')}</button>
</div>`
: '';
return `<div class="plan-rail-step is-${step.status}" data-step-index="${step.index}" ${step.output_msg_id ? `data-msg-id="${escapeHtml(step.output_msg_id)}"` : ''}>
@@ -213,15 +213,15 @@ document.addEventListener('click', async (ev) => {
);
const data = await res.json().catch(() => ({}));
if (!data?.ok) {
- uiAlert(t('plan.error.retry_failed', { reason: data?.error || 'unknown' }) || `重试失败: ${data?.error || 'unknown'}`);
+ uiAlert(t('plan.error.retry_failed', { reason: data?.error || 'unknown' }) || `Retry failed: ${data?.error || 'unknown'}`);
}
} catch (err) {
- uiAlert(t('plan.error.retry_failed', { reason: err && err.message }) || `重试失败: ${err && err.message}`);
+ uiAlert(t('plan.error.retry_failed', { reason: err && err.message }) || `Retry failed: ${err && err.message}`);
}
return;
}
if (action === 'skip') {
- const ok = await uiConfirm(t('plan.confirm.skip') || '确认跳过此步骤?');
+ const ok = await uiConfirm(t('plan.confirm.skip') || 'Skip this step?');
if (!ok) return;
try {
const res = await apiFetch(
@@ -230,15 +230,15 @@ document.addEventListener('click', async (ev) => {
);
const data = await res.json().catch(() => ({}));
if (!data?.ok) {
- uiAlert(t('plan.error.skip_failed', { reason: data?.error || 'unknown' }) || `跳过失败: ${data?.error || 'unknown'}`);
+ uiAlert(t('plan.error.skip_failed', { reason: data?.error || 'unknown' }) || `Skip failed: ${data?.error || 'unknown'}`);
}
} catch (err) {
- uiAlert(t('plan.error.skip_failed', { reason: err && err.message }) || `跳过失败: ${err && err.message}`);
+ uiAlert(t('plan.error.skip_failed', { reason: err && err.message }) || `Skip failed: ${err && err.message}`);
}
return;
}
if (action === 'abort') {
- const ok = await uiConfirm(t('plan.confirm.abort') || '确认放弃整个执行计划?');
+ const ok = await uiConfirm(t('plan.confirm.abort') || 'Abandon the entire plan?');
if (!ok) return;
try {
await apiFetch(
@@ -246,7 +246,7 @@ document.addEventListener('click', async (ev) => {
{ method: 'POST' },
);
} catch (err) {
- uiAlert(t('plan.error.abort_failed', { reason: err && err.message }) || `放弃失败: ${err && err.message}`);
+ uiAlert(t('plan.error.abort_failed', { reason: err && err.message }) || `Abort failed: ${err && err.message}`);
}
return;
}
diff --git a/src/renderer/modules/queue-draft.js b/src/renderer/modules/queue-draft.js
index 56e2e9d3..863600c0 100644
--- a/src/renderer/modules/queue-draft.js
+++ b/src/renderer/modules/queue-draft.js
@@ -4,7 +4,7 @@
// sent immediately. Queue is per-cid, persisted in localStorage so a refresh
// mid-stream doesn't drop pending messages. Drained one-by-one when the
// current reply finishes (or is aborted). Each entry records the raw user
-// text plus the selected skill — the `使用 X skill:` prefix is applied at
+// text plus the selected skill — the "use skill X" prefix is applied at
// dispatch time so a later skill change is reflected correctly.
function _loadQueueFromStorage(cid) {
@@ -104,7 +104,7 @@ function _dispatchNextQueued(cid) {
_updateConvSidebarBadge(cid);
renderMessageQueue(cid);
// Skill is an inline text prefix (applied at dispatch time so later skill
- // changes take effect). Agent runs are just "运行 <name>" text — no flag.
+ // changes take effect). Agent runs are just "run <name>" text — no flag.
// Recipient prefix (`@<agent>`) is also applied at dispatch time so the
// message routes to whoever is currently selected in the chip.
const withSkill = next.skill ? transformWithSkill(next.content, next.skill) : next.content;
diff --git a/src/renderer/modules/search.js b/src/renderer/modules/search.js
index 5eb70062..20b9cede 100644
--- a/src/renderer/modules/search.js
+++ b/src/renderer/modules/search.js
@@ -6,7 +6,7 @@
const _SEARCH_HISTORY_KEY = 'search_history';
const _SEARCH_HISTORY_MAX = 12;
const _SEARCH_FETCH_LIMIT = 200; // backend cap; we filter/slice locally per tab
-const _SEARCH_ALL_PER_SECTION = 10; // "all" tab shows up to N per section, overflow → 查看更多
+const _SEARCH_ALL_PER_SECTION = 10; // "all" tab shows up to N per section, overflow → "view more"
let _searchTimer = null;
let _searchSeq = 0;
let _searchTab = 'all'; // 'all' | 'chat' | 'agent' | 'skill' | 'context'
@@ -264,8 +264,11 @@ function _renderSearchResults(query) {
const parts = [];
const visible = [];
- // "全部" tab 顺序:对话 → 智能体 → 技能 → 知识库;每段最多 _SEARCH_ALL_PER_SECTION 条,
- // 超出给"查看更多"按钮跳到对应 tab。其它 tab 只显示自己那段(不截顶,让用户能滚完)。
+ // "All" tab order: chats → agents → skills → knowledge base; each
+ // section caps at _SEARCH_ALL_PER_SECTION rows, with overflow
+ // surfacing a "view more" button that jumps to the matching tab.
+ // Other tabs render their own section only (no cap, so the user can
+ // scroll through everything).
const sections = [
{ tab: 'chat', bucket: chats, labelKey: 'search.section.chat' },
{ tab: 'agent', bucket: agents, labelKey: 'search.section.agent' },
diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.js
index 292397a4..4b477272 100644
--- a/src/renderer/modules/settings.js
+++ b/src/renderer/modules/settings.js
@@ -1,10 +1,11 @@
// ─── Settings (entries-based: picker + priority list) ────────────────────
// The page is split in two:
-// 1. "添加模型授权": pick provider + model, then "+ 添加账号" → either an
-// API Key form or the OAuth flow, depending on what the provider
-// supports. On success we auto-create a priority-list entry pointing
-// at the new credential.
-// 2. "已配置(按优先级)": ordered list of (provider, model, profile)
+// 1. "Add model auth": pick provider + model, then "+ Add account" →
+// either an API Key form or the OAuth flow, depending on what the
+// provider supports. On success we auto-create a priority-list
+// entry pointing at the new credential.
+// 2. "Configured (by priority)": ordered list of
+// (provider, model, profile)
// entries. First = default model; later items are the fallback chain.
// Rows are drag-reorderable.
@@ -42,9 +43,10 @@ async function loadSettings() {
}
// ── Commander avatar ──
-// 指挥官头像走 prefs IPC,存到 preferences.json。修改后立即推回缓存
-// (conversation.js 的 _commanderAvatarCache)以便聊天行立即用上新头像,
-// 不用等下次 view 切换。
+// Commander avatar goes through the prefs IPC and lands in
+// preferences.json. After a change we immediately push it back to the
+// cache (conversation.js's _commanderAvatarCache) so chat rows pick up
+// the new avatar without waiting for the next view switch.
async function _settingsRefreshCommanderAvatar() {
try {
@@ -70,13 +72,15 @@ function _settingsRenderCommanderAvatar() {
trigger.addEventListener('click', (e) => {
e.stopPropagation();
if (isAvatarPickerOpenFor(trigger)) { closeAvatarPicker(); return; }
- // 指挥官头像图标固定 crown,picker 只显示颜色行。后端校验依然两个 token
- // 都要带,所以保存时强制写 crown。
+ // The commander avatar's icon is fixed at crown, so the picker
+ // only shows the color row. Backend validation still requires both
+ // tokens, so we force-write crown on save.
openAvatarPicker(trigger, cur, { allowCommanderCombo: true, hideIcons: true }, async (next) => {
const icon = COMMANDER_DEFAULT.icon;
_settingsState.commanderAvatar = { icon, color: next.color };
cur.icon = icon; cur.color = next.color;
- // 就地更新,保留 trigger 上的 click 监听 —— 用户可以连点几次直到满意。
+ // Update in place — the trigger's click listener is preserved so
+ // the user can click a few times in a row until satisfied.
applyAvatarToElement(trigger, icon, next.color, 'commander');
try {
const res = await window.orkas.invoke('prefs.setCommanderAvatar', { icon, color: next.color });
@@ -143,9 +147,11 @@ function _settingsRenderLocalExec() {
}
}
-// ── Metacognition (Agent 元认知自演进) ──
-// 落到 preferences.json::metacognition_enabled,env `ORKAS_METACOGNITION='0'` 仍是
-// 更高优先级的 kill switch(`envForcedOff`),命中时 UI 把开关锁灰并提示。
+// ── Metacognition (agent self-evolution) ──
+// Stored at preferences.json::metacognition_enabled. The env var
+// `ORKAS_METACOGNITION='0'` is still a higher-priority kill switch
+// (surfaced as `envForcedOff`); when active, the UI greys out the
+// toggle and shows an explanatory hint.
async function _settingsRefreshMetacognition() {
try {
@@ -177,7 +183,7 @@ function _settingsRenderMetacognition() {
if (res && res.ok) {
_settingsState.metacognition = { ..._settingsState.metacognition, enabled: !!res.enabled };
} else {
- // 写失败时回滚 UI
+ // Roll back the UI on write failure.
cb.checked = !next;
_settingsLog.warn('setMetacognition rejected', res);
}
@@ -268,9 +274,11 @@ async function _settingsRenderPicker() {
if (p.supportsOAuth && p.supportsApiKey) authHint = t('settings.oauth.support_api_and_oauth');
else if (p.supportsOAuth && !p.supportsApiKey) authHint = t('settings.oauth.support_oauth_only');
else if (p.supportsApiKey) authHint = t('settings.oauth.support_api_only');
- // subscriptionNote 是"用错了会 401 白白浪费 key"级别的关键前提,
- // 优先展示;授权方式能力次之。两条都有就用 ' · ' 串起来。
- // subscriptionNote 是 i18n key(见 provider_catalog.ts 字段注释),渲染时翻译。
+ // subscriptionNote is the "wrong-account → 401 wastes the key"
+ // class of critical prerequisite, so it goes first; the auth
+ // capability hint comes second. Join with ' · ' when both exist.
+ // subscriptionNote is an i18n key (see the field comment in
+ // provider_catalog.ts) — translated on render.
const subNote = p.subscriptionNote ? t(p.subscriptionNote) : '';
const hint = [subNote, authHint].filter(Boolean).join(' · ');
return { value: p.id, label, hint };
@@ -943,15 +951,15 @@ function _settingsSetRowStatus(el, kind, text, baseCls = 'account-row-status') {
//
// Shape mirrors the chat-entries list visually but uses simpler rows
// (provider + label + delete). Provider list is fixed (Tavily / Serper /
-// Brave Search API / 百度 AI 搜索); see search-adapters.ts for the
+// Brave Search API / Baidu AI Search); see search-adapters.ts for the
// canonical registry.
const _SEARCH_PROVIDER_OPTIONS = [
{ id: 'tavily', label: 'Tavily', docs: 'https://tavily.com/' },
{ id: 'serper', label: 'Serper', docs: 'https://serper.dev/' },
{ id: 'brave-search', label: 'Brave', docs: 'https://brave.com/search/api/' },
- { id: 'baidu-ai-search', label: '百度', docs: 'https://cloud.baidu.com/doc/qianfan-api/s/em82g4tlk' },
- { id: 'metaso', label: '秘塔', docs: 'https://metaso.cn/' },
+ { id: 'baidu-ai-search', label: 'Baidu', docs: 'https://cloud.baidu.com/doc/qianfan-api/s/em82g4tlk' },
+ { id: 'metaso', label: 'Metaso', docs: 'https://metaso.cn/' },
];
function _searchProviderLabel(id) {
diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.js
index 15c32e9d..62fe0a16 100644
--- a/src/renderer/modules/skills.js
+++ b/src/renderer/modules/skills.js
@@ -7,7 +7,7 @@ let _selectedSkill = null; // { source, id }
// Re-render the skill grid + currently selected detail page when the UI
// language changes — descriptions are bilingual now and `pickDesc` returns
// a different string after the locale flip. Detail re-render goes through
-// `selectSkillFile` so the SKILL.md frontmatter re-parses and 简介 picks the
+// `selectSkillFile` so the SKILL.md frontmatter re-parses and the description picks the
// right locale via `_renderSkillSections`.
window.addEventListener('i18n-change', () => {
if (_skillsCache) renderSkillsGrid(_skillsCache);
@@ -41,7 +41,7 @@ async function loadSkills() {
// The chip pill is still used to display a skill that was attached
// programmatically by the "use skill" flow (▶ on a skill card → useSkill →
// setChatSkill). Clicking × removes the chip. On send, the chip's name is
-// prepended to the message as `使用 <name> skill:<content>`.
+// prepended to the message as `use skill <name>: <content>`.
const _chatSkill = { 'new-chat': '', 'conversation': '' };
@@ -543,15 +543,18 @@ async function selectSkillFile(source, id, filepath, nodeEl) {
const sourceLabel = source === 'custom' ? t('skills.source_custom') : t('skills.source_builtin');
document.getElementById('skills-detail-source').textContent = sourceLabel;
- // Doc sections (简介 / 外部依赖 / 依赖技能 / 其他属性) — seed with the
- // cached description so the page isn't blank on first paint; refined
- // once SKILL.md frontmatter parses.
+ // Doc sections (description / external dependencies / dependent
+ // skills / other attributes) — seed with the cached description so
+ // the page isn't blank on first paint; refined once SKILL.md
+ // frontmatter parses.
const seedDesc = pickDesc(skill, getLang()).trim();
_renderSkillSections(seedDesc ? [['description', seedDesc]] : []);
// Actions bar: visible when a skill is selected.
- // Order: 使用 (icon) / 编辑 / 启用-禁用 / 内置(custom+dev) / 删除.
- // In edit mode only 完成 (relabeled 编辑) is shown; everything else hides.
+ // Order: use (icon) / edit / enable-disable / promote-to-builtin
+ // (custom + dev) / delete.
+ // In edit mode only the "done" button (the relabeled "edit") is
+ // shown; everything else hides.
const actions = document.getElementById('skills-detail-actions');
const canEditThisSkill = source === 'custom' || (source === 'builtin' && isDevMode());
if (actions) {
@@ -700,9 +703,10 @@ function _parseSkillFrontmatterPairs(content) {
// Single source of truth for rendering frontmatter fields into the
// document. Splits known fields into their own dedicated sections (with
-// labels) and tucks any unknown leftover keys under "其他属性". Hides any
-// section whose content is empty (except 简介 which always renders so the
-// reader sees a placeholder when missing).
+// labels) and tucks any unknown leftover keys under "other
+// attributes". Hides any section whose content is empty (except the
+// description, which always renders so the reader sees a placeholder
+// when missing).
function _renderSkillSections(pairs) {
const map = new Map();
for (const [k, v] of (pairs || [])) {
@@ -710,10 +714,10 @@ function _renderSkillSections(pairs) {
}
// `description_zh` / `description_en` are the canonical bilingual fields;
// legacy single `description` is kept in `known` so it doesn't bleed into
- // "其他属性" when reading older SKILL.md files.
+ // the "other attributes" bucket when reading older SKILL.md files.
const known = new Set(['description', 'description_zh', 'description_en']);
- // — 简介 — pick by current UI language with cross-language fallback (so a
+ // — Description — pick by current UI language with cross-language fallback (so a
// single-language skill still shows something instead of going blank).
const summaryEl = document.getElementById('skills-detail-summary');
if (summaryEl) {
@@ -731,7 +735,7 @@ function _renderSkillSections(pairs) {
}
}
- // — 其他属性 (catch-all for anything we don't render explicitly) —
+ // — Other attributes (catch-all for anything we don't render explicitly) —
const extraSection = document.getElementById('skills-section-extra');
const extraBody = document.getElementById('skills-detail-extra');
if (extraSection && extraBody) {
@@ -753,7 +757,7 @@ function _renderSkillSections(pairs) {
// Read-only view of a skill file. Markdown renders, other formats get a
// code block. Stores the raw content on the element so the editor variant
-// can reset on "放弃修改" without re-fetching.
+// can reset on "discard changes" without re-fetching.
function _renderSkillFileView(body, content, ext) {
body.className = 'skills-detail-body';
body.dataset.rawContent = content;
@@ -886,11 +890,12 @@ function _updateEditButtonLabel() {
btn.textContent = _skillEditMode ? t('skills.edit_btn_done') : t('skills.edit_btn_edit');
}
-// When called with {autoSeed: true} (e.g. right after skill creation), sends
-// a short "帮我完善这个技能" message to kick off the LLM. When autoSeed is a
-// non-empty string, sends that exact string instead — used by URL / Dir
-// import flows to inject their own "帮我安装技能:<...>" seed. In plain edit
-// mode (user clicks "编辑" on an existing skill) no message is sent
+// When called with {autoSeed: true} (e.g. right after skill creation),
+// sends a short "help me refine this skill" message to kick off the
+// LLM. When autoSeed is a non-empty string, sends that exact string
+// instead — used by URL / Dir import flows to inject their own
+// "help me install this skill: <...>" seed. In plain edit mode (user
+// clicks "edit" on an existing skill) no message is sent
// automatically — the user drives the conversation from a blank input.
async function toggleSkillEditMode(opts = {}) {
if (!_selectedSkill) return;
@@ -898,10 +903,11 @@ async function toggleSkillEditMode(opts = {}) {
if (_selectedSkill.source !== 'custom'
&& !(_selectedSkill.source === 'builtin' && isDevMode())) return;
if (_skillEditMode && _skillEditSkillId === _selectedSkill.id) {
- // Abort any in-flight reply so 完成 is "stop + exit", not "exit but
- // keep streaming". The chat controller is a singleton; leaving it
- // pending also leaks the streaming-button state into the next skill's
- // edit panel when the user clicks 编辑 elsewhere.
+ // Abort any in-flight reply so "done" means "stop + exit", not
+ // "exit but keep streaming". The chat controller is a singleton;
+ // leaving it pending also leaks the streaming-button state into
+ // the next skill's edit panel when the user clicks "edit"
+ // elsewhere.
try { _skillChatCtrl?.abort(); } catch (_) { /* ignore */ }
_skillEditMode = false;
_skillEditSkillId = null;
@@ -1012,10 +1018,11 @@ async function _refreshSkillView() {
if (!_selectedSkill || _selectedSkill.id !== sid || _selectedSkill.source !== source) return;
// Re-render the whole detail page via selectSkillFile so the header
- // (name) and the doc sections (description / 外部依赖 / 依赖技能 / ...)
- // pick up SKILL.md frontmatter changes the LLM just made — without
- // this, the description chip stayed on the pre-edit value until the
- // user clicked 完成. selectSkillFile also re-reads the body, so we
+ // (name) and the doc sections (description / external deps /
+ // dependent skills / ...) pick up SKILL.md frontmatter changes the
+ // LLM just made — without this, the description chip stayed on the
+ // pre-edit value until the user clicked "done". selectSkillFile
+ // also re-reads the body, so we
// don't need a separate body refetch here.
const filepath = _selectedSkill.filepath || 'SKILL.md';
await selectSkillFile(source, sid, filepath, null);
@@ -1074,7 +1081,7 @@ async function openSkillModal(editId) {
if (el) el.value = '';
}
const sel = document.getElementById('skill-dir-selected');
- if (sel) sel.textContent = t('skill_modal.dir_none') || '(未选择)';
+ if (sel) sel.textContent = t('skill_modal.dir_none') || '(none selected)';
if (editId) {
title.textContent = t('skills.modal_edit_title');
@@ -1250,7 +1257,7 @@ async function _saveSkillFromDir({ msgEl }) {
// Shared "after create" tail: close modal, refresh list, jump to edit view.
// `seedMessage` — custom first message to seed the skill edit chat with.
// Pass null to let toggleSkillEditMode use its default seed
-// ("帮我完善这个技能"). Ignored in edit mode (isNew=false).
+// ("help me refine this skill"). Ignored in edit mode (isNew=false).
async function _afterSkillCreated(sid, isNew, seedMessage) {
closeSkillModal();
_skillsCache = null;
@@ -1325,9 +1332,10 @@ async function promoteCustomSkill(id) {
}
/**
- * Per-skill 启用 / 禁用 button in the detail header. Clone-replace the node
- * each render to drop any prior click handler bound to a stale skill id.
- * The button label flips between 启用 / 禁用 (whichever the click would do).
+ * Per-skill enable / disable button in the detail header.
+ * Clone-replace the node each render to drop any prior click handler
+ * bound to a stale skill id. The button label flips between "enable"
+ * and "disable" (whichever the click would do).
*/
function _renderSkillEnabledButton(skill) {
const oldBtn = document.getElementById('skill-enabled-btn');
diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.js
index 146263f0..277aa5d9 100644
--- a/src/renderer/modules/state.js
+++ b/src/renderer/modules/state.js
@@ -92,7 +92,7 @@ function _onPolledResponse(cid, content, isError = false) {
// created-agent chip. The historical "patch the bubble's content
// directly" path lost all of those because polling only had access to
// `last.content` (a string), so an aborted commander turn that was
- // recovered by polling rendered as bare "(已中断)" without the process
+ // recovered by polling rendered as bare "(stopped)" without the process
// info that the user already watched stream in.
if (el && el.isConnected) {
const finalEl = el.querySelector('[data-role="final"]');
@@ -194,10 +194,11 @@ function bindStaticHandlers() {
// Quick-create-agent button (conversation toolbar). Pushes a canned
// request through handleChatSubmit so it honors queue / pending /
// attachments state — we don't bypass the send pipeline.
- // 创建智能体 inline 入口在 conversation.js 内动态创建并自带 click 绑定。
+ // The "Create agent" inline entry is dynamically created inside
+ // conversation.js and binds its own click handler.
// Agents (grid + detail)
- // 完成 button (only visible while editing) — exits edit mode.
+ // "Done" button (only visible while editing) — exits edit mode.
document.getElementById('create-agent-btn')?.addEventListener('click', () => openAgentModal());
document.getElementById('agents-back-btn')?.addEventListener('click', () => _showAgentsGridView());
document.getElementById('agent-use-btn')?.addEventListener('click', () => {
@@ -242,7 +243,8 @@ function bindStaticHandlers() {
document.getElementById('skills-detail-name')?.addEventListener('click', _handleSkillNameClick);
document.getElementById('skill-chat-clear-btn')?.addEventListener('click', clearSkillChat);
- // Detail-view chrome: 「← 返回技能库」 + 折叠区开关 + Esc 返回 + 外点关 ⋯ 菜单
+ // Detail-view chrome: "← Back to skill library" + collapsible-section
+ // toggle + Esc to return + outside-click to close the ⋯ menu.
document.getElementById('skills-back-btn')?.addEventListener('click', () => _showSkillsGridView());
document.getElementById('skills-source-toggle')?.addEventListener('click', () => _toggleSkillsSource());
document.addEventListener('keydown', (e) => {
diff --git a/src/renderer/modules/user-workspace.js b/src/renderer/modules/user-workspace.js
index 45e7dd85..d2aa7a9d 100644
--- a/src/renderer/modules/user-workspace.js
+++ b/src/renderer/modules/user-workspace.js
@@ -97,7 +97,8 @@ function _createWorkspaceChip() {
const chip = document.createElement('button');
chip.type = 'button';
chip.className = 'workspace-chip';
- chip.title = _wsInfo.currentPath || '点击选择工作区';
+ chip.title = _wsInfo.currentPath
+ || (typeof t === 'function' ? t('workspace.chip_title') : 'Click to pick a workspace');
chip.innerHTML =
'<svg class="workspace-chip-icon" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">' +
'<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>' +
diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.js
index f8c14cf8..6df98dc5 100644
--- a/src/renderer/modules/utils.js
+++ b/src/renderer/modules/utils.js
@@ -476,7 +476,7 @@ function _aiSelectMount(el, config) {
const state = {
options: [], // [{value, label, hint?}]
value: '',
- placeholder: (typeof t === 'function' ? t('ai_select.placeholder') : '— 请选择 —'),
+ placeholder: (typeof t === 'function' ? t('ai_select.placeholder') : '— Select —'),
onChange: () => {},
open: false,
activeIdx: -1,