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.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Keep Agent and Skill authoring language rules in their owners
wytd34ced73afe8
diff --git a/resources/builtin/system/skills/agent-creator/SKILL.md b/resources/builtin/system/skills/agent-creator/SKILL.mdindex 4e30fc5b..9c5b94d7 100644--- a/resources/builtin/system/skills/agent-creator/SKILL.md+++ b/resources/builtin/system/skills/agent-creator/SKILL.md@@ -25,7 +25,7 @@ Do not read unrelated references. A simple bound edit normally needs only `llm-a- **One container per Agent.** Multiple containers are legal only when the user asked to create or edit multiple distinct Agents, and the number of valid containers must equal the number of Agents you claim to have created. End the turn after emitting them; do not dispatch the Agent.- **Validate every container independently before sending.** Read its tags in order: every opening tag must have the exact matching closing tag, with no crossed, missing, or reused closer. For a multi-Agent reply, repeat this structural check for each container rather than copying an unchecked suffix.- **Read attachment sources.** For an injected attachment, missing inline body text is not a missing source; call `read_files` with the exact supplied path in `paths` and ask for another upload only if that read fails.-- **Use the user's current UI language** for display copy and user-visible prose. Keep XML tags, tool/Skill names, paths, JSON keys, and closed-set values unchanged. Use localized description tags only when the user explicitly requests multilingual descriptions.+- **Use the user's current UI language** for authored display copy other than descriptions. Keep XML tags, tool/Skill names, paths, JSON keys, and closed-set values unchanged.- **Keep user-visible prose outcome-based.** State what the Agent does, when to use it, and the substantive change; do not expose XML/field/schema/id mechanics or source provenance by default.- **Agent roles are not model runtimes.** Do not imitate or claim an unavailable provider by naming an ordinary role Agent after a model. Real external CLI runtimes are handled by their smaller editable contract.- **Do not hard-code other Agent display names** in authored content; describe downstream roles by capability.@@ -46,6 +46,8 @@ For a new Agent, first compare its name and its typical objects/actions with the## Routing descriptions+Description language: explicit description-language request, otherwise the current UI language; the chat's response language does not select it. Use `<description>` by default and `<description_zh>` / `<description_en>` for explicitly requested Chinese/English variants.+New or rewritten descriptions usually need one or two concise sentences: action, work object, deliverable, and any boundary needed to distinguish adjacent roles. Use natural routing terms; add an example only to resolve ambiguity, not a repeated keyword list. Keep execution steps out of the description. Do not shorten supplied or existing descriptions during unrelated edits or source-preserving imports.## Execution sequencediff --git a/resources/builtin/system/skills/agent-creator/references/llm-agent-fields.md b/resources/builtin/system/skills/agent-creator/references/llm-agent-fields.mdindex 21109701..ea1dbe9d 100644--- a/resources/builtin/system/skills/agent-creator/references/llm-agent-fields.md+++ b/resources/builtin/system/skills/agent-creator/references/llm-agent-fields.md@@ -59,8 +59,7 @@ On create or when the current icon is missing, choose the closest candidate. OthThis is the Commander's dispatch signal; workflow, inputs, and Skills are not visible at dispatch time.-- Default: one current-language description only. Use `<description_zh>` / `<description_en>` only when the user explicitly asks for multilingual/bilingual descriptions.-- Follow the root Skill's routing-description contract; this field is a selection aid, not an execution manual.+Follow the root Skill's description-language and routing-description contracts; this field is a selection aid, not an execution manual.## `<workflow>`diff --git a/resources/builtin/system/skills/skill-creator/SKILL.md b/resources/builtin/system/skills/skill-creator/SKILL.mdindex 05b8c8af..70b10811 100644--- a/resources/builtin/system/skills/skill-creator/SKILL.md+++ b/resources/builtin/system/skills/skill-creator/SKILL.md@@ -31,7 +31,7 @@ Do not read unrelated references. A category-only edit needs only `metadata.md`;- **No protocol files.** Do not dump `<skill>`, `<skill-meta>`, or file blocks into the workspace. The host parses them inline.- **One container per Skill.** Multiple containers are legal only when the request or source contains multiple distinct Skills. Never merge multiple source `SKILL.md` files into one Skill.- **Skills are independent.** Do not name, invoke, or read another Skill from this Skill's body, references, scripts, or examples. Orchestration belongs to the caller.-- **Use the user's UI language** for newly authored human-readable instructions and user-visible prose. Keep frontmatter keys, identifiers, paths, commands, and code unchanged. Imported prose remains faithful by default.+- **Use the user's UI language** for newly authored Skill body instructions. Keep frontmatter keys, identifiers, paths, commands, and code unchanged. Imported prose remains faithful by default.- **The host owns completion.** A valid `<skill>` container or file block only requests a mutation. Only a successful host result proves it was applied; before that, or after a failed or omitted mutation, never say the Skill is created, updated, saved, ready, or available. Describe pending mutations as “将创建” or “已提交,等待应用”.## Decide create versus editdiff --git a/resources/builtin/system/skills/skill-creator/references/metadata.md b/resources/builtin/system/skills/skill-creator/references/metadata.mdindex e43d7a48..e4370621 100644--- a/resources/builtin/system/skills/skill-creator/references/metadata.md+++ b/resources/builtin/system/skills/skill-creator/references/metadata.md@@ -24,7 +24,7 @@ Do not include execution steps, tool names, implementation details, marketing clWhen authoring or repairing a description, use the same compact routing index as SKILL.md frontmatter; aim for no more than 200 characters; exceed this target only when needed to preserve routing information, and keep it at or below 200 estimated tokens (the runtime’s local estimate). Use only the detail needed for complete routing; there is no minimum length and no need to pad. Runtime will preserve the complete description up to that token boundary and mark an omitted tail with `…`; when the roster exceeds its budget, lower-priority non-builtin entries are listed by name only and stay discoverable through `skill_search`. Do not depend on truncation. Preserve faithful imported descriptions unless the user asks for a rewrite.-Use `<description>` for the current UI language. Emit `<description_zh>` and `<description_en>` only when the user explicitly asks for multilingual/bilingual descriptions; write each independently with equivalent routing signal.+Description language: explicit description-language request, otherwise the current UI language; the chat's response language does not select it. Use `<description>` by default and `<description_zh>` / `<description_en>` for explicitly requested Chinese/English variants. When both are requested, keep their routing signal equivalent.## Routing metadata tagsdiff --git a/src/main/features/agents.ts b/src/main/features/agents.tsindex becc6d64..a060b775 100644--- a/src/main/features/agents.ts+++ b/src/main/features/agents.ts@@ -279,14 +279,13 @@ export interface Agent {/** Marketplace category code. Empty string only for legacy/manual specs.* Maintained by hidden create defaults and by the agent-edit LLM's `<category>` sub-tag. */category: string;- /** Output rendering preference — agent-level hint injected into the worker- * system prompt at dispatch time. Four user-facing values, progressive- * capability disclosure:+ /** Output rendering preference — agent-level hint injected into the named Agent+ * system prompt at dispatch time. Four user-facing values:* - `'auto'`: default. The model chooses the lightest useful* presentation: plain text/Markdown, inline dashboard, or interactive app.* - `'text'`: blocks `:::dashboard` + `create_artifact`. The plain-reply* hard constraint.- * - `'dashboard'`: allows `:::dashboard` blocks; still blocks `create_artifact`.+ * - `'dashboard'`: prefers `:::dashboard` for structured data.* - `'artifact'`: allows both `:::dashboard` and `create_artifact`.* Legacy aliases kept for back-compat: `'markdown_only'` (old name for* `'text'`) and `'allow_artifacts'` (old name for `'artifact'`).@@ -1387,9 +1386,9 @@ export async function setAgentCliProjectDir(return getCliProjectDirInfoForAgent(userId, agent);}-// Bump when normalizeAgent's materialized schema changes so persisted rows are-// rebuilt instead of bypassing read-time compatibility reconciliation.-const AGENT_CATALOG_CACHE_VERSION = 3;+// Bump when normalized rows or scan completeness changes. Version 4 rebuilds+// snapshots that older tolerant reads could persist after a source failure.+const AGENT_CATALOG_CACHE_VERSION = 4;const AGENT_ENRICHED_CACHE_TTL_MS = 2_000;interface AgentListCache { stamp: string; data: Agent[] }@@ -1472,7 +1471,10 @@ function _agentDirStamp(): string {let stamp = '';for (const d of [CUSTOM_AGENTS_DIR(), userMarketplaceAgentsDir(getActiveUserId())]) {try { stamp += `${d}:${fs.statSync(d).mtimeMs};`; }- catch { stamp += `${d}:0;`; }+ catch (error) {+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw new Error('Agent catalog unavailable');+ stamp += `${d}:0;`;+ }}return stamp;}@@ -1539,15 +1541,22 @@ async function _listAgentSpecs(): Promise<Agent[]> {const seen = new Set<string>();const sources: Array<[AgentSource, string]> = [['marketplace', userMarketplaceAgentsDir(getActiveUserId())], ['custom', CUSTOM_AGENTS_DIR()]];for (const [source, dir] of sources) {- if (!fs.existsSync(dir)) continue;- const entries = (await fsp.readdir(dir, { withFileTypes: true }))+ const entries = (await fsp.readdir(dir, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => {+ if (error?.code === 'ENOENT') return [];+ throw new Error('Agent catalog unavailable');+ })).filter((e) => e.isDirectory() && !e.name.startsWith('.')).sort((a, b) => a.name.localeCompare(b.name));for (const e of entries) {const full = path.join(dir, e.name, 'agent.json');- if (!fs.existsSync(full)) continue;let data: AgentRaw;- try { data = await readJson<AgentRaw>(full); } catch { continue; }+ try { data = await readJson<AgentRaw>(full, { strict: true }); }+ catch (error) {+ // A staging directory may not contain a definition yet. Existing+ // but unreadable/malformed definitions make the scan incomplete.+ if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') continue;+ throw new Error('Agent catalog unavailable');+ }const norm = normalizeAgent(data, source);if (!norm) continue;if (isMarketplaceSource(source)) {diff --git a/src/main/features/marketplace_reconcile.ts b/src/main/features/marketplace_reconcile.tsindex 56846c94..24a13e57 100644--- a/src/main/features/marketplace_reconcile.ts+++ b/src/main/features/marketplace_reconcile.ts@@ -42,6 +42,7 @@ import { withMarketplaceInstallLock } from './marketplace_locks';import { agentPrivateSkillIdsFromBundle } from './marketplace_private_skills';import { downloadMarketplaceBundle, parseMarketplaceBundle } from './marketplace_bundle';import { createLogger } from '../logger';+import { logErrorSummary, logPathRef } from '../util/log-redact';import { createMarketplaceCatalogReader, type MarketplaceCatalogReader, type MarketplaceCatalogRow } from './marketplace_catalog';import { fetchWithRetry } from '../util/retry';import { replaceDirectoryAtomically, sweepStaleReplacementArtifacts } from '../util/atomic-directory-replace';@@ -466,13 +467,13 @@ export async function reconcileInstalls(try { _assertContinue(opts); } catch {return _emptyReconcileResult();}- // Staging/backup directories of an install that died mid-flight start with- // a dot, so the listings below never saw them and nothing reclaimed them.+ // Reclaim abandoned staging; previous copies need positive commit evidence+ // before they can be discarded, even when a target directory also exists.for (const root of [userMarketplaceAgentsDir(uid), userMarketplaceSkillsDir(uid)]) {const removed = await sweepStaleReplacementArtifacts(root, (err, artifact) => {log.warn('stale install artifact cleanup failed', {- artifact: path.basename(artifact),- error: (err as Error).message,+ artifact: logPathRef(artifact),+ error: logErrorSummary(err),});});if (removed.length) log.info(`swept ${removed.length} stale install artifact(s) under ${path.basename(root)}`);diff --git a/src/main/prompts/chat_agent_setup_cli.md b/src/main/prompts/chat_agent_setup_cli.mdindex 090369ae..4aeb325d 100644--- a/src/main/prompts/chat_agent_setup_cli.md+++ b/src/main/prompts/chat_agent_setup_cli.md@@ -1,7 +1,5 @@## Core task-Refine one **CLI-backed agent** with the user: `name`, bilingual `description`, optional `inputs`, and `interactive`.--It spawns a local coding CLI to execute end-to-end; no workflow / skills / tools are authored here.+Edit the CLI-backed Agent bound to this session.Full authoring rules live in system skill `agent-creator`. **Read it first**using the exact read ref shown in the generated `## System skills` block; its@@ -11,21 +9,10 @@ CLI-backed section is canonical.## What's specific to THIS session-- **Editable here**: `name` / `description_zh` / `description_en` / `inputs` / `interactive`.-- **Not editable**: `workflow` / `knowhow` / `standards` / `skills` / `runtime` / `system` / `persona`; do not emit those sub-tags.-- Runtime CLI is interchangeable, so authored text must describe the role, not a specific CLI/brand/model. Never name CLI/runtime/vendor/model terms listed in `agent-creator`.- Bound to one agent: emit at most one `<agent>` container, with neither `<operation>` nor `<agent_id>`.-- Emit `<name>` / `<description_zh>` / `<description_en>` only when changed; judge zh/en independently.-- Emit `<inputs>` / `<interactive>` only when that field changed. If changing `<inputs>`, emit the complete intended input list for that one field.-- Emit no container for pure discussion or unrelated questions.--## How to work with the user--1. Clarify what coding task it owns and what deliverable it produces.-2. Most CLI agents need zero/few inputs; add only genuinely structured launch choices. If unsure, leave inputs empty, or use one task field plus one optional context field.-3. `interactive` is usually `false`; set `true` only for real multi-turn dependency.-4. Follow `agent-creator`'s routing-description contract; keep requested languages equivalent and CLI-agnostic.-5. Iterate gradually and keep replies concise.+- Emit only changed fields. If changing `<inputs>`, emit the complete intended input list.+- `interactive` is usually `false`; set `true` only for real multi-turn dependency.+- Apply a clear edit request directly. Ask only when necessary information is missing.---diff --git a/src/main/prompts/chat_skill_setup.md b/src/main/prompts/chat_skill_setup.mdindex 57a7512d..190e43d1 100644--- a/src/main/prompts/chat_skill_setup.md+++ b/src/main/prompts/chat_skill_setup.md@@ -9,30 +9,14 @@ Full authoring rules live in system skill `skill-creator`. Read it first throughThis session is bound to the skill in Runtime injection.-- Normal single-skill edits: `<<<skill-file>>>` writes only into this skill directory; emit `<<<skill-file path=...>>>` directly, with no `<skill>` wrapper.-- Import draft only: if the imported source clearly contains multiple existing skills, restore them as multiple skills by emitting one top-level `<skill>...</skill>` container per source skill. Make the first emitted source skill become this current draft skill (the app will apply that container to the current skill and rename it from its SKILL.md frontmatter); emit the remaining source skills as additional containers. Do not merge multiple source skills into one. Do not use `<skill>` wrappers for ordinary edits of this bound skill.-- Metadata-only changes (`name`, descriptions, `category`, `routing.negative_examples`, `routing.applicable_domain`, `routing.prerequisites`) use `<skill-meta>...</skill-meta>` instead of rewriting `SKILL.md`.- If this session starts after a local folder import that already installed existing `SKILL.md` files, do not re-emit those files. Read the installed files and emit only metadata tags. For additional already-installed skills named by the first user message, use metadata-only top-level `<skill>` containers with `<skill_id>...`.- When emitting file/meta/skill protocol, do not write prose around the protocol. If a short user-visible sentence is needed, put it in `<skill-reply>...</skill-reply>`; keep configs, YAML/frontmatter, file blocks, and source material out of that reply. If omitted, the app will show a concise completion status.-- First user message maps to `skill-creator` Mode A/B/C; follow that flow. If the skill directory already contains user-imported files besides `SKILL.md`, treat those files as source material and complete the skill from them directly.-- Emit no file block for pure discussion, no actual change, or unrelated questions.--## How to work with the user--- Mode A only: ask 1-3 key uncertainties up front only when the skill directory has no usable imported source files and the intended capability cannot be inferred. If imported docs, references, scripts, or examples are present, inspect them and write the best skill you can without asking for confirmation; ask only when a safety gate, irreversible external action, missing secret, or genuinely missing source blocks progress. Modes B/C do not proactively clarify; stop/report on fetch/import failure.-- Keep output concise; avoid dumping large code blocks.-- For unrelated questions, answer normally and ask whether to continue refining.-- On failure, state cause + remedy; do not power through.-- Dependency installs: ask before installing; state package, purpose, command. Install only after agreement and record deps in SKILL.md "External dependencies".---## Installing a skill from a URL — use the owning System Skill-When this session's first message asks to install or import a skill from a URL, use the routing gates in the injected System Skills instead of mirroring another actor's prompt:-- Skill content or an explicit portable custom-Skill request → follow `skill-creator`.-- A runnable repository, CLI, or external package → follow `package-installer`.-- If the owning routing gates leave the outcome genuinely ambiguous, state the portability trade-off in one line of plain outcome language and wait for the user's choice.+When this session's first message asks to install or import a skill from a URL, follow the routing gates in `skill-creator` and `package-installer`.The external-package success handoff is specific to this bound editor: only after `package-installer` succeeds, end the reply with `<skill-as-package name="<installed-name>"/>` on its own line so the host removes the placeholder and opens the installed package. Never emit the marker for a custom Skill or a failed/incomplete install, and do not author `SKILL.md` on the external-package route. Tell the user in plain outcome language that the package is installed and where to manage it.diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.jsindex 6f3b663b..6e8403c2 100644--- a/src/renderer/modules/agents.js+++ b/src/renderer/modules/agents.js@@ -1596,7 +1596,7 @@ function _renderAgentDetailMemory(agent, editing = false) {function _agentMemoryFailureText(res, fallback) {const error = String((res && res.error) || '');if (/^memory full/i.test(error)) return t('memory.error_full');- return error || fallback;+ return fallback;}async function _agentMemoryAdd(agent, text) {@@ -1620,6 +1620,27 @@ async function _agentMemoryRemove(agent, text) {return window.orkas.invoke('agents.memory.remove', { agent_id: agent.agent_id, old_text: text });}+async function _applyAgentMemoryChange(agent, write) {+ let res;+ try {+ res = await write();+ } catch (_) {+ uiAlert(t('memory.error_generic'));+ return false;+ }+ if (!res || res.ok === false) {+ uiAlert(_agentMemoryFailureText(res, t('memory.error_generic')));+ return false;+ }+ try {+ await loadAgents(true);+ await _refreshAgentDetail(agent.agent_id);+ } catch (_) {+ _agentsLog.warn('agent memory refresh failed', { error_code: 'refresh_failed' });+ }+ return true;+}+function _wireAgentMemoryControls(host, agent) {host.querySelectorAll('[data-agent-memory-add]').forEach((btn) => {btn.addEventListener('click', async (e) => {@@ -1630,17 +1651,7 @@ function _wireAgentMemoryControls(host, agent) {: window.prompt(label, '');const text = (content || '').trim();if (!text) return;- try {- const res = await _agentMemoryAdd(agent, text);- if (!res || res.ok === false) {- uiAlert(_agentMemoryFailureText(res, _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました')));- return;- }- await loadAgents(true);- await _refreshAgentDetail(agent.agent_id);- } catch (err) {- uiAlert((err && err.message) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));- }+ await _applyAgentMemoryChange(agent, () => _agentMemoryAdd(agent, text));});});host.querySelectorAll('[data-agent-memory-edit]').forEach((btn) => {@@ -1654,17 +1665,7 @@ function _wireAgentMemoryControls(host, agent) {: window.prompt(label, oldText);const text = (content || '').trim();if (!text || text === oldText) return;- try {- const res = await _agentMemoryUpdate(agent, oldText, text);- if (!res || res.ok === false) {- uiAlert(_agentMemoryFailureText(res, _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました')));- return;- }- await loadAgents(true);- await _refreshAgentDetail(agent.agent_id);- } catch (err) {- uiAlert((err && err.message) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));- }+ await _applyAgentMemoryChange(agent, () => _agentMemoryUpdate(agent, oldText, text));});});host.querySelectorAll('[data-agent-memory-remove]').forEach((btn) => {@@ -1681,17 +1682,7 @@ function _wireAgentMemoryControls(host, agent) {}): false;if (!ok) return;- try {- const res = await _agentMemoryRemove(agent, text);- if (!res || res.ok === false) {- uiAlert(_agentMemoryFailureText(res, _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました')));- return;- }- await loadAgents(true);- await _refreshAgentDetail(agent.agent_id);- } catch (err) {- uiAlert((err && err.message) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));- }+ await _applyAgentMemoryChange(agent, () => _agentMemoryRemove(agent, text));});});}@@ -1927,7 +1918,6 @@ function _renderAgentOutputFormatSection(agent, editing = false) {}}-/** Render the runtime control in the detail body.** The runtime "kind" is locked at create time:@@ -2672,7 +2662,6 @@ function _renderAgentEnabledButton(agent) {});}-function _toggleAgentFieldEditable(on) {const nameEl = document.getElementById('agents-detail-name');const nameInput = document.getElementById('agents-detail-name-input');@@ -4828,5 +4817,7 @@ window.addEventListener('local-cli-upgraded', async (event) => {void _renderAgentDetailRuntime(agent);void _renderAgentDetailCliSettings(agent, { refresh: true });void renderCliAccountUsage(agent, { force: true });- } catch (_) { /* next detail entry revalidates independently */ }+ } catch (_) {+ _agentsLog.warn('CLI account details refresh unavailable');+ }});diff --git a/src/renderer/modules/memory.js b/src/renderer/modules/memory.jsindex 27268362..7abaf338 100644--- a/src/renderer/modules/memory.js+++ b/src/renderer/modules/memory.js@@ -10,8 +10,6 @@// `usage.limit` — never hardcoded here. Stored entries are plain text.const _MEM_LIMIT_WARN = 0.85; // usage bar turns warn above this fraction-const _MEM_IPC_FAILURE_DEDUPE_MS = 60 * 1000;-const _MEM_IPC_FAILURE_MAX_PER_SESSION = 20;const _MEM_IPC_CHANNELS = new Set(['memory.list','memory.add',@@ -24,8 +22,6 @@ const _MEM_IPC_CHANNELS = new Set([const _memLog = (typeof createLogger === 'function')? createLogger('memory'): { info() {}, warn() {} };-const _memIpcFailureState = new Map();-let _memIpcFailureCount = 0;// Ordered scope descriptors for the current render:// { key, kind:'user'|'shared', title, sub, icon }@@ -52,39 +48,6 @@ function _memLogSafe(level, message, data) {} catch (_) { /* diagnostics must not alter the operation result */ }}-function _memLogResult(action, data) {- _memLogSafe('info', 'memory action result', { action, ...(data || {}) });-}--function _memLogReadResult(action, startedAt, results) {- const rows = Array.isArray(results) ? results : [];- const failures = rows.filter((row) => !row || row.ok !== true);- const successCount = rows.length - failures.length;- const payload = {- result: failures.length === 0- ? 'success'- : (successCount > 0 ? 'partial_failure' : 'failure'),- action: action === 'reveal' ? 'reveal' : 'list',- duration_ms: _memDuration(startedAt),- entry_count: rows.reduce((total, row) => (- total + (row && row.ok && Array.isArray(row.entries) ? row.entries.length : 0)- ), 0),- failed_count: failures.length,- };- if (failures.length > 0) {- const details = failures.map(_memFailureDetails);- const errorCodes = [...new Set(details.map((item) => item.error_code))];- const errorTypes = [...new Set(details.map((item) => item.error_type))];- payload.error_code = errorCodes.length === 1 ? errorCodes[0] : 'multiple';- payload.error_type = errorTypes.length === 1 ? errorTypes[0] : 'runtime';- }- _memLogResult('memory_read_result', payload);-}--function _memDuration(startedAt) {- return Math.max(0, Date.now() - startedAt);-}-function _memTarget(target) {return target === 'user' ? 'user' : 'shared';}@@ -128,20 +91,7 @@ function _memFailureDetails(result) {return { error_type: 'runtime', error_code: 'memory_operation_failed' };}-function _memReportIpcFailure(channel, result) {- const safeChannel = _memChannel(channel);- const details = _memFailureDetails(result);- const key = `${safeChannel}:${details.error_code}`;- const now = Date.now();- const previous = _memIpcFailureState.get(key) || 0;- if (now - previous < _MEM_IPC_FAILURE_DEDUPE_MS) return;- if (_memIpcFailureCount >= _MEM_IPC_FAILURE_MAX_PER_SESSION) return;- _memIpcFailureState.set(key, now);- _memIpcFailureCount += 1;-}--async function _memInvoke(channel, payload, options) {- const resultOwned = Boolean(options && options.resultOwned);+async function _memInvoke(channel, payload) {if (!window.orkas || typeof window.orkas.invoke !== 'function') {const failure = {ok: false,@@ -153,7 +103,6 @@ async function _memInvoke(channel, payload, options) {channel: _memChannel(channel),error_code: failure.__memory_error_code,});- if (!resultOwned) _memReportIpcFailure(channel, failure);return failure;}@@ -172,7 +121,6 @@ async function _memInvoke(channel, payload, options) {error_type: details.error_type,error_code: details.error_code,});- if (!resultOwned) _memReportIpcFailure(channel, failure);}return failure;} catch (err) {@@ -187,7 +135,6 @@ async function _memInvoke(channel, payload, options) {error_type: 'ipc',error_code: failure.__memory_error_code,});- if (!resultOwned) _memReportIpcFailure(channel, failure);return failure;}}@@ -208,7 +155,6 @@ function _memScopePayload(key, extra) {// ── Data load ──────────────────────────────────────────────────────────────async function _memLoad() {- const startedAt = Date.now();_memScopes = [{ key: 'user', kind: 'user', title: t('memory.section_user'), sub: t('memory.section_user_sub'), icon: 'users' },{ key: 'shared', kind: 'shared', title: t('memory.section_shared'), sub: t('memory.section_shared_sub'), icon: 'sparkles' },@@ -217,9 +163,7 @@ async function _memLoad() {const results = await Promise.all(_memScopes.map((s) => _memInvoke('memory.list',_memParseScope(s.key),- { resultOwned: true },)));- _memLogReadResult('list', startedAt, results);_memData = {};_memScopes.forEach((s, i) => {const r = results[i];@@ -228,13 +172,10 @@ async function _memLoad() {}async function _memReveal(target) {- const startedAt = Date.now();const result = await _memInvoke('memory.reveal',_memParseScope(target),- { resultOwned: true },);- _memLogReadResult('reveal', startedAt, [result]);return result;}@@ -474,32 +415,13 @@ async function _memSaveEditor(target) {const content = ta.value.trim();if (!content) return;const isEdit = _memEditor && _memEditor.mode === 'edit';- const mode = isEdit ? 'edit' : 'add';- const startedAt = Date.now();const res = isEdit- ? await _memInvoke('memory.replace', _memScopePayload(safeTarget, { oldText: _memEditor.oldText, content }), { resultOwned: true })- : await _memInvoke('memory.add', _memScopePayload(safeTarget, { content }), { resultOwned: true });- const durationMs = _memDuration(startedAt);+ ? await _memInvoke('memory.replace', _memScopePayload(safeTarget, { oldText: _memEditor.oldText, content }))+ : await _memInvoke('memory.add', _memScopePayload(safeTarget, { content }));if (!res.ok) {- const details = _memFailureDetails(res);- _memLogResult('memory_entry_save_result', {- result: 'failure',- target: safeTarget,- mode,- duration_ms: durationMs,- ...details,- });_memToast(_memErrorToText(res.error), 'error');return;}- _memLogResult('memory_entry_save_result', {- result: 'success',- target: safeTarget,- mode,- chars: content.length,- char_count: content.length,- duration_ms: durationMs,- });_memEditor = null;// Refresh just this scope from the op result (it already carries entries+usage).const prev = _memData[safeTarget] || {};@@ -513,25 +435,11 @@ async function _memDelete(target, text) {? await uiConfirm({ message: t('memory.delete_confirm'), okLabel: t('memory.delete'), cancelLabel: t('memory.cancel') }): true;if (!ok) return;- const startedAt = Date.now();- const res = await _memInvoke('memory.remove', _memScopePayload(safeTarget, { oldText: text }), { resultOwned: true });- const durationMs = _memDuration(startedAt);+ const res = await _memInvoke('memory.remove', _memScopePayload(safeTarget, { oldText: text }));if (!res.ok) {- const details = _memFailureDetails(res);- _memLogResult('memory_entry_delete_result', {- result: 'failure',- target: safeTarget,- duration_ms: durationMs,- ...details,- });_memToast(_memErrorToText(res.error), 'error');return;}- _memLogResult('memory_entry_delete_result', {- result: 'success',- target: safeTarget,- duration_ms: durationMs,- });const prev = _memData[safeTarget] || {};_memData[safeTarget] = { entries: res.entries || [], usage: res.usage || prev.usage, path: prev.path };_memRerender();@@ -548,7 +456,13 @@ function _memErrorToText(error) {// ── Modal shell ──────────────────────────────────────────────────────────────+let _memModalKeyHandler = null;+function _memCloseModal() {+ if (_memModalKeyHandler) {+ document.removeEventListener('keydown', _memModalKeyHandler);+ _memModalKeyHandler = null;+ }const host = document.getElementById('memory-modal-host');if (host) host.remove();}@@ -563,8 +477,10 @@ function _memOpenModal(width, innerHtml) {if (typeof window.hydrateUiIcons === 'function') window.hydrateUiIcons(host);// Esc close. Backdrop clicks are ignored to avoid accidental dismissals.const onKey = (e) => {- if (e.key === 'Escape') { _memCloseModal(); document.removeEventListener('keydown', onKey); }+ if (e.isComposing || e.keyCode === 229) return;+ if (e.key === 'Escape') _memCloseModal();};+ _memModalKeyHandler = onKey;document.addEventListener('keydown', onKey);return host;}@@ -766,33 +682,16 @@ function _memUpdateMergeSummary(host) {async function _memDoMerge() {const kept = _memImportItems.filter((it) => it.keep);if (!kept.length) return;- const startedAt = Date.now();let added = 0;let failed = 0;- const failureTypes = new Set();for (const it of kept) {// it.target is 'user' | 'shared' (a scope-key the backend accepts directly).- const res = await _memInvoke('memory.add', _memScopePayload(_memTarget(it.target), { content: it.text }), { resultOwned: true });+ const res = await _memInvoke('memory.add', _memScopePayload(_memTarget(it.target), { content: it.text }));if (res.ok) added++;else {failed++;- failureTypes.add(_memFailureDetails(res).error_type);}}- const result = failed ? (added ? 'partial_failure' : 'failure') : 'success';- const resultPayload = {- result,- added_count: added,- failed_count: failed,- duration_ms: _memDuration(startedAt),- };- if (failed) {- resultPayload.error_type = failureTypes.size === 1 ? Array.from(failureTypes)[0] : 'unknown';- resultPayload.error_code = added ? 'memory_import_partial_failure' : 'memory_import_failed';- }- // Persistence is the terminal boundary. Modal/toast/render failures cannot- // erase or reverse the completed aggregate result.- _memLogResult('memory_import_result', resultPayload);_memCloseModal();if (added) _memToast(t('memory.merge_done', { n: added }), 'success');if (failed) _memToast(t('memory.merge_partial', { n: failed }), 'warning');diff --git a/test/e2e/resources_e2e_crud.spec.ts b/test/e2e/resources_e2e_crud.spec.tsindex 0ce708d6..16b83a80 100644--- a/test/e2e/resources_e2e_crud.spec.ts+++ b/test/e2e/resources_e2e_crud.spec.ts@@ -193,9 +193,11 @@ test.describe('agents and skills', () => {)).toContain("This is the Agent's default capability boundary");});- test('creates an agent, persists its enabled state, and deletes it', async ({ orkas }) => {+ test('creates an agent, persists its enabled state, and deletes it', async ({ modelOrkas: orkas }) => {if (!orkas.page) throw new Error('Orkas renderer is unavailable');const page = orkas.page;+ const completedReply = 'E2E agent edit chat completed without changes.';+ orkas.setModelTextReplies([completedReply]);await openSidebarEntry(page, '#agents-btn');await expect(page.locator('#panel-agents')).toHaveClass(/\bactive\b/);await page.locator('#create-agent-btn').click();@@ -208,11 +210,28 @@ test.describe('agents and skills', () => {await expect(page.locator('#agents-detail-name')).toHaveText('E2EAgent');await expect(page.locator('#agent-edit-btn')).toHaveText('Done');+ // Finish the automatic edit turn before leaving the editor. This CRUD+ // scenario controls its model dependency and does not test cancellation.+ const final = page.locator('#agents-chat-messages .chat-message.assistant [data-role="final"]').last();+ await expect(final).toHaveText(completedReply, { timeout: 20_000 });+ await expect(page.locator('#agents-chat-send-btn')).not.toHaveClass(/\b(streaming|aborting)\b/);+ expect(orkas.modelRequests).toHaveLength(1);await page.locator('#agent-edit-btn').click();await expect(page.locator('#agent-enabled-btn')).toBeVisible();const created = await orkas.invoke<{ agents: AgentSummary[] }>('agents.list');const agent = created.agents.find((item) => item.name === 'E2EAgent');expect(agent).toBeTruthy();+ expect(created.agents.filter((item) => item.name === 'E2EAgent')).toHaveLength(1);+ const fetched = await orkas.invoke<{ agent: AgentDetail }>('agents.get', {+ agent_id: agent?.agent_id,+ });+ expect(fetched.agent.description_zh || fetched.agent.description_en)+ .toBe('Checks deterministic desktop user flows.');+ const history = await orkas.invoke<{ messages: Array<{ role?: string; content?: string }> }>('agents.chat.history', {+ agent_id: agent?.agent_id,+ });+ expect(history.messages.filter((message) => message.role === 'assistant')+ .map((message) => message.content)).toEqual([completedReply]);await page.locator('#agent-enabled-btn').click();await expect.poll(async () => {@@ -241,11 +260,14 @@ test.describe('agents and skills', () => {}),]),}));+ expect(orkas.modelRequests).toHaveLength(1);});- test('creates a skill, persists its enabled state, and deletes it', async ({ orkas }) => {+ test('creates a skill, persists its enabled state, and deletes it', async ({ modelOrkas: orkas }) => {if (!orkas.page) throw new Error('Orkas renderer is unavailable');const page = orkas.page;+ const completedReply = 'E2E skill edit chat completed without changes.';+ orkas.setModelTextReplies([completedReply]);await openSidebarEntry(page, '#skills-btn');await expect(page.locator('#panel-skills')).toHaveClass(/\bactive\b/);await page.locator('#create-skill-btn').click();@@ -258,11 +280,28 @@ test.describe('agents and skills', () => {await expect(page.locator('#skills-detail-name')).toHaveText('e2e-desktop-check');await expect(page.locator('#skill-edit-btn')).toHaveText('Done');+ // Finish the automatic edit turn before leaving the editor. This CRUD+ // scenario controls its model dependency and does not test cancellation.+ const final = page.locator('#skills-chat-messages .chat-message.assistant [data-role="final"]').last();+ await expect(final).toHaveText(completedReply, { timeout: 20_000 });+ await expect(page.locator('#skills-chat-send-btn')).not.toHaveClass(/\b(streaming|aborting)\b/);+ expect(orkas.modelRequests).toHaveLength(1);await page.locator('#skill-edit-btn').click();await expect(page.locator('#skill-enabled-btn')).toBeVisible();const created = await orkas.invoke<{ skills: SkillSummary[] }>('skills.list');const skill = created.skills.find((item) => item.name === 'e2e-desktop-check');expect(skill).toBeTruthy();+ expect(created.skills.filter((item) => item.name === 'e2e-desktop-check')).toHaveLength(1);+ const fetched = await orkas.invoke<{ skill: { name: string; description_zh?: string; description_en?: string } }>('skills.get', {+ id: skill?.id,+ });+ expect(fetched.skill.description_zh || fetched.skill.description_en)+ .toBe('Verifies deterministic desktop UI behavior.');+ const history = await orkas.invoke<{ messages: Array<{ role?: string; content?: string }> }>('skills.chat.history', {+ id: skill?.id,+ });+ expect(history.messages.filter((message) => message.role === 'assistant')+ .map((message) => message.content)).toEqual([completedReply]);await page.locator('#skill-enabled-btn').click();await expect.poll(async () => {@@ -291,5 +330,6 @@ test.describe('agents and skills', () => {}),]),}));+ expect(orkas.modelRequests).toHaveLength(1);});});diff --git a/test/main/features/agents.test.ts b/test/main/features/agents.test.tsindex e97d9cc3..1b349199 100644--- a/test/main/features/agents.test.ts+++ b/test/main/features/agents.test.ts@@ -1,5 +1,6 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import * as fs from 'node:fs';+import { syncBuiltinESMExports } from 'node:module';import * as os from 'node:os';import * as path from 'node:path';@@ -191,6 +192,8 @@ function writeCustomAgent(agentId: string, fields: Partial<Record<string, any>>created_at: '2026-04-18T10:00:00',updated_at: '2026-04-18T10:00:00',};+ if ('description_zh' in fields) data.description_zh = fields.description_zh;+ if ('description_en' in fields) data.description_en = fields.description_en;if ('skill_list' in fields) data.skill_list = fields.skill_list;if ('tool_list' in fields) data.tool_list = fields.tool_list;if ('runtime' in fields) data.runtime = fields.runtime;@@ -2866,23 +2869,47 @@ describe('agents › streamSendToAgentEditChat synthesized progress', () => {expect(seenOpts.agentToolDependencyAuthoring).toBe(true);});- it('does not advertise tool dependency authoring in a CLI Agent editor', async () => {+ it.each([+ { language: 'zh' as const, message: 'Shorten the description.', patch: '<description>审查代码并报告风险。</description>', zh: '审查代码并报告风险。', en: 'Original English' },+ { language: 'en' as const, message: '把描述改短。', patch: '<description>Reviews code and reports risks.</description>', zh: '原有中文', en: 'Reviews code and reports risks.' },+ { language: 'zh' as const, message: '请同时更新中英文描述。', patch: '<description_zh>审查代码。</description_zh><description_en>Reviews code.</description_en>', zh: '审查代码。', en: 'Reviews code.' },+ { language: 'zh' as const, message: '只把英文简介改成更简短的版本。', patch: '<description_en>Reviews code.</description_en>', zh: '原有中文', en: 'Reviews code.' },+ ].flatMap(scenario => (['cli', 'in_process'] as const).map(kind => ({ ...scenario, kind }))))(+ 'applies a $kind description edit with UI language $language: $message', async ({ kind, language, message, patch, zh, en }) => {+ const { setLanguage } = await import('../../../src/main/features/config');+ setLanguage(language);let seenOpts: any = null;+ // Synthetic model output verifies prompt assembly and persistence, not model language quality.streamImpl.current = async function* (opts: any) {seenOpts = opts;- yield { type: 'final', text: 'done' };+ yield { type: 'final', text: `<agent>${patch}</agent>` };};- writeCustomAgent('cli-agent', {- name: 'CliAgent',- runtime: { kind: 'cli', cli: 'codex' },+ const runtime = kind === 'cli' ? { kind: 'cli', cli: 'codex' } : { kind: 'in_process' };+ writeCustomAgent('edited-agent', {+ name: 'Reviewer',+ description_zh: '原有中文',+ description_en: 'Original English',+ runtime,});const a = await loadAgents();- for await (const _ev of a.streamSendToAgentEditChat('u1', 'cli-agent', '更新说明')) {- // drain+ const events: any[] = [];+ for await (const event of a.streamSendToAgentEditChat(TEST_UID, 'edited-agent', message)) {+ events.push(event);}- expect(seenOpts.agentToolDependencyAuthoring).toBeUndefined();+ expect(seenOpts.agentToolDependencyAuthoring).toBe(kind === 'cli' ? undefined : true);+ expect(seenOpts.systemSkillList).toEqual(['agent-creator']);+ expect(seenOpts.systemPrompt).not.toContain('bilingual `description`');+ const { buildLanguageDirective } = await import('../../../src/main/i18n');+ expect(seenOpts.systemPrompt).toContain(buildLanguageDirective(language));+ expect(seenOpts.systemPrompt).toContain('**Description (Chinese)**: 原有中文');+ expect(seenOpts.systemPrompt).toContain('**Description (English)**: Original English');+ expect(events.some(event => event.type === 'error')).toBe(false);+ expect(events).toContainEqual(expect.objectContaining({ type: 'final', updated: expect.any(Object) }));+ const stored = JSON.parse(fs.readFileSync(path.join(customAgentsDir(), 'edited-agent', 'agent.json'), 'utf8'));+ expect(stored).toMatchObject({ name: 'Reviewer', description_zh: zh, description_en: en });+ expect((await a.getAgent('edited-agent'))?.runtime?.kind ?? 'in_process').toBe(kind);});it('passes edit-chat attachments into the model prompt and history', async () => {@@ -3051,6 +3078,28 @@ describe('agents › deleteCustomAgent', () => {});describe('agents › buildAgentEditSystemPrompt', () => {+ it.each(['in_process', 'cli'] as const)('separates description language in the %s editor', async (kind) => {+ const { setLanguage } = await import('../../../src/main/features/config');+ setLanguage('zh');+ const a = await loadAgents();+ const sys = a.buildAgentEditSystemPrompt({+ name: 'Reviewer',+ description_en: 'Reviews code.',+ runtime: kind === 'cli' ? { kind: 'cli', cli: 'codex' } : { kind: 'in_process' },+ });+ expect(sys).toContain('Fallback UI language: **Chinese (简体中文)**');+ expect(sys).toContain('a current explicit request about reply language');+ expect(sys).toContain('Agent and Skill descriptions instead follow the description-language rules in their owning creator Skill');+ expect(sys.indexOf('## User language')).toBeGreaterThan(sys.indexOf('## Runtime injection'));+ expect(sys).toContain('**Description (English)**: Reviews code.');+ if (kind === 'cli') {+ expect(sys).toContain('Apply a clear edit request directly');+ expect(sys).toContain('Ask only when necessary information is missing');+ expect(sys).toContain('neither `<operation>` nor `<agent_id>`');+ expect(sys).not.toMatch(/Editable here|Clarify what coding task|Iterate gradually/i);+ }+ });+it('substitutes agent fields and drops the removed skills_list placeholder', async () => {const a = await loadAgents();const sys = await a.buildAgentEditSystemPrompt({@@ -3091,7 +3140,34 @@ describe('agents › buildAgentEditSystemPrompt', () => {});describe('agents › list cache invalidation', () => {- it('rebuilds a v2 OpenCode catalog snapshot with the host-owned project_dir schema', async () => {+ it('retains the last complete disk snapshot on a failed refresh and reads the recovered source next time', async () => {+ writeCustomAgent('recoverable', { name: 'Old name' });+ const a = await loadAgents();+ expect((await a.listAgents())[0].name).toBe('Old name');+ const paths = await import('../../../src/main/paths');+ const cache = paths.userAgentCatalogCacheFile(TEST_UID);+ const snapshot = fs.readFileSync(cache, 'utf8');+ const file = path.join(customAgentsDir(), 'recoverable', 'agent.json');+ const body = JSON.parse(fs.readFileSync(file, 'utf8'));+ fs.writeFileSync(file, JSON.stringify({ ...body, name: 'Fresh name' }));+ const stamp = fs.statSync(customAgentsDir());+ fs.utimesSync(customAgentsDir(), stamp.atime, new Date(stamp.mtimeMs + 2000));+ const read = fs.promises.readFile.bind(fs.promises);+ const spy = vi.spyOn(fs.promises, 'readFile').mockImplementation((...args: any[]) => {+ if (args[0] === file) return Promise.reject(Object.assign(new Error('private read failure'), { code: 'EIO' }));+ return (read as any)(...args);+ });+ syncBuiltinESMExports();+ try {+ await expect(a.listAgents()).rejects.toThrow('Agent catalog unavailable');+ await expect(a.listAgentSummaries()).rejects.toThrow('Agent catalog unavailable');+ expect(fs.readFileSync(cache, 'utf8')).toBe(snapshot);+ } finally { spy.mockRestore(); syncBuiltinESMExports(); }+ expect((await a.listAgents())[0].name).toBe('Fresh name');+ expect(JSON.parse(fs.readFileSync(cache, 'utf8')).data[0].name).toBe('Fresh name');+ });++ it.each([2, 3])('rebuilds a v%s catalog instead of trusting an obsolete or poisoned empty snapshot', async (version) => {writeCustomAgent('cached-opencode', {name: 'Cached OpenCode',runtime: { kind: 'cli', cli: 'opencode' },@@ -3105,8 +3181,8 @@ describe('agents › list cache invalidation', () => {const paths = await import('../../../src/main/paths');const cacheFile = paths.userAgentCatalogCacheFile(TEST_UID);const stale = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));- stale.version = 2;- stale.data = stale.data.map((agent: any) => (+ stale.version = version;+ stale.data = version === 3 ? [] : stale.data.map((agent: any) => (agent.agent_id === 'cached-opencode' ? { ...agent, inputs: undefined } : agent));fs.writeFileSync(cacheFile, JSON.stringify(stale));@@ -3120,7 +3196,41 @@ describe('agents › list cache invalidation', () => {expect(repaired?.inputs?.find((input) => input.id === 'project_dir')).toMatchObject({type: 'directory', required: true, default: '',});- expect(JSON.parse(fs.readFileSync(cacheFile, 'utf8')).version).toBe(3);+ expect(JSON.parse(fs.readFileSync(cacheFile, 'utf8')).version).toBe(4);+ });++ it.each(['EACCES', 'EIO', 'malformed'])('does not publish a partial catalog after %s and recovers without manual invalidation', async (fault) => {+ writeCustomAgent('a-healthy', { name: 'Healthy' });+ writeCustomAgent('z-recoverable', { name: 'Recoverable' });+ const file = path.join(customAgentsDir(), 'z-recoverable', 'agent.json');+ const source = fs.readFileSync(file, 'utf8');+ const a = await loadAgents();+ const paths = await import('../../../src/main/paths');+ const cache = paths.userAgentCatalogCacheFile(TEST_UID);+ const read = fs.promises.readFile.bind(fs.promises);+ const spy = vi.spyOn(fs.promises, 'readFile').mockImplementation((...args: any[]) => {+ if (args[0] === file) return Promise.reject(Object.assign(new Error('private read failure'), { code: fault }));+ return (read as any)(...args);+ });+ syncBuiltinESMExports();+ if (fault === 'malformed') {+ spy.mockRestore();+ syncBuiltinESMExports();+ fs.writeFileSync(file, '{broken');+ }+ try {+ await expect(a.listAgents()).rejects.toThrow('Agent catalog unavailable');+ expect(fs.existsSync(cache)).toBe(false);+ expect(fs.readFileSync(path.join(customAgentsDir(), 'a-healthy', 'agent.json'), 'utf8')).toContain('Healthy');+ } finally {+ spy.mockRestore();+ syncBuiltinESMExports();+ fs.writeFileSync(file, source);+ }+ expect((await a.listAgents()).map(agent => agent.agent_id).sort()).toEqual(['a-healthy', 'z-recoverable']);+ vi.resetModules();+ (await import('../../../src/main/features/users')).activateUser(TEST_UID);+ expect((await (await loadAgents()).listAgents()).map(agent => agent.agent_id).sort()).toEqual(['a-healthy', 'z-recoverable']);});it('reuses the persisted catalog after a module restart and honors force invalidation', async () => {@@ -3142,7 +3252,9 @@ describe('agents › list cache invalidation', () => {expect((await restarted.listAgents())[0].name).toBe('Persisted Agent');restarted.clearAgentListCache();- expect(await restarted.listAgents()).toEqual([]);+ await expect(restarted.listAgents()).rejects.toThrow('Agent catalog unavailable');+ writeCustomAgent('persisted-agent', { name: 'Recovered Agent' });+ expect((await restarted.listAgents())[0].name).toBe('Recovered Agent');});it('picks up newly created agents on next listAgents', async () => {diff --git a/test/main/features/group_chat/agents-index.test.ts b/test/main/features/group_chat/agents-index.test.tsindex be3c93fd..661a61a8 100644--- a/test/main/features/group_chat/agents-index.test.ts+++ b/test/main/features/group_chat/agents-index.test.ts@@ -25,6 +25,8 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import * as fs from 'node:fs';+import nativeFs from 'node:fs';+import { syncBuiltinESMExports } from 'node:module';import * as os from 'node:os';import * as path from 'node:path';@@ -84,6 +86,45 @@ async function buildBlock(uid: string): Promise<string> {}describe('agents_index block — header + per-entry shape', () => {+ it('rejects an inaccessible catalog stamp rather than treating the root as absent', async () => {+ writeAgent(customAgentsDir(), 'kept', { name: 'Kept' });+ const stat = nativeFs.statSync.bind(nativeFs);+ const spy = vi.spyOn(nativeFs, 'statSync').mockImplementation(((...args: any[]) => {+ if (args[0] === customAgentsDir()) throw Object.assign(new Error('private stamp failure'), { code: 'EACCES' });+ return (stat as any)(...args);+ }) as typeof fs.statSync);+ syncBuiltinESMExports();+ try { await expect(buildBlock(TEST_UID)).rejects.toThrow('Agent catalog unavailable'); }+ finally { spy.mockRestore(); syncBuiltinESMExports(); }+ expect(await buildBlock(TEST_UID)).toContain('@Kept');+ });++ it('keeps a disabled Agent out of a genuinely empty enabled roster', async () => {+ writeAgent(customAgentsDir(), 'disabled', { name: 'Disabled' });+ const enabled = await import('../../../../src/main/features/component_enabled');+ enabled.setAgentEnabled(TEST_UID, 'disabled', false);+ const block = await buildBlock(TEST_UID);+ expect(block).toContain('(no agents)');+ expect(block).not.toContain('@Disabled');+ });++ it('rejects a catalog directory failure instead of advertising no agents, then recovers', async () => {+ writeAgent(customAgentsDir(), 'healthy', { name: 'Healthy' });+ writeAgent(builtinAgentsDir(), 'other', { name: 'Other' });+ const read = fs.promises.readdir.bind(fs.promises);+ const spy = vi.spyOn(fs.promises, 'readdir').mockImplementation((...args: any[]) => {+ if (args[0] === customAgentsDir()) return Promise.reject(Object.assign(new Error('private directory failure'), { code: 'EACCES' }));+ return (read as any)(...args);+ });+ syncBuiltinESMExports();+ try { await expect(buildBlock(TEST_UID)).rejects.toThrow('Agent catalog unavailable'); }+ finally { spy.mockRestore(); syncBuiltinESMExports(); }+ const block = await buildBlock(TEST_UID);+ expect(block).toContain('@Healthy');+ expect(block).toContain('@Other');+ expect(block).not.toContain('(no agents)');+ });+it('exposes the complete built-in corpus with each authored description once and no workflows', async () => {const root = path.join(__dirname, '../../../../resources/builtin/marketplace/agents');const agents = fs.readdirSync(root).flatMap((id) => {@@ -313,6 +354,14 @@ describe('Commander project-task prompt gating', () => {expect(nonProject).not.toContain('$project_tasks_rules');expect(project).toContain('### Project tasks (the work backlog)');expect(project).not.toContain('$project_tasks_rules');+ const taskContract = "preserve the selected task's requirements unless the current request explicitly changes them";+ const pauseContract = 'A review or pause applies to the work it names; a hold on dependent work does not suspend its authorized prerequisites';+ const deliveryContract = 'Reconcile both direct and delegated delivery';+ for (const contract of [taskContract, pauseContract, deliveryContract]) {+ expect(project.split(contract)).toHaveLength(2);+ expect(project.indexOf(contract)).toBeLessThan(project.indexOf('## Runtime injection'));+ expect(nonProject).not.toContain(contract);+ }expect(project.indexOf('### Project tasks (the work backlog)')).toBeLessThan(project.indexOf('## Runtime injection'));expect(nonProject).not.toContain('## Orchestration continuity');diff --git a/test/main/features/marketplace_reconcile.test.ts b/test/main/features/marketplace_reconcile.test.tsindex d1d90b80..34889cba 100644--- a/test/main/features/marketplace_reconcile.test.ts+++ b/test/main/features/marketplace_reconcile.test.ts@@ -1,5 +1,7 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import * as fs from 'node:fs';+import nativeFs from 'node:fs';+import { syncBuiltinESMExports } from 'node:module';import * as http from 'node:http';import * as os from 'node:os';import * as path from 'node:path';@@ -69,6 +71,40 @@ afterEach(async () => {});describe('marketplace reconcile', () => {+ it('keeps cleanup diagnostics private without suppressing the recoverable failure', async () => {+ const logger = await import('../../../src/main/logger');+ const createLogger = logger.createLogger;+ const warnings: unknown[][] = [];+ const capture = vi.spyOn(logger, 'createLogger').mockImplementation(name => {+ const scoped = createLogger(name);+ return name === 'marketplace_reconcile'+ ? {...scoped, warn: (message: string, ...args: unknown[]) => {warnings.push([message,...args]);}}+ : scoped;+ });+ const artifact = path.join(tmpDir, 'u1', 'local', 'marketplace', 'agents', '.private-draft.install-abandoned');+ fs.mkdirSync(artifact, {recursive:true});+ const rm = nativeFs.promises.rm.bind(nativeFs.promises);+ const denied = Object.assign(new Error(`PRIVATE-CLEANUP-CONTENT ${artifact}`), {code:'EACCES'});+ const remove = vi.spyOn(nativeFs.promises, 'rm').mockImplementation(async (file, options) => {+ if(String(file)===artifact)throw denied;+ return rm(file,options);+ });+ syncBuiltinESMExports();+ try {+ writeManifest({version:1,agents:[],skills:[]});+ const reconcile = await import('../../../src/main/features/marketplace_reconcile');+ expect(await reconcile.reconcileInstalls('u1')).toMatchObject({failed:[]});+ expect(fs.existsSync(artifact)).toBe(true);+ expect(warnings).toHaveLength(1);+ const payload=JSON.stringify(warnings);+ for(const secret of [artifact,path.basename(artifact),'PRIVATE-CLEANUP-CONTENT'])expect(payload).not.toContain(secret);+ expect(warnings[0][1]).toMatchObject({+ artifact:{path_hash:expect.any(String)},+ error:{code:'EACCES',message_hash:expect.any(String)},+ });+ } finally {remove.mockRestore();capture.mockRestore();syncBuiltinESMExports();}+ });+function writeLocalSkill(id: string, meta: Record<string, unknown>): string {const dir = path.join(tmpDir, 'u1', 'local', 'marketplace', 'skills', id);fs.mkdirSync(dir, { recursive: true });diff --git a/test/main/features/skills.test.ts b/test/main/features/skills.test.tsindex 6b207a54..d16b9f03 100644--- a/test/main/features/skills.test.ts+++ b/test/main/features/skills.test.ts@@ -2325,6 +2325,13 @@ describe('skills › buildSkillEditSystemPrompt', () => {expect(sys).toContain('a demo');expect(sys).toContain('alpha'); // shows up in skill_dir (dir name == id)expect(sys).toContain('SKILL.md'); // file listing includes SKILL.md+ expect(sys).toContain('This session is bound to the skill in Runtime injection');+ expect(sys).toContain('<skill-reply>...</skill-reply>');+ expect(sys).toContain('<skill-as-package name="<installed-name>"/>');+ expect(sys).not.toMatch(/\bModes? [ABC]|How to work with the user|Dependency installs/i);+ expect(sys).toContain('a current explicit request about reply language');+ expect(sys).toContain('Agent and Skill descriptions instead follow the description-language rules in their owning creator Skill');+ expect(sys.indexOf('## User language')).toBeGreaterThan(sys.indexOf('## Runtime injection'));// Template no longer carries the user-input footer.expect(sys).not.toMatch(/##\s*用户的初始请求/);// All placeholders resolved.diff --git a/test/main/features/system_skills.test.ts b/test/main/features/system_skills.test.tsindex 9e843af8..ed65ba0a 100644--- a/test/main/features/system_skills.test.ts+++ b/test/main/features/system_skills.test.ts@@ -527,8 +527,8 @@ describe('system skill contracts', () => {it('pins agent-creator descriptions to current-language defaults and hidden provenance', () => {const md = packagedSystemSkillBundle('agent-creator');- expect(md).toContain('Use `<description_zh>` / `<description_en>` only when the user explicitly asks for multilingual/bilingual descriptions');- expect(md).toContain('Default: one current-language description only');+ expect(md).toContain('Use `<description>` by default');+ expect(md).toContain('explicit description-language request, otherwise the current UI language');expect(md).toContain('Do **not** show source provenance by default');expect(md).toContain('No container, no mutation, no success claim');expect(md).toContain('the number of valid containers must equal the number of Agents');diff --git a/test/renderer/agent-memory-outcomes.test.ts b/test/renderer/agent-memory-outcomes.test.tsnew file mode 100644index 00000000..19414bd1--- /dev/null+++ b/test/renderer/agent-memory-outcomes.test.ts@@ -0,0 +1,116 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';+import vm from 'node:vm';+import { describe, expect, it, vi } from 'vitest';++const renderer = path.join(__dirname, '../../src/renderer');+const source = readFileSync(path.join(renderer, 'modules/agents.js'), 'utf8');+const locales = Object.fromEntries(['en', 'zh'].map(locale => [locale,+ JSON.parse(readFileSync(path.join(renderer, `locales/${locale}.json`), 'utf8'))]));++function memoryAction(action: 'add' | 'edit' | 'remove', options: { locale?: 'en' | 'zh'; commander?: boolean } = {}) {+ const locale = options.locale || 'en';+ let click: ((event: any) => Promise<void>) | undefined;+ const alerts: string[] = [], warnings: any[] = [];+ const invoke = vi.fn<(channel: string, payload?: any) => Promise<any>>(async () => ({ ok: true }));+ const host = { querySelectorAll: (selector: string) => selector === `[data-agent-memory-${action}]` ? [{+ getAttribute: () => 'Synthetic saved fact',+ addEventListener: (_type: string, listener: any) => { click = listener; },+ }] : [] };+ const context: any = {+ console, setTimeout, clearTimeout,+ createLogger: () => ({ warn: (...args: any[]) => warnings.push(args), info() {}, error() {} }),+ document: { readyState: 'loading', addEventListener() {}, querySelector: () => null, querySelectorAll: () => [], getElementById: () => null },+ window: { addEventListener() {}, orkas: { invoke } },+ getLang: () => locale,+ t: (key: string) => locales[locale][key] || key,+ normalizeCatalogSource: (value: string) => value || '',+ uiPrompt: vi.fn(async () => 'Synthetic new fact'),+ uiConfirm: vi.fn(async () => true),+ uiAlert: (message: string) => { alerts.push(message); },+ };+ vm.createContext(context); vm.runInContext(source, context, { filename: 'agents.js' });+ const refresh = vi.fn(async () => {});+ context.loadAgents = refresh; context._refreshAgentDetail = vi.fn(async () => {});+ context.host = host; context.agent = { agent_id: options.commander ? 'commander' : 'fixture-agent', source: 'custom' };+ vm.runInContext('_wireAgentMemoryControls(host, agent)', context);+ if (!click) throw new Error('Memory action was not wired');+ return { context, invoke, alerts, warnings, refresh, run: () => click!({ preventDefault() {} }),+ failureText: locales[locale]['memory.error_generic'], fullText: locales[locale]['memory.error_full'] };+}++describe('Agent memory action outcomes', () => {+ it('has the shared recovery message in every registered locale', () => {+ const supported = vm.runInNewContext(readFileSync(path.join(renderer, 'modules/i18n.js'), 'utf8')+ + '; getSupportedLanguages()', { createLogger: () => ({ warn() {} }), window: {} }) as Array<{ code:string }>;+ expect(supported.length).toBeGreaterThan(0);+ for (const { code } of supported) {+ const table = JSON.parse(readFileSync(path.join(renderer, `locales/${code}.json`), 'utf8'));+ expect(typeof table['memory.error_generic'], code).toBe('string');+ expect(table['memory.error_generic'].trim(), code).not.toBe('');+ expect(table['memory.error_generic'], code).not.toBe('memory.error_generic');+ }+ });++ for (const action of ['add', 'edit', 'remove'] as const) {+ it.each([+ { locale:'en' as const, thrown:false }, { locale:'zh' as const, thrown:false },+ { locale:'en' as const, thrown:true }, { locale:'zh' as const, thrown:true },+ ])(`${action} hides raw errors ($locale, thrown=$thrown)`, async ({ locale, thrown }) => {+ const h = memoryAction(action, { locale });+ const marker = 'PRIVATE_AGENT_MEMORY_DIAGNOSTIC';+ h.invoke.mockImplementation(async () => { if (thrown) throw new Error(marker); return { ok: false, error: marker }; });+ await h.run();+ expect(h.alerts).toEqual([h.failureText]);+ expect(JSON.stringify([h.alerts, h.warnings])).not.toContain(marker);++ });++ it.each(['list', 'detail'])(`${action} preserves a successful write when %s refresh fails`, async phase => {+ const h = memoryAction(action);+ (phase === 'list' ? h.refresh : h.context._refreshAgentDetail).mockRejectedValue(new Error('PRIVATE_REFRESH_DIAGNOSTIC'));+ await h.run();+ expect(h.alerts).toEqual([]);++ expect(h.warnings).toEqual([['agent memory refresh failed', { error_code: 'refresh_failed' }]]);+ });++ it.each([null, undefined])(`${action} reports a missing IPC reply without refreshing (%s)`, async response => {+ const h = memoryAction(action); h.invoke.mockResolvedValue(response); await h.run();+ expect(h.alerts).toEqual([h.failureText]); expect(h.refresh).not.toHaveBeenCalled();++ });++ it(`${action} preserves the full-store message`, async () => {+ const h = memoryAction(action);+ h.invoke.mockResolvedValue({ ok: false, error: 'memory full: synthetic capacity refusal' } as any);+ await h.run();+ expect(h.alerts).toEqual([h.fullText]); expect(h.refresh).not.toHaveBeenCalled();+ });++ it.each([false, true])(`${action} preserves the ordinary IPC route (commander=%s)`, async commander => {+ const h = memoryAction(action, { commander }); await h.run();+ const operation = { add:'add', edit:'replace', remove:'remove' }[action];+ const channel = commander ? `memory.${operation}` : `agents.memory.${action === 'edit' ? 'update' : action}`;+ const content = action === 'remove' ? {} : { content:'Synthetic new fact' };+ const selector = action === 'add' ? {} : commander+ ? { oldText:'Synthetic saved fact' } : { old_text:'Synthetic saved fact' };+ const identity = commander ? { target:'agent', agentId:'commander' } : { agent_id:'fixture-agent' };+ expect(h.invoke).toHaveBeenCalledExactlyOnceWith(channel, { ...identity, ...content, ...selector });+ expect(h.alerts).toEqual([]); expect(h.refresh).toHaveBeenCalledOnce();++ });+ }++ it.each(['', ' ', 'Synthetic saved fact'])('does not submit an empty or unchanged edit (%s)', async text => {+ const h = memoryAction('edit'); h.context.uiPrompt.mockResolvedValue(text); await h.run();+ expect(h.invoke).not.toHaveBeenCalled();+ });++ it('does not write when the prompt or deletion confirmation is cancelled', async () => {+ for (const action of ['add', 'edit', 'remove'] as const) {+ const h = memoryAction(action); h.context.uiPrompt.mockResolvedValue(null); h.context.uiConfirm.mockResolvedValue(false);+ await h.run(); expect(h.invoke).not.toHaveBeenCalled();+ }+ });+});diff --git a/test/renderer/memory-full-notice.test.ts b/test/renderer/memory-full-notice.test.tsindex aed7796d..6be7f6e7 100644--- a/test/renderer/memory-full-notice.test.ts+++ b/test/renderer/memory-full-notice.test.ts@@ -57,7 +57,9 @@ describe('memory page full notice', () => {});describe('project memory full notice', () => {- function projectContext() {+ function projectContext(realLogger = false) {+ const records: any[] = [];+ const timers: Array<() => void> = [];const nodes: Record<string, any> = {'project-memory-list': { innerHTML: '', style: {}, appendChild() {} },'project-memory-empty': { style: {} },@@ -81,8 +83,18 @@ describe('project memory full notice', () => {t: (key: string) => key,setTimeout, clearTimeout,});+ if (realLogger) {+ delete context.createLogger;+ context.console = { log() {}, info() {}, warn() {}, error() {}, debug() {} };+ context.window.orkas.log = (record: any) => records.push(record);+ context.setTimeout = (callback: () => void) => { timers.push(callback); return timers.length; };+ vm.runInContext(fs.readFileSync(path.join(rendererRoot, 'modules/logger.js'), 'utf8'), context, { filename: 'logger.js' });+ }vm.runInContext(projectSource, context, { filename: 'project-detail.js' });- return { context, nodes, alerts };+ return { context, nodes, alerts, records, flushLogs() {+ for (let index = 0; timers.length && index < 32; index++) timers.shift()!();+ expect(timers).toHaveLength(0);+ } };}it('toggles the notice from the store usage', () => {@@ -93,6 +105,32 @@ describe('project memory full notice', () => {expect(nodes['project-memory-full'].hidden).toBe(true);});+ it.each([+ ['read', 'load project memory failed', 'ipc', 'memory_ipc_invoke_failed'],+ ['mutate', 'project memory mutate failed', 'ipc', 'memory_ipc_invoke_failed'],+ ['refresh', 'refresh project memory after mutation failed', 'runtime', 'memory_operation_failed'],+ ])('keeps the %s failure private through the real logger bridge', async (phase, message, type, code) => {+ const { context, records, alerts, flushLogs } = projectContext(true);+ const marker = 'PRIVATE_MEMORY_DIAGNOSTIC_MARKER';+ context.currentUserId = 'account-fixture';+ vm.runInContext("_projectDetailPid = 'project-fixture'", context);+ if (phase === 'refresh') {+ vm.runInContext(`window.orkas.invoke = async () => ({ ok:true, entries:['fixture'], usage:{full:false} });+ _renderProjectMemoryList = () => { throw new Error(${JSON.stringify(marker)}); }`, context);+ } else {+ vm.runInContext(`window.orkas.invoke = async () => { throw new Error(${JSON.stringify(marker)}); }`, context);+ }+ const outcome = await vm.runInContext(phase === 'read' ? "_loadProjectMemory('project-fixture')"+ : "_mutateProjectMemory('memory.add', { content:'fixture' })", context);+ flushLogs();+ expect(records).toHaveLength(1);+ expect(records[0]).toMatchObject({ level: 'warn', message });+ expect(JSON.stringify(records)).not.toContain(marker);+ expect(records[0].data).toEqual([{ error_type: type, error_code: code }]);+ if (phase === 'mutate') { expect(outcome.ok).toBe(false); expect(alerts).toEqual(['project.memory.failed']); }+ if (phase === 'refresh') { expect(outcome).toEqual({ ok:true, failure:null }); expect(alerts).toHaveLength(0); }+ });+it('classifies a refused add as full', () => {const { context } = projectContext();expect(vm.runInContext("_projectMemoryFailure({ error: 'memory full: the project store would hold 17/16 entries' }).error_code", context))@@ -100,7 +138,11 @@ describe('project memory full notice', () => {});it('places a localized status notice in the project memory panel', () => {- expect(html).toMatch(/id="project-memory-full"[^>]*role="status"[^>]*hidden[^>]*data-i18n="memory\.full_notice"|id="project-memory-full"[^>]*data-i18n="memory\.full_notice"/);+ const notice = html.match(/<p\b[^>]*\bid="project-memory-full"[^>]*>/)?.[0];+ expect(notice).toBeDefined();+ expect(notice).toMatch(/\srole="status"(?:\s|>)/);+ expect(notice).toMatch(/\shidden(?:\s|>)/);+ expect(notice).toMatch(/\sdata-i18n="memory\.full_notice"(?:\s|>)/);});});@@ -112,7 +154,7 @@ describe('agent memory full message', () => {const text = vm.runInNewContext(`(${match?.[0]})`, { t: (key: string) => key }) as (res: any, fallback: string) => string;const refused = { ok: false, error: 'memory full: the agent store would hold 17/16 entries. Consolidate it first: merge related entries with replace or remove outdated ones, then retry.' };expect(text(refused, 'fallback')).toBe('memory.error_full');- expect(text({ ok: false, error: 'old_text not found' }, 'fallback')).toBe('old_text not found');+ expect(text({ ok: false, error: 'old_text not found' }, 'fallback')).toBe('fallback');expect(text(null, 'fallback')).toBe('fallback');// Every agent-memory add/edit failure goes through the helper.expect(source).not.toMatch(/uiAlert\(\(res && res\.error\) \|\| _agentLabel\('agents\.memory_update_failed'/);