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.

Sync release 1.6.8 shared improvements

wytdd835b8ed831
diff --git a/resources/builtin/_manifest.json b/resources/builtin/_manifest.json
index 9f17e0ad..b40303e5 100644
--- a/resources/builtin/_manifest.json
+++ b/resources/builtin/_manifest.json
@@ -1,6 +1,6 @@
{
"schema": 1,
- "content_tree_sha256": "d9031626322133bc758ef086eacf147f3bd2d82ec9509e80922814f3ee249607",
+ "content_tree_sha256": "535d923aa8eb9ed696a3b24f31edf5711076bdb835eb010270ebb3df6e74a131",
"files": [
{
"path": "marketplace/agents/173d4235a431/_meta.json",
@@ -19,8 +19,8 @@
},
{
"path": "marketplace/agents/78900d8758bc/agent.json",
- "bytes": 4331,
- "sha256": "056511550346c82163b65428aa936cf6dd69cc79f97e934356e1e33b4c007dc0"
+ "bytes": 4344,
+ "sha256": "da67a5e0092a547ea28cbe0f4ddf4f3181fe500328152112665ee17541b90fa3"
},
{
"path": "marketplace/agents/79df9cc89f5f/agent.json",
@@ -945,7 +945,7 @@
{
"path": "marketplace/skills/ee99fbb42964/_meta.json",
"bytes": 146,
- "sha256": "f501c5f987c76087a2668c4a1ced3c375e1b467941abed344cfda44b590a53d9"
+ "sha256": "ed65a6445bbe4eb2b34cdeb7ff40972e1f42b07ee965ea9e1cc635b493db4b99"
},
{
"path": "marketplace/skills/ee99fbb42964/references/citation-style.md",
@@ -954,8 +954,8 @@
},
{
"path": "marketplace/skills/ee99fbb42964/references/compact-landscape.md",
- "bytes": 12357,
- "sha256": "c7084f55f4078af94a638034016e6d533e577fcdbe21b9d1fe33c78381f48201"
+ "bytes": 12358,
+ "sha256": "4df1f9428340ff8aff1c334767222b72cb2dfbb310859fe059e245fe73385ff8"
},
{
"path": "marketplace/skills/ee99fbb42964/references/evidence-standards.md",
@@ -964,8 +964,8 @@
},
{
"path": "marketplace/skills/ee99fbb42964/references/operations-and-report.md",
- "bytes": 10005,
- "sha256": "08337e2a15441bb826926cd32e53ae9b35abd29bd0720de265cc1351565e76ed"
+ "bytes": 10309,
+ "sha256": "0f4d73d08f0661a7310e46c088e1a5af6232807cb02e1c25a2ab437a6ef70798"
},
{
"path": "marketplace/skills/ee99fbb42964/references/report-structure.md",
@@ -1004,8 +1004,8 @@
},
{
"path": "marketplace/skills/ee99fbb42964/scripts/citations.py",
- "bytes": 61326,
- "sha256": "7d99bf9ea0679ce7bbf993eb6f59ceffc4d90c35495d8c70b742c9e0cb4118a0"
+ "bytes": 62055,
+ "sha256": "c43aca918b093887d3a55ef824b10cb490fbb2d8cbab1166a2182c6a8c29a66a"
},
{
"path": "marketplace/skills/ee99fbb42964/scripts/compress.py",
@@ -1014,8 +1014,8 @@
},
{
"path": "marketplace/skills/ee99fbb42964/SKILL.md",
- "bytes": 9009,
- "sha256": "e6be318ea6fa499092f91a9d691397c28e95c04915bac1664a63a1a43e23e518"
+ "bytes": 9211,
+ "sha256": "417cee8df9160d150ecbe35eeff2aa21cd28b833a31158cc9f02824b64b437d7"
},
{
"path": "marketplace/skills/ee99fbb42964/test/test_academic.py",
@@ -1029,8 +1029,8 @@
},
{
"path": "marketplace/skills/ee99fbb42964/test/test_citations.py",
- "bytes": 63468,
- "sha256": "c7b6ac8f87c3780d078f99d2359ed06cd91b1189da21770c5148563250b9c1ae"
+ "bytes": 64694,
+ "sha256": "fed9abed91b4841ec602bb8ffa5467e54350648c9fab61b2b8de0a345cd75915"
},
{
"path": "marketplace/skills/ee99fbb42964/test/test_compress.py",
@@ -1369,8 +1369,8 @@
},
{
"path": "system/skills/agent-creator/references/cli-and-prose.md",
- "bytes": 1993,
- "sha256": "d8e29fa21a88615c6e545c7493ed141a51421bbe8e6771855785953741f1aa27"
+ "bytes": 1850,
+ "sha256": "2682012568ee3144844820cb4cbd0ef9bb58ec89f96bd33f619a91eab7042e2a"
},
{
"path": "system/skills/agent-creator/references/llm-agent-fields.md",
@@ -1379,13 +1379,13 @@
},
{
"path": "system/skills/agent-creator/references/source-and-editing.md",
- "bytes": 3702,
- "sha256": "f4999737cdcb18faa3b38de0bcc0cad13033a29b5b9ba665f24a5b373f9a77fd"
+ "bytes": 3193,
+ "sha256": "7a114a05d1e6b91d6f755050b6306dca0911a5944e9043a2a40ee5a0d784d5c1"
},
{
"path": "system/skills/agent-creator/SKILL.md",
- "bytes": 6526,
- "sha256": "00f5decc6cbd73e7c71a8a201e334fa9394a2b1c90f5c40e2965b9e50ee3845a"
+ "bytes": 6429,
+ "sha256": "d9df1fdcafb0be2870f6165ab1752564190f9476237dc25cf717f9f1758a8b4a"
},
{
"path": "system/skills/autotask-creator/SKILL.md",
@@ -1394,8 +1394,8 @@
},
{
"path": "system/skills/memory-manager/SKILL.md",
- "bytes": 3654,
- "sha256": "a124936ec7a7c29c878c7970001f208db871f9407063f3998cc97bb1388ffa8a"
+ "bytes": 3764,
+ "sha256": "6f6dc8f418c5327a3a4c0f455d84db81dea627e78fdfacf614ba453ee5d2ee73"
},
{
"path": "system/skills/package-installer/SKILL.md",
@@ -1409,8 +1409,8 @@
},
{
"path": "system/skills/skill-creator/references/authoring.md",
- "bytes": 6229,
- "sha256": "ce5ab09738177d77b9fd70e107aa8b7f176879157f3818c41d1b868d02b912a8"
+ "bytes": 6461,
+ "sha256": "e6404f3f688f18c4d3e40e08ecafdc8301f65d4cf8ca77c5e5ba902807582b29"
},
{
"path": "system/skills/skill-creator/references/file-deletion.md",
@@ -1429,8 +1429,8 @@
},
{
"path": "system/skills/skill-creator/SKILL.md",
- "bytes": 7238,
- "sha256": "19e3b573aded1c409cf90a645b5c11b4a4ec9a232f6d47fc627e746ab9aa993d"
+ "bytes": 7281,
+ "sha256": "587b246c0584c90d37096ff2862d19512b0e689c9abb69085d91ad5479c72bdf"
}
],
"inventory": {
@@ -1476,10 +1476,10 @@
{
"id": "78900d8758bc",
"name": "DeepResearcher",
- "version": "1.0.60",
+ "version": "1.0.61",
"icon": "search",
"color": "sky",
- "updated_at": "2026-08-21T09:33:00.000Z",
+ "updated_at": "2026-08-29T05:04:02.000Z",
"skill_list": [
"6743aa0797a2",
"9be6fda271a5",
@@ -1746,8 +1746,8 @@
{
"id": "ee99fbb42964",
"name": "deep-research",
- "version": "1.0.49",
- "updated_at": "2026-08-23T09:48:36.000Z"
+ "version": "1.0.50",
+ "updated_at": "2026-08-27T22:10:00.000Z"
},
{
"id": "f283632103ba",
diff --git a/resources/builtin/marketplace/agents/78900d8758bc/agent.json b/resources/builtin/marketplace/agents/78900d8758bc/agent.json
index e91a1a06..e0750078 100644
--- a/resources/builtin/marketplace/agents/78900d8758bc/agent.json
+++ b/resources/builtin/marketplace/agents/78900d8758bc/agent.json
@@ -1,6 +1,6 @@
{
"agent_id": "78900d8758bc",
- "version": "1.0.60",
+ "version": "1.0.61",
"name": "DeepResearcher",
"description_zh": "复杂主题的证据型深度研究:拆解问题、规划研究路径、检索网页与学术来源、整理用户材料、压缩证据、核验引用与来源质量,输出带置信度、矛盾点、限制说明和参考来源的可复核研究报告;适合\"深度研究这个主题\"\"做一份带引用的行业/文献综述\"\"核验这些说法有没有可靠出处\";触发词:深度研究、证据分析、文献综述、趋势报告、行业研究、来源核验、引用核验、研究计划",
"description_en": "Evidence-grounded deep research for complex topics: decomposes questions, plans the research path, searches web and scholarly sources, organizes user-provided materials, compresses evidence, checks citation and source quality, and delivers auditable reports with confidence, contradictions, limitations, and references; For: \"research this topic in depth\", \"prepare a cited industry or literature review\", \"check whether these claims have reliable sources\"; Triggers: deep research, evidence analysis, literature review, trend report, industry research, source verification, citation check, research plan",
@@ -9,7 +9,7 @@
"Append-only ledgers account for every attempted research call without unrecorded retries or refetches; saved caps are enforced whenever a user, cost, task, or resume budget applies.",
"Every delivered claim and comparison cell aligns with its own cited evidence; unsupported content is repaired, narrowed, removed, or marked Not verified.",
"Recommend only from verified choice-changing facts; unresolved choice-changing gaps make a candidate conditional and the result partial, never complete.",
- "The handoff links a validated RESEARCH-REPORT.md containing retained evidence, limitations, run status, named gaps, and a decision-useful next step."
+ "The handoff links a validated topic-named RESEARCH-<topic>.md containing retained evidence, limitations, run status, named gaps, and a decision-useful next step."
],
"workflow": "### 1. Scope\n- Read `deep-research` as the governing Skill. Choose its normal, durable-resume, or compact path and load a supplemental Skill only when that evidence domain is actually required.\n- Ask only when the answer materially changes scope, cost, risk, audience, or deliverable; otherwise state bounded assumptions.\n\n### 2. Preserve State\n- Initialize durable ledgers and any applicable user, cost, task, or resume caps once, or resume only unfinished subquestions from saved state. Batch independent work and honor every recorded limit.\n\n### 3. Gather\n- Collect only decision-changing primary evidence. Preserve exact quotes, dates, limitations, contradictions, confidence, and failed-source gaps; continue while distinct sources add decision value, and stop on sufficient evidence, repeated no-gain strategies, or an applicable cap.\n\n### 4. Verify\n- Build narrow candidate-local claims, then judge recommendations from verifier-supported facts. Resolve only worthwhile choice-changing gaps; otherwise deliver a conditional partial.\n\n### 5. Deliver\n- Assemble the canonical report from clean verifier output, account when a cap applies, publish once, and hand over the report with findings, limitations, run status, named gaps, and the decision-useful next step.",
"tool_list": ["workspace.read", "workspace.write.output", "workspace.execute.command", "web"],
@@ -42,6 +42,6 @@
"icon": "search",
"color": "sky",
"created_at": "2026-06-04T18:10:00",
- "updated_at": "2026-08-21T09:33:00.000Z",
+ "updated_at": "2026-08-29T05:04:02.000Z",
"category": "data"
}
diff --git a/resources/builtin/marketplace/skills/ee99fbb42964/SKILL.md b/resources/builtin/marketplace/skills/ee99fbb42964/SKILL.md
index 6af57ad2..4536c411 100644
--- a/resources/builtin/marketplace/skills/ee99fbb42964/SKILL.md
+++ b/resources/builtin/marketplace/skills/ee99fbb42964/SKILL.md
@@ -116,11 +116,14 @@ bounded result.
On the compact path, after the final fetch batch emit the final fetch-ledger
write, field-tagged evidence-ledger write, compact citations-input write, and
-canonical citations command with `--report-out RESEARCH-REPORT.md` as ordered
-calls in one model response. The verifier builds the report from that compact
-state; do not transform ledgers, read its full audit, or assemble the report
-with shell code. Then emit the final plan update and publication together; add
-final caps accounting only when a user, cost, resume, or task budget applies.
+canonical citations command with `--report-out RESEARCH-<topic>.md` as ordered
+calls in one model response. `<topic>` is a short slug of this research
+question; never reuse a report filename that already exists in the workspace,
+because a later research run is a new report, not a revision of an earlier one.
+The verifier builds the report from that compact state; do not transform
+ledgers, read its full audit, or assemble the report with shell code. Then
+emit the final plan update and publication together; add final caps
+accounting only when a user, cost, resume, or task budget applies.
On other paths, keep the equivalent known writes and deterministic command
batched.
diff --git a/resources/builtin/marketplace/skills/ee99fbb42964/_meta.json b/resources/builtin/marketplace/skills/ee99fbb42964/_meta.json
index fce53689..28395734 100644
--- a/resources/builtin/marketplace/skills/ee99fbb42964/_meta.json
+++ b/resources/builtin/marketplace/skills/ee99fbb42964/_meta.json
@@ -1,6 +1,6 @@
{
- "version": "1.0.49",
- "updated_at": "2026-08-23T09:48:36.000Z",
+ "version": "1.0.50",
+ "updated_at": "2026-08-27T22:10:00.000Z",
"category": "data",
"reseed_if_deleted_before": "2026-07-27T12:00:00Z"
}
diff --git a/resources/builtin/marketplace/skills/ee99fbb42964/references/compact-landscape.md b/resources/builtin/marketplace/skills/ee99fbb42964/references/compact-landscape.md
index ccb22f16..85c91ed1 100644
--- a/resources/builtin/marketplace/skills/ee99fbb42964/references/compact-landscape.md
+++ b/resources/builtin/marketplace/skills/ee99fbb42964/references/compact-landscape.md
@@ -24,7 +24,7 @@ omits one:
4. Keep newly written unchanged plan and ledger state in memory; do not reread it
merely to continue the next known step.
5. Persist exact evidence, run `citations --op verify`, assemble and validate
- `RESEARCH-REPORT.md`, then publish it.
+ `RESEARCH-<topic>.md`, then publish it.
6. Make one final plan-status update after verified assembly. Prefer a batched
update when several statuses are already known, but one isolated update stays
valid and work never waits merely to form a batch.
diff --git a/resources/builtin/marketplace/skills/ee99fbb42964/references/operations-and-report.md b/resources/builtin/marketplace/skills/ee99fbb42964/references/operations-and-report.md
index 0b6d5b96..716592f6 100644
--- a/resources/builtin/marketplace/skills/ee99fbb42964/references/operations-and-report.md
+++ b/resources/builtin/marketplace/skills/ee99fbb42964/references/operations-and-report.md
@@ -81,7 +81,7 @@ retained comparison cells; when evidence does not support a field, expose the
gap instead of manufacturing another claim. Audit every canonical comparison
column before running citations.
-On the compact landscape path, let the verifier write `RESEARCH-REPORT.md`
+On the compact landscape path, let the verifier write `RESEARCH-<topic>.md`
directly from the field-tagged evidence ledger and compact candidate profiles.
Do not read `citations_output.json`, author another recommendation list or
comparison table, reconstruct fields from memory, or use shell code to assemble
@@ -168,9 +168,14 @@ rewrite the payload merely to remove non-material warnings.
Generate the compact verified report once with:
```bash
-"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" deep-research citations -- --op verify --input citations_input.json --out citations_output.json --report-out RESEARCH-REPORT.md
+"$ORKAS_NODE" "$ORKAS_PC_DIR/bin/run-skill.cjs" deep-research citations -- --op verify --input citations_input.json --out citations_output.json --report-out RESEARCH-<topic>.md
```
+Replace `<topic>` with a short slug of this research question, so the report
+carries a name a reader can recognise in the file list. The command refuses an
+existing target: a second research run in the same conversation is a new report,
+not a revision of the earlier one, and must never overwrite it.
+
The report contains the supplied title and boundary, then evidence-informed
model-selected paths with complete or partial factual coverage, the only
systematic comparison table, and the final Evidence used section. Do not
diff --git a/resources/builtin/marketplace/skills/ee99fbb42964/scripts/citations.py b/resources/builtin/marketplace/skills/ee99fbb42964/scripts/citations.py
index 7fd1956f..a3b0c2a6 100644
--- a/resources/builtin/marketplace/skills/ee99fbb42964/scripts/citations.py
+++ b/resources/builtin/marketplace/skills/ee99fbb42964/scripts/citations.py
@@ -1412,6 +1412,19 @@ def _load(path):
return json.loads(raw)
+def _write_new_report(report_path: str, report_markdown: str) -> None:
+ """Create one report atomically; never replace an earlier deliverable."""
+ try:
+ with open(report_path, "x", encoding="utf-8") as fh:
+ fh.write(report_markdown)
+ except FileExistsError:
+ raise ValueError(
+ "--report-out target already exists: {}. Pass a topic-specific "
+ "RESEARCH-<topic>.md name that does not exist yet; a previous "
+ "report is never overwritten.".format(report_path)
+ ) from None
+
+
def main(argv):
ap = argparse.ArgumentParser(prog="deep-research/citations")
ap.add_argument("--op", choices=["verify", "references"], default="verify")
@@ -1445,8 +1458,10 @@ def main(argv):
if value:
parts.append(value)
report_markdown = "\n\n".join(parts) + "\n"
- with open(args.report_out, "w", encoding="utf-8") as fh:
- fh.write(report_markdown)
+ # A later research run in the same workspace is a new report, not a
+ # revision of the earlier one. Exclusive creation makes that guarantee
+ # atomic even when two same-topic runs finish concurrently.
+ _write_new_report(args.report_out, report_markdown)
data["report"] = {
"path": args.report_out,
"characters": len(report_markdown),
diff --git a/resources/builtin/marketplace/skills/ee99fbb42964/test/test_citations.py b/resources/builtin/marketplace/skills/ee99fbb42964/test/test_citations.py
index 09e75ff3..231d2f05 100644
--- a/resources/builtin/marketplace/skills/ee99fbb42964/test/test_citations.py
+++ b/resources/builtin/marketplace/skills/ee99fbb42964/test/test_citations.py
@@ -404,6 +404,31 @@ class CompactLandscapeInput(unittest.TestCase):
0,
)
+ # A later research run is a new report, not a revision: rerunning
+ # onto an existing target must fail instead of truncating it.
+ with mock.patch.dict(
+ os.environ,
+ {"ORKAS_DEEP_RESEARCH_EVIDENCE_FILE": snapshot_path},
+ ):
+ with self.assertRaises(ValueError) as caught:
+ citations.main([
+ "--op", "verify",
+ "--input", input_path,
+ "--out", output_path,
+ "--report-out", report_path,
+ ])
+ self.assertIn("already exists", str(caught.exception))
+ with open(report_path, encoding="utf-8") as fh:
+ self.assertEqual(fh.read(), report)
+
+ # The no-overwrite contract must be one filesystem operation, not
+ # exists()+write(), or concurrent runs can both pass the probe.
+ with mock.patch("builtins.open", mock.mock_open()) as report_open:
+ citations._write_new_report("RESEARCH-atomic.md", "# report\n")
+ report_open.assert_called_once_with(
+ "RESEARCH-atomic.md", "x", encoding="utf-8"
+ )
+
stdout = _cli_stdout(result, [
"--input", input_path,
"--out", output_path,
diff --git a/resources/builtin/system/skills/agent-creator/SKILL.md b/resources/builtin/system/skills/agent-creator/SKILL.md
index ba948129..2e580008 100644
--- a/resources/builtin/system/skills/agent-creator/SKILL.md
+++ b/resources/builtin/system/skills/agent-creator/SKILL.md
@@ -13,7 +13,7 @@ Create or edit a custom Agent by emitting one inline `<agent>...</agent>` contai
The root file is the execution gate. Before emitting a container, read the matching reference through this Skill's read ref:
- New LLM-managed Agent, or an edit to its name, icon, description, workflow, guidance, Skills, tools, inputs, interaction mode, or category → [llm-agent-fields.md](references/llm-agent-fields.md).
-- Creation from supplied files/prompts/specs, conversation crystallization, similarity checking, or an unbound edit of an existing Agent → also read [source-and-editing.md](references/source-and-editing.md).
+- Creation from supplied files/prompts/specs, conversation crystallization, or an unbound edit of an existing Agent → also read [source-and-editing.md](references/source-and-editing.md). Current-turn requirements for inputs, checks, workflow, outputs, or non-goals count as a supplied spec, so this reference is required.
- CLI-backed Agent edit or a request about its external runtime boundary → read [cli-and-prose.md](references/cli-and-prose.md).
Do not read unrelated references. A simple bound edit normally needs only `llm-agent-fields.md`; a CLI-backed edit normally needs only `cli-and-prose.md`.
@@ -21,10 +21,10 @@ Do not read unrelated references. A simple bound edit normally needs only `llm-a
## Non-negotiable protocol
- **Mutation only via the inline container.** Never use `edit_file`, `write_file`, or `bash` to change `agent.json`. Never dump the container into a workspace file.
-- **No container, no mutation, no success claim.** An Agent exists or changes only after this reply contains a valid container for that Agent and the host applies it. Without one, describe the result only as a proposal, clarification, or blocker; never say the Agent is ready, created, updated, installed, or available.
+- **No container, no mutation, no success claim.** Without a valid container, describe the result only as a proposal, clarification, or blocker; never say the Agent is ready, created, updated, installed, or available. A valid container only requests a mutation; only the host result proves it was applied. Until then, use pending wording such as “将创建” or “已提交,等待应用”.
- **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.
-- **Preserve source material.** If the user supplied a prompt, spec, examples, files, or an Agent directory, read the relevant source before authoring and preserve its role, goals, workflow order, tool rules, outputs, examples, safety rules, and stop points. For an attachment path, 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. Adapt only what Orkas requires unless the user requests a rewrite.
+- **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.
- **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.
@@ -51,7 +51,7 @@ For a new Agent, first compare its name and its typical objects/actions with the
3. Read any required current Agent spec or user-supplied source.
4. Validate the intended fields, category, capability dependencies, interaction shape, and safety boundary.
5. Emit concise user-facing prose plus the smallest valid patch container. On create, include every required creation field. On edit, omit unchanged fields; list-like fields replace the entire list when present.
-6. Stop. The host applies the container and supplies persistence evidence.
+6. Stop after emitting the container; the host supplies persistence evidence.
## Safety gate
diff --git a/resources/builtin/system/skills/agent-creator/references/cli-and-prose.md b/resources/builtin/system/skills/agent-creator/references/cli-and-prose.md
index 608d1c45..8699493a 100644
--- a/resources/builtin/system/skills/agent-creator/references/cli-and-prose.md
+++ b/resources/builtin/system/skills/agent-creator/references/cli-and-prose.md
@@ -19,7 +19,6 @@ The host hides the container. The prose outside it is what the user sees.
- Describe concepts rather than implementation fields: say “what it asks before running”, “what capabilities it uses”, “the steps it follows”, or “it now runs autonomously”.
- Do not expose XML tags, field names, schema/config terminology, ids, internal source mechanics, or data-structure jargon.
- For CLI-backed Agents, do not mention the selected CLI, vendor, or model in success prose.
-- Claim success only when a valid container is present for the exact Agent. Otherwise call the response a proposal, clarification, or blocker.
Example:
diff --git a/resources/builtin/system/skills/agent-creator/references/source-and-editing.md b/resources/builtin/system/skills/agent-creator/references/source-and-editing.md
index 6cf90665..edb57eee 100644
--- a/resources/builtin/system/skills/agent-creator/references/source-and-editing.md
+++ b/resources/builtin/system/skills/agent-creator/references/source-and-editing.md
@@ -1,19 +1,12 @@
# Source-backed creation and editing
-Read this file when source material or conversation history defines the Agent, when checking similarity for a new Agent, or when editing an existing Agent from an unbound Commander session.
-
-## Pre-create similarity check
-
-Before creating, compare the proposed name and its typical objects/actions with the injected Agent index.
-
-- If an existing entry overlaps, emit no container. Name the existing Agent in one current-language paragraph, explain the overlap, and ask whether to use it or still create a new one.
-- If none overlaps, create in the same turn without a pre-announcement.
+Read this file when source material or conversation history defines the Agent, or when editing an existing Agent from an unbound Commander session.
## Source-preservation contract
Source includes current-turn attachments or referenced files, pasted prompts, `agent.json`, YAML/JSON specs, README/workflow documents, examples, or Agent directories.
-1. Read the source first. A filename plus a short request is not enough. For an injected attachment path, call `read_files` with that exact path in `paths`; ask for another upload only if the read fails.
+1. Read the source first. A filename plus a short request is not enough; for an injected path, apply the root attachment-source gate.
2. Preserve the core prompt: role/persona, objective, boundaries, step order, tool rules, examples, output format, evaluation checks, and safety/confirmation points.
3. Adapt format rather than substance. Map content into Orkas display, workflow, guidance, capability dependency, input, interaction, and category fields.
4. Treat an `agent_id` found in exported or supplied source as provenance, not mutation intent. For import-as-new, copy, or create-from-source requests, never copy or emit that source ID. Follow the mutation controls in `llm-agent-fields.md`; only an explicit unbound edit resolved from the current index and spec emits the canonical current id.
diff --git a/resources/builtin/system/skills/memory-manager/SKILL.md b/resources/builtin/system/skills/memory-manager/SKILL.md
index 417f6ec1..5fa2c998 100644
--- a/resources/builtin/system/skills/memory-manager/SKILL.md
+++ b/resources/builtin/system/skills/memory-manager/SKILL.md
@@ -1,7 +1,7 @@
---
name: memory-manager
-description_zh: "添加、替换或删除持久的 Commander、用户、共享或项目记忆及项目指令;用于“记住这个”、长期偏好、持久决策、项目规则,以及遗忘或更新请求,不用于只读询问已提供的上下文。"
-description_en: "Add, replace, or remove durable Commander, user, shared, or project memories and project instructions. Use for “remember this,” standing preferences, durable decisions, project rules, and forget or update requests; not for read-only questions about context already supplied."
+description_zh: "当用户要求让信息、偏好、决定或规则在未来对话持续生效,或要求更新、纠正、遗忘这些持久信息时,先读取本 Skill,再通过实际工具完成添加、替换或删除;覆盖 Commander、用户、共享、项目记忆及项目指令。不用于只读回忆或保存普通文件。"
+description_en: "Read this Skill before “remember this” or any request to preserve facts, preferences, decisions, or rules across future conversations, or correct/forget durable state. It governs mutations to Commander, user, shared, and project memory/instructions; exclude read-only recall and ordinary file saving."
---
# memory-manager
diff --git a/resources/builtin/system/skills/skill-creator/SKILL.md b/resources/builtin/system/skills/skill-creator/SKILL.md
index b0630ea6..e2f60b48 100644
--- a/resources/builtin/system/skills/skill-creator/SKILL.md
+++ b/resources/builtin/system/skills/skill-creator/SKILL.md
@@ -21,20 +21,18 @@ Do not read unrelated references. A category-only edit needs only `metadata.md`;
## Routing gate
-**Explicit creation intent required.** Use this Skill only when the user explicitly asks to create, edit, convert into, or import a Skill, or when already inside a bound Skill editor. Do **not** consult this skill for a plain "install this URL / install this GitHub repo / add this project" request. A runnable external package belongs to `package-installer` unless the user explicitly wants a portable custom Skill.
+**Explicit creation intent required.** Use this Skill only when the user explicitly asks to create, edit, convert into, or import a Skill, or when already inside a bound Skill editor. Do **not** consult this skill for a plain "install this URL / install this GitHub repo / add this project" request. A runnable external package belongs to `package-installer` unless the user explicitly wants a portable custom Skill. If that outcome is genuinely ambiguous, ask one concise clarification.
## Non-negotiable protocol
- **Use host-owned mutation paths only.** Use `import_skill_package` for an explicitly supplied local Skill directory/ZIP when available, metadata tags for metadata-only changes, and `<<<skill-file>>>` for changed file content. Never use `edit_file`, `write_file`, or shell redirects under the Skill directory.
- **Whole-file replacement.** Every `<<<skill-file>>>` block replaces one complete relative file. Read an existing file before changing it; a partial body erases omitted content.
+- **Protocol completeness beats prose depth.** Close every file block with `>>>` on its own line and close the outer `</skill>` before optional user-visible prose. If response space is tight, shorten the Skill body; never truncate or omit a protocol delimiter.
- **No protocol files.** Do not dump `<skill>`, `<skill-meta>`, or file blocks into the workspace. The host parses them inline.
-- **Explicit creation intent.** A URL, README, or tool document alone does not authorize Skill creation. Ask one concise clarification when intent is genuinely ambiguous.
- **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.
-- **Preserve source material.** Read relevant source contents before authoring; a filename plus a short request is not enough. For an existing Skill, preserve its body, scripts, references, examples, filenames, layout, and behavior unless an Orkas compatibility change is required or the user asks for a rewrite.
-- **Bundled scripts use the standard Skill Runner.** Never expose or construct an installation path or depend on the caller's working directory.
- **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.
-- **No silent defaults or residue.** Validate category and audit imported files before claiming success.
+- **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. If visible prose is useful, use pending wording such as “将创建” or “已提交,等待应用”.
## Decide create versus edit
@@ -96,9 +94,9 @@ description: compact current-language routing description
1. Confirm explicit Skill intent and classify create, edit, or import.
2. Read only the references required by the routing table.
3. Read the current Skill and any user-supplied source material.
-4. Preserve source or design the smallest self-contained capability; choose guide versus script deliberately.
+4. Preserve source or design the smallest self-contained capability; choose guide versus script deliberately. For a straightforward guide, prefer the required use/non-use boundary, preconditions, 3–7 steps, and output shape over a long tutorial or repeated examples.
5. Validate metadata, category, runner commands, safety, relative links, and the final resource inventory.
-6. Emit only the minimal metadata tags and complete changed files, followed by concise user-facing status when the surface allows it.
+6. Emit only the minimal metadata tags and complete changed files, then stop for the host result.
## Safety gate
@@ -106,4 +104,4 @@ Do not author credential-store reads, dynamic or decoded execution, download-and
## User-visible prose
-State only what the Skill now does, when it is used, which meaningful files changed, and any required next step. Do not expose protocol tags, frontmatter mechanics, internal modes, ids, or design jargon. Do **not** show source provenance by default. Mention it only when asked or when a failed read/import needs repair. Never claim completion after a failed or omitted mutation.
+State only what the Skill now does, when it is used, which meaningful files changed, and any required next step. Do not expose protocol tags, frontmatter mechanics, internal modes, ids, or design jargon. Do **not** show source provenance by default. Mention it only when asked or when a failed read/import needs repair.
diff --git a/resources/builtin/system/skills/skill-creator/references/authoring.md b/resources/builtin/system/skills/skill-creator/references/authoring.md
index fa11a646..45bc92d1 100644
--- a/resources/builtin/system/skills/skill-creator/references/authoring.md
+++ b/resources/builtin/system/skills/skill-creator/references/authoring.md
@@ -12,6 +12,7 @@ A Skill is an independent reusable capability, not a tutorial or an Agent.
- Prefer a guide using existing tools. Add a script only for deterministic repeated logic or a real integration boundary.
- Keep the root SKILL.md as the routing and common execution spine. Move conditional variants, long schemas, detailed examples, and deep domain material into one-level `references/` files. In the root, retain only each branch's discriminator/read condition; do not repeat branch checklists, branch schemas, or empty branch templates there.
- Aim to keep a newly authored root comfortably below 12,000 characters. This is a context budget, not a reason to omit required safety or execution rules; move conditional depth rather than compressing it into ambiguity.
+- A straightforward single-path guide should be much shorter than that ceiling. Do not expand a compact request into a tutorial: cover the required boundaries, preconditions, 3–7 execution steps, and output shape once, then stop.
## Design workflow
diff --git a/src/core-agent/src/agent/runner.ts b/src/core-agent/src/agent/runner.ts
index 7389a518..c36fbbe5 100644
--- a/src/core-agent/src/agent/runner.ts
+++ b/src/core-agent/src/agent/runner.ts
@@ -2067,6 +2067,54 @@ export class AgentRunner {
// Check for tool use
const toolCalls = result.content.filter((c) => c.type === "tool_use");
+ // A user can steer while the provider is deciding which tools to run.
+ // Reconcile that newer instruction before any proposed side effect,
+ // not only after the whole tool batch has already executed. The
+ // assistant tool_use blocks are already committed, so pair each with a
+ // synthetic skipped result before appending the steer and re-running
+ // inference; this preserves provider protocol without executing stale
+ // work.
+ if (toolCalls.length > 0) {
+ const preExecutionSteer = await this.drainSteer(params);
+ if (this.hasUnappliedSteer(preExecutionSteer, appliedSteerIds)) {
+ const skipped = "Tool call skipped because a newer user instruction arrived before execution.";
+ for (const call of toolCalls as ReadonlyArray<ToolUseCall>) {
+ yield { type: "tool_start", id: call.id, name: call.name, input: call.input };
+ this.session.withContextMutationBatch(() => {
+ this.session.addToolResult(call.id, skipped, undefined, true);
+ recordCompletedToolWork(
+ this.session,
+ call,
+ { content: skipped, isError: true },
+ "skipped",
+ compactionCount,
+ );
+ });
+ yield {
+ type: "tool_end",
+ id: call.id,
+ name: call.name,
+ result: skipped,
+ isError: true,
+ durationMs: 0,
+ };
+ }
+ toolBoundarySynthesisPending = false;
+ await this.appendSteerMessages(preExecutionSteer, false, appliedSteerIds);
+ log.info("interrupt-steer: skipped stale proposed tool calls before execution", {
+ toolCalls: toolCalls.length,
+ });
+ attempt = -1;
+ continue;
+ }
+ // An acknowledgement may have failed after the structured message
+ // was already accepted on an earlier boundary. Retry only the ACK;
+ // do not suppress this tool batch or duplicate the user message.
+ if (preExecutionSteer.length > 0) {
+ await this.appendSteerMessages(preExecutionSteer, false, appliedSteerIds);
+ }
+ }
+
// Tools were intentionally withheld for a boundary synthesis. A
// provider/model that nevertheless emits a tool call must never regain
// side effects or turn this one-shot explanation into another loop.
diff --git a/src/core-agent/src/agent/session.ts b/src/core-agent/src/agent/session.ts
index 8dc5778b..6cea268d 100644
--- a/src/core-agent/src/agent/session.ts
+++ b/src/core-agent/src/agent/session.ts
@@ -2102,12 +2102,20 @@ export class Session {
const objectiveNote = plan.objectiveTruncated || objective !== plan.objective
? " (bounded deterministic excerpts; raw user messages remain canonical)"
: " (deterministically anchored from user instructions)";
- const latestUserDigest = this.latestUserTextInActiveTurn()?.digest;
+ const latestUser = this.latestUserTextInActiveTurn();
+ const latestUserDigest = latestUser?.digest;
const needsReconciliation = plan.updatedTurnId !== activeTurnId
|| !plan.updatedUserMessageDigest
|| plan.updatedUserMessageDigest !== latestUserDigest;
const lines = [
"[Execution plan anchor — authoritative runtime state, not a summary]",
+ ...(needsReconciliation && latestUser
+ ? [
+ "Latest user instruction — authoritative; replaces conflicting earlier requirements:",
+ truncateMiddle(latestUser.text, EXECUTION_PLAN_MAX_ANCHOR_OBJECTIVE_CHARS),
+ "The prior objective and steps below are stale until reconciled; retain only non-conflicting requirements.",
+ ]
+ : []),
`Objective${objectiveNote}:`,
objective,
`Revision: ${plan.revision}`,
diff --git a/src/core-agent/src/providers/pi-provider.ts b/src/core-agent/src/providers/pi-provider.ts
index 9d1724f8..148f84c0 100644
--- a/src/core-agent/src/providers/pi-provider.ts
+++ b/src/core-agent/src/providers/pi-provider.ts
@@ -374,12 +374,93 @@ function mapUsage(u: PiAssistantMessage["usage"]): Usage {
};
}
+type MapContentOptions = {
+ stripLeadingThinkText?: boolean;
+};
+
+type LeadingThinkTextFilter = {
+ push(text: string): string;
+ finish(): string;
+};
+
+const LEADING_THINK_OPEN = "<think>";
+const LEADING_THINK_CLOSE = "</think>";
+
+/**
+ * Some user-configured OpenAI-compatible endpoints serialize private
+ * reasoning as a literal leading `<think>...</think>` text block instead of
+ * the protocol's structured reasoning field. Hold only the ambiguous prefix
+ * while streaming, suppress each block in a consecutive leading sequence,
+ * and pass every non-leading lookalike through unchanged.
+ */
+function createLeadingThinkTextFilter(): LeadingThinkTextFilter {
+ let state: "detect" | "suppress" | "pass" = "detect";
+ let pending = "";
+ let suppressedLeadingBlock = false;
+
+ return {
+ push(text: string): string {
+ if (!text) return "";
+ if (state === "pass") return text;
+ pending += text;
+
+ while (true) {
+ if (state === "detect") {
+ const candidate = pending.replace(/^\s+/, "");
+ if (!candidate || LEADING_THINK_OPEN.startsWith(candidate)) return "";
+ if (!candidate.startsWith(LEADING_THINK_OPEN)) {
+ state = "pass";
+ const visible = suppressedLeadingBlock ? candidate : pending;
+ pending = "";
+ return visible;
+ }
+ state = "suppress";
+ pending = candidate.slice(LEADING_THINK_OPEN.length);
+ }
+
+ if (state === "suppress") {
+ const closeIndex = pending.indexOf(LEADING_THINK_CLOSE);
+ if (closeIndex < 0) {
+ pending = pending.slice(-(LEADING_THINK_CLOSE.length - 1));
+ return "";
+ }
+ pending = pending.slice(closeIndex + LEADING_THINK_CLOSE.length);
+ suppressedLeadingBlock = true;
+ state = "detect";
+ }
+ }
+ },
+
+ finish(): string {
+ const visible = state === "detect"
+ ? (suppressedLeadingBlock ? pending.replace(/^\s+/, "") : pending)
+ : "";
+ pending = "";
+ state = "pass";
+ return visible;
+ },
+ };
+}
+
+function stripLeadingThinkText(text: string): string {
+ const filter = createLeadingThinkTextFilter();
+ return filter.push(text) + filter.finish();
+}
+
/** Convert pi-ai AssistantMessage content to our MessageContent[]. */
-function mapContent(content: PiAssistantMessage["content"]): MessageContent[] {
+function mapContent(
+ content: PiAssistantMessage["content"],
+ options: MapContentOptions = {},
+): MessageContent[] {
const result: MessageContent[] = [];
+ let atTextStart = options.stripLeadingThinkText === true;
for (const block of content) {
if (block.type === "text") {
- result.push({ type: "text", text: block.text });
+ const text = atTextStart ? stripLeadingThinkText(block.text) : block.text;
+ if (text) {
+ result.push({ type: "text", text });
+ atTextStart = false;
+ }
} else if (block.type === "toolCall") {
result.push({
type: "tool_use",
@@ -405,10 +486,16 @@ function mapContent(content: PiAssistantMessage["content"]): MessageContent[] {
return result;
}
-export function mapContentForTest(content: PiAssistantMessage["content"]): MessageContent[] {
- return mapContent(content);
+export function mapContentForTest(
+ content: PiAssistantMessage["content"],
+ options: MapContentOptions = {},
+): MessageContent[] {
+ return mapContent(content, options);
}
+export const createLeadingThinkTextFilterForTest = createLeadingThinkTextFilter;
+export const stripLeadingThinkTextForTest = stripLeadingThinkText;
+
const REASONING_LEVELS = ["minimal", "low", "medium", "high"] as const;
type PiReasoningLevel = typeof REASONING_LEVELS[number];
@@ -470,6 +557,7 @@ export function createPiProvider(config: {
supportedReasoning?: ReadonlyArray<"minimal" | "low" | "medium" | "high">;
}): LLMProvider {
const providerId = config.provider as KnownProvider;
+ const shouldStripLeadingThinkText = config.provider === "custom";
// Resolve the model object. `customModel` shortcuts pi-ai's catalog
// lookup for providers pi-ai doesn't know about.
@@ -552,7 +640,9 @@ export function createPiProvider(config: {
}
return {
- content: mapContent(result.content),
+ content: mapContent(result.content, {
+ stripLeadingThinkText: shouldStripLeadingThinkText,
+ }),
stopReason: mapStopReason(result.stopReason),
usage: mapUsage(result.usage),
model: resolvedResponseModel(result, model.id),
@@ -574,6 +664,9 @@ export function createPiProvider(config: {
log.debug(`stream ${providerId}/${model.id}`);
try {
+ const leadingThinkFilter = shouldStripLeadingThinkText
+ ? createLeadingThinkTextFilter()
+ : null;
const eventStream = reasoning
? piStreamSimple(model, context, {
apiKey: config.apiKey,
@@ -603,9 +696,16 @@ export function createPiProvider(config: {
yield { type: "message_start" };
break;
case "text_delta":
- yield { type: "text_delta", text: event.delta };
+ {
+ const text = leadingThinkFilter?.push(event.delta) ?? event.delta;
+ if (text) yield { type: "text_delta", text };
+ }
break;
case "toolcall_start":
+ {
+ const text = leadingThinkFilter?.finish() ?? "";
+ if (text) yield { type: "text_delta", text };
+ }
yield {
type: "tool_use_start",
id: event.partial.content[event.contentIndex]?.type === "toolCall"
@@ -623,12 +723,18 @@ export function createPiProvider(config: {
yield { type: "tool_use_end", id: event.toolCall.id };
break;
case "done":
+ {
+ const text = leadingThinkFilter?.finish() ?? "";
+ if (text) yield { type: "text_delta", text };
+ }
const serverFallbackReason = serverFallbackReasonFromResponseId(event.message.responseId);
yield {
type: "message_end",
stopReason: mapStopReason(event.reason),
usage: mapUsage(event.message.usage),
- content: mapContent(event.message.content),
+ content: mapContent(event.message.content, {
+ stripLeadingThinkText: shouldStripLeadingThinkText,
+ }),
model: resolvedResponseModel(event.message, model.id),
...(serverFallbackReason ? { serverFallbackReason } : {}),
providerTermination: {
@@ -640,6 +746,10 @@ export function createPiProvider(config: {
};
break;
case "error":
+ {
+ const text = leadingThinkFilter?.finish() ?? "";
+ if (text) yield { type: "text_delta", text };
+ }
const errorServerFallbackReason = serverFallbackReasonFromResponseId(event.error.responseId);
const responseModel = resolvedResponseModel(event.error, model.id);
// Surface everything we can from the stream error event.
diff --git a/src/core-agent/test/agent-runner.test.ts b/src/core-agent/test/agent-runner.test.ts
index a342d720..52e58e94 100644
--- a/src/core-agent/test/agent-runner.test.ts
+++ b/src/core-agent/test/agent-runner.test.ts
@@ -6840,10 +6840,10 @@ describe("AgentRunner", () => {
expect(result.meta.error?.kind).not.toBe("context_overflow");
});
- it("interrupt-steer: folds drainSteer messages into the next LLM round", async () => {
- // round 1 calls a no-op tool → loop boundary → drainSteer yields a steer →
- // round 2 must see it as a user message; round 1 must NOT (folded only after
- // the tool round).
+ it("interrupt-steer: skips stale proposed tools before folding the newer instruction", async () => {
+ // A steer lands while round 1 is deciding to call a tool. The old proposal
+ // must receive a protocol-safe synthetic result without executing, and
+ // round 2 must see the newer user instruction.
const captured: Message[][] = [];
let streamCalls = 0;
const provider: LLMProvider = {
@@ -6854,16 +6854,23 @@ describe("AgentRunner", () => {
streamCalls++;
captured.push([...params.messages]);
if (streamCalls === 1) {
- const id = "c1";
+ const firstId = "c1";
+ const secondId = "c2";
yield { type: "message_start" as const };
- yield { type: "tool_use_start" as const, id, name: "noop" };
- yield { type: "tool_use_delta" as const, id, input: "{}" };
- yield { type: "tool_use_end" as const, id };
+ yield { type: "tool_use_start" as const, id: firstId, name: "noop" };
+ yield { type: "tool_use_delta" as const, id: firstId, input: "{}" };
+ yield { type: "tool_use_end" as const, id: firstId };
+ yield { type: "tool_use_start" as const, id: secondId, name: "noop" };
+ yield { type: "tool_use_delta" as const, id: secondId, input: "{}" };
+ yield { type: "tool_use_end" as const, id: secondId };
yield {
type: "message_end" as const,
stopReason: "tool_use" as const,
usage: { inputTokens: 5, outputTokens: 5, totalTokens: 10 },
- content: [{ type: "tool_use" as const, id, name: "noop", input: {} }],
+ content: [
+ { type: "tool_use" as const, id: firstId, name: "noop", input: {} },
+ { type: "tool_use" as const, id: secondId, name: "noop", input: {} },
+ ],
model: "mock-model",
};
} else {
@@ -6883,11 +6890,15 @@ describe("AgentRunner", () => {
const registry = new ProviderRegistry();
registry.registerFactory("mock", () => provider);
+ let executions = 0;
const noop = defineTool({
name: "noop",
description: "no-op",
inputSchema: { type: "object", properties: {} },
- async execute() { return { content: "ok" }; },
+ async execute() {
+ executions++;
+ return { content: "ok" };
+ },
});
const config = createConfig({ agent: { defaultProvider: "mock", defaultModel: "mock-model" } });
const runner = new AgentRunner({ config, providers: registry, tools: [noop] });
@@ -6908,7 +6919,14 @@ describe("AgentRunner", () => {
msgs.some((m) => m.role === "user"
&& m.content.some((c) => c.type === "text" && c.text.includes(STEER)));
expect(sawSteer(captured[1])).toBe(true); // round 2 sees the folded steer
- expect(sawSteer(captured[0])).toBe(false); // round 1 (pre-tool) does not
+ expect(sawSteer(captured[0])).toBe(false); // round 1 predates the steer
+ expect(executions).toBe(0);
+ const skippedResults = captured[1]
+ .flatMap((message) => message.content)
+ .filter((content) => content.type === "tool_result"
+ && content.content === "Tool call skipped because a newer user instruction arrived before execution.");
+ expect(skippedResults.map((content) => content.type === "tool_result" ? content.toolUseId : null))
+ .toEqual(["c1", "c2"]);
});
it("interrupt-steer: persists structured text, image, and resource context before acknowledging", async () => {
@@ -6951,11 +6969,15 @@ describe("AgentRunner", () => {
};
const registry = new ProviderRegistry();
registry.registerFactory("mock", () => provider);
+ let executions = 0;
const noop = defineTool({
name: "noop",
description: "no-op",
inputSchema: { type: "object", properties: {} },
- async execute() { return { content: "ok" }; },
+ async execute() {
+ executions++;
+ return { content: "ok" };
+ },
});
const config = createConfig({ agent: { defaultProvider: "mock", defaultModel: "mock-model" } });
const session = new Session();
@@ -6983,6 +7005,7 @@ describe("AgentRunner", () => {
expect(result.text).toBe("used rich update");
expect(streamCalls).toBe(2);
+ expect(executions).toBe(0);
expect(captured[0].some((message) => message.content.some((content) => content.type === "image")))
.toBe(false);
expect(captured[1]).toContainEqual(expect.objectContaining({
@@ -7202,7 +7225,7 @@ describe("AgentRunner", () => {
message: "do the task",
drainSteer: () => {
drainCalls++;
- return drainCalls === 2 ? [STEER] : [];
+ return drainCalls === 3 ? [STEER] : [];
},
});
@@ -7277,11 +7300,15 @@ describe("AgentRunner", () => {
const registry = new ProviderRegistry();
registry.registerFactory("mock", () => provider);
+ let executions = 0;
const noop = defineTool({
name: "noop",
description: "no-op",
inputSchema: { type: "object", properties: {} },
- async execute() { return { content: "ok" }; },
+ async execute() {
+ executions++;
+ return { content: "ok" };
+ },
});
const config = createConfig({ agent: { defaultProvider: "mock", defaultModel: "mock-model" } });
const runner = new AgentRunner({ config, providers: registry, tools: [noop] });
@@ -7289,6 +7316,7 @@ describe("AgentRunner", () => {
await runner.run({ message: "do the task", drainSteer: () => [] });
expect(streamCalls).toBe(2);
+ expect(executions).toBe(1);
// No steer is folded. The visible tool_result is not duplicated into the
// completed-work projection, so the only added user-text block is the
// deterministic execution objective anchor.
diff --git a/src/core-agent/test/providers.test.ts b/src/core-agent/test/providers.test.ts
index 00937692..ba1b2ab1 100644
--- a/src/core-agent/test/providers.test.ts
+++ b/src/core-agent/test/providers.test.ts
@@ -1,6 +1,15 @@
import { describe, it, expect } from "vitest";
import { ProviderRegistry } from "../src/providers/registry.js";
-import { createAnthropicProvider, createOpenAIProvider, createPiProvider, listPiProviders, listPiModels } from "../src/providers/pi-provider.js";
+import {
+ createAnthropicProvider,
+ createLeadingThinkTextFilterForTest,
+ createOpenAIProvider,
+ createPiProvider,
+ listPiProviders,
+ listPiModels,
+ mapContentForTest,
+ stripLeadingThinkTextForTest,
+} from "../src/providers/pi-provider.js";
import { createConfig } from "../src/config/loader.js";
describe("Providers (pi-ai backed)", () => {
@@ -45,6 +54,38 @@ describe("Providers (pi-ai backed)", () => {
expect(provider.id).toBe("google");
});
+ it("removes leading private think blocks from custom-provider content", () => {
+ const raw = "<think>private chain of thought</think>\n\nUser-facing result";
+ expect(mapContentForTest([{ type: "text", text: raw }], { stripLeadingThinkText: true }))
+ .toEqual([{ type: "text", text: "User-facing result" }]);
+ expect(mapContentForTest([{ type: "text", text: raw }]))
+ .toEqual([{ type: "text", text: raw }]);
+ });
+
+ it("suppresses consecutive leading think blocks split across deltas", () => {
+ expect(stripLeadingThinkTextForTest(
+ "<think>first</think>\n<think>second</think>\nVisible result",
+ )).toBe("Visible result");
+ const filter = createLeadingThinkTextFilterForTest();
+ expect(filter.push("<think>first</think>\n<th")).toBe("");
+ expect(filter.push("ink>second</thi")).toBe("");
+ expect(filter.push("nk>\nVisible result")).toBe("Visible result");
+ expect(filter.finish()).toBe("");
+ });
+
+ it("preserves non-leading and partial think-tag lookalikes", () => {
+ for (const text of [
+ "Answer with an inline <think> example",
+ "<thinker>visible element</thinker>",
+ "\n<thin",
+ ]) {
+ expect(stripLeadingThinkTextForTest(text)).toBe(text);
+ }
+ const afterBlock = createLeadingThinkTextFilterForTest();
+ expect(afterBlock.push("<think>private</think>\n<thin")).toBe("");
+ expect(afterBlock.finish()).toBe("<thin");
+ });
+
});
describe("listPiProviders / listPiModels", () => {
diff --git a/src/core-agent/test/session.test.ts b/src/core-agent/test/session.test.ts
index 540e308c..1f1b191e 100644
--- a/src/core-agent/test/session.test.ts
+++ b/src/core-agent/test/session.test.ts
@@ -1445,6 +1445,13 @@ describe("Session execution plan anchor", () => {
session.beginUserTurn([{ type: "text", text: "Actually switch to the replacement task" }]);
let view = JSON.stringify(session.getMessagesForModel());
expect(view).toContain("Reconciliation required");
+ const stalePlanTail = JSON.stringify(session.getMessagesForModel().at(-1));
+ expect(stalePlanTail).toContain(
+ "Latest user instruction — authoritative; replaces conflicting earlier requirements",
+ );
+ expect(stalePlanTail).toContain("Actually switch to the replacement task");
+ expect(stalePlanTail.indexOf("Actually switch to the replacement task"))
+ .toBeLessThan(stalePlanTail.indexOf("Objective"));
expect(session.getExecutionPlan()?.objective).toBe("Original task");
session.updateExecutionPlan({
@@ -1474,7 +1481,11 @@ describe("Session execution plan anchor", () => {
session.updateExecutionPlan({ steps: [{ step: "Work", status: "in_progress" }] });
session.addMessage("user", [{ type: "text", text: "Pause that and account for this new constraint" }]);
- expect(JSON.stringify(session.getMessagesForModel())).toContain("Reconciliation required");
+ const stalePlanTail = JSON.stringify(session.getMessagesForModel().at(-1));
+ expect(stalePlanTail).toContain("Reconciliation required");
+ expect(stalePlanTail).toContain("Pause that and account for this new constraint");
+ expect(stalePlanTail.indexOf("Pause that and account for this new constraint"))
+ .toBeLessThan(stalePlanTail.indexOf("Initial in-flight goal"));
session.updateExecutionPlan({ steps: [{ step: "Account for constraint", status: "in_progress" }] });
const view = JSON.stringify(session.getMessagesForModel());
diff --git a/src/main/features/group_chat/app_health.ts b/src/main/features/group_chat/app_health.ts
new file mode 100644
index 00000000..90c42cff
--- /dev/null
+++ b/src/main/features/group_chat/app_health.ts
@@ -0,0 +1,102 @@
+/**
+ * Read-only app-health probes for the Commander `app_health` tool.
+ *
+ * Every probe is side-effect free and sanitized: status kinds, counts, ids,
+ * and already-localized user-facing messages only — never credentials, base
+ * URLs, file paths, or free-form provider error text. The `tasks` probe is
+ * injected by the bus (its running-state maps live there) to avoid an import
+ * cycle. A probe failure degrades to an `unavailable` marker instead of
+ * failing the whole snapshot.
+ */
+
+import * as auth from '../auth';
+import * as connectorManager from '../connectors/manager';
+import { isConnectorRuntimeEnabled } from '../connectors/availability';
+import { isConnectorUsable } from '../connectors/types';
+import {
+ isConnectorEnabledFromSnapshot,
+ readEnabledMap,
+} from '../component_enabled';
+import * as kbVector from '../kb_vector';
+
+export type AppHealthDomain = 'model' | 'connectors' | 'kb' | 'tasks';
+export const APP_HEALTH_DOMAINS: readonly AppHealthDomain[] = ['model', 'connectors', 'kb', 'tasks'];
+
+export function isAppHealthDomain(value: string): value is AppHealthDomain {
+ return (APP_HEALTH_DOMAINS as readonly string[]).includes(value);
+}
+
+export interface AppHealthTasksProbe {
+ active_work: boolean;
+ active_conversation_count: number;
+ other_active_conversation_count: number;
+ current_conversation: {
+ processing: boolean;
+ in_flight_actor_count: number;
+ active_turn_count: number;
+ };
+}
+
+const CONNECTOR_ITEM_CAP = 20;
+
+async function modelProbe(): Promise<Record<string, unknown>> {
+ const configured = auth.hasConfiguredModel().configured;
+ const cfg = await auth.getConfig();
+ const cooldown = auth.getConfiguredModelCooldown();
+ return {
+ configured,
+ default_provider: cfg.provider || null,
+ default_model: cfg.model || null,
+ // `kind` is the bounded failure classification; the free-form reason and
+ // profile label are deliberately dropped.
+ credential_cooldown: cooldown
+ ? {
+ kind: String(cooldown.kind),
+ seconds_remaining: Math.max(0, Math.ceil((cooldown.cooledUntil - Date.now()) / 1000)),
+ }
+ : null,
+ // Already a localized, sanitized user-facing sentence (or null).
+ oauth_expired: auth.getConfiguredModelOAuthExpiredMessage(),
+ };
+}
+
+async function connectorsProbe(uid: string): Promise<Record<string, unknown>> {
+ const instances = connectorManager.listInstances(uid);
+ const enabledSnapshot = readEnabledMap(uid);
+ const items = instances.map((instance) => {
+ const enabled = isConnectorRuntimeEnabled(instance.id)
+ && isConnectorEnabledFromSnapshot(enabledSnapshot, instance.id);
+ return {
+ id: instance.id,
+ name: instance.display_name,
+ status: String(instance.status?.kind || 'unknown'),
+ enabled,
+ usable: enabled && isConnectorUsable(instance.status),
+ };
+ });
+ return {
+ configured_count: items.length,
+ connected_count: items.filter((item) => item.enabled && item.status === 'connected').length,
+ usable_count: items.filter((item) => item.usable).length,
+ items: items.slice(0, CONNECTOR_ITEM_CAP),
+ };
+}
+
+export async function collectAppHealth(
+ uid: string,
+ domains: readonly AppHealthDomain[],
+ tasksProbe: () => AppHealthTasksProbe,
+): Promise<Record<string, unknown>> {
+ const out: Record<string, unknown> = {};
+ for (const domain of domains) {
+ try {
+ if (domain === 'model') out.model = await modelProbe();
+ else if (domain === 'connectors') out.connectors = await connectorsProbe(uid);
+ else if (domain === 'kb') out.kb = kbVector.statusSummary(uid);
+ else if (domain === 'tasks') out.tasks = tasksProbe();
+ } catch {
+ out[domain] = { unavailable: true };
+ }
+ }
+ return out;
+}
diff --git a/src/main/features/group_chat/app_nav.ts b/src/main/features/group_chat/app_nav.ts
new file mode 100644
index 00000000..5dbbe7bc
--- /dev/null
+++ b/src/main/features/group_chat/app_nav.ts
@@ -0,0 +1,123 @@
+/**
+ * Commander-navigable app surfaces for the `open_app_view` tool.
+ *
+ * The tool stages a navigation card on the commander's reply; the renderer
+ * executes the navigation only when the user clicks the card, so this
+ * registry carries no side effects — it is the single source of truth for
+ * which surfaces exist and what the tool schema advertises. The renderer's
+ * executor map (conversation.js) must cover exactly these ids;
+ * `test/main/features/group_chat/app-nav-registry.test.ts` pins that parity.
+ */
+
+export type AppNavAction = 'open' | 'create' | 'add_custom' | 'configure';
+
+export interface AppNavSurface {
+ id: string;
+ /** Review-facing one-liner; the model schema receives the compact matrix. */
+ summary: string;
+ /** Closed actions supported by this surface. `open` is the default. */
+ actions: readonly AppNavAction[];
+ /** Actions that require a stable business id resolved by the renderer. */
+ targetRequiredFor?: readonly AppNavAction[];
+}
+
+export const APP_NAV_SURFACES: readonly AppNavSurface[] = [
+ { id: 'settings.models', summary: 'Settings → Models: model providers, API keys, priority order, connection tests.', actions: ['open'] },
+ { id: 'settings.general', summary: 'Settings → General: interface language and app preferences.', actions: ['open'] },
+ { id: 'settings.data', summary: 'Settings → Data: local data and access permissions.', actions: ['open'] },
+ {
+ id: 'connectors',
+ summary: 'Connectors: open the catalog, add a custom MCP server, or focus one configured connector.',
+ actions: ['open', 'add_custom', 'configure'],
+ targetRequiredFor: ['configure'],
+ },
+ { id: 'library', summary: 'Library: durable documents imported for retrieval.', actions: ['open'] },
+ {
+ id: 'projects',
+ summary: 'Projects: focus the sidebar list, start creation, or open one existing Project by id.',
+ actions: ['open', 'create', 'configure'],
+ targetRequiredFor: ['configure'],
+ },
+ {
+ id: 'agents',
+ summary: 'AI Team: open installed Agents, start creation, or open one Agent by id.',
+ actions: ['open', 'create', 'configure'],
+ targetRequiredFor: ['configure'],
+ },
+ { id: 'skills', summary: 'Skills: open installed Skills or start Skill creation.', actions: ['open', 'create'] },
+ {
+ id: 'auto',
+ summary: 'Automation: open scheduled tasks, start creation, or edit one task by id.',
+ actions: ['open', 'create', 'configure'],
+ targetRequiredFor: ['configure'],
+ },
+ { id: 'apps', summary: 'My Apps: saved interactive results that can be launched again.', actions: ['open'] },
+ { id: 'marketplace', summary: 'Marketplace: installable Agents and Skills.', actions: ['open'] },
+];
+
+export const APP_NAV_ACTIONS: readonly AppNavAction[] = Array.from(new Set(
+ APP_NAV_SURFACES.flatMap((surface) => surface.actions),
+));
+
+export function findAppNavSurface(id: string): AppNavSurface | null {
+ return APP_NAV_SURFACES.find((s) => s.id === id) ?? null;
+}
+
+export function appNavSurfaceDescription(): string {
+ const idsByActionSet = new Map<string, string[]>();
+ for (const surface of APP_NAV_SURFACES) {
+ const actionSet = surface.actions.join('|');
+ const ids = idsByActionSet.get(actionSet) ?? [];
+ ids.push(surface.id);
+ idsByActionSet.set(actionSet, ids);
+ }
+ return `Actions: ${[...idsByActionSet.entries()]
+ .map(([actions, ids]) => `${ids.join(', ')}=${actions}`)
+ .join('; ')}.`;
+}
+
+export function validateAppNavRequest(input: {
+ surface_id: string;
+ action?: string;
+ target_id?: string;
+}): { ok: true; request: Omit<AppNavRequest, 'requested_at'> } | { ok: false; error: string } {
+ const surface = findAppNavSurface(input.surface_id);
+ if (!surface) return { ok: false, error: `unknown surface_id: ${input.surface_id || '(empty)'}` };
+ const action = (input.action || 'open') as AppNavAction;
+ if (!surface.actions.includes(action)) {
+ return { ok: false, error: `action ${action} is not supported for ${surface.id}; allowed: ${surface.actions.join(', ')}` };
+ }
+ const targetId = String(input.target_id || '').trim();
+ if (targetId.length > 160 || /[\u0000-\u001f\u007f]/.test(targetId)) {
+ return { ok: false, error: 'target_id must be a bounded printable identifier' };
+ }
+ const requiresTarget = surface.targetRequiredFor?.includes(action) === true;
+ if (requiresTarget && !targetId) {
+ return { ok: false, error: `target_id is required for ${surface.id}/${action}` };
+ }
+ if (!requiresTarget && targetId) {
+ if (surface.actions.includes('configure')) {
+ return {
+ ok: false,
+ error: `target_id requires action configure for ${surface.id}; retry with action configure and the same target_id`,
+ };
+ }
+ return { ok: false, error: `target_id is not supported for ${surface.id}/${action}` };
+ }
+ return {
+ ok: true,
+ request: {
+ surface_id: surface.id,
+ action,
+ ...(targetId ? { target_id: targetId } : {}),
+ },
+ };
+}
+
+/** One staged navigation card (GroupMessage.app_nav_requests entry). */
+export interface AppNavRequest {
+ surface_id: string;
+ action: AppNavAction;
+ target_id?: string;
+ requested_at: string;
+}
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 8e66cede..10df4b43 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -49,7 +49,7 @@ import type {
import {
Actor, ActorKind, COMMANDER_ID, USER_ID, RESERVED_IDS,
actorSessionId, addMember, ensureAgentMember, readMembers, seedReservedActors,
- setStatus, markInFlight, readState, transitionStatus, setCodingProjectDir, touchActivity,
+ setStatus, markInFlight, readState, transitionStatus, setCodingProjectDir, setCodingProjectDirOnce, touchActivity,
setActiveRecipient, setOrchestrationLedger, markOrchestrationInterrupted,
takeOrchestrationLedgerForAgent, takeOrchestrationLedgerForForm, clearOrchestrationLedger,
beginAgentHandoff, rollbackAgentHandoff, clearOrchestrationForCancellation,
@@ -57,6 +57,10 @@ import {
import type { StateFile } from './state';
import { maxToolLoopsForActorKind } from './actor-budgets';
import { resolveDeliveryChecks } from './terminal-checks';
+import {
+ DurableMemoryWriteEvidence,
+ scrubCompletedDurableMemoryWriteClaims,
+} from './memory-write-verification';
import {
GroupMessage, appendVisible, readSlice,
buildGroupConversationHistory, buildGroupConversationHistoryTail,
@@ -98,6 +102,14 @@ import { buildLanguageDirective, normalizeLang, t, type Lang } from '../../i18n'
import { resolveLanguageForUser } from '../config';
import * as marketplaceFeat from '../marketplace';
import { readInstalls } from '../marketplace_installs';
+import {
+ APP_NAV_ACTIONS,
+ APP_NAV_SURFACES,
+ appNavSurfaceDescription,
+ validateAppNavRequest,
+ type AppNavRequest,
+} from './app_nav';
+import { APP_HEALTH_DOMAINS, collectAppHealth, isAppHealthDomain } from './app_health';
import { createSkillTurnBuffer, onAgentTurnEnd, onUserMessage } from '../expert_signals/turn_hooks';
import {
bindRuntimeSkillTarget,
@@ -878,6 +890,28 @@ interface WorkerState {
* metadata such as agent avatar tokens without relying on the model to
* copy every field back. */
marketplaceSearchResults?: Map<string, Partial<MarketplaceInstallRequest>>;
+ /** Navigation cards staged by `open_app_view` during a commander turn.
+ * Attached to the final message; the renderer navigates only on user
+ * click, so staging has no side effect. */
+ pendingAppNavRequests?: AppNavRequest[];
+}
+
+function stageAppNavRequest(
+ w: WorkerState,
+ input: { surface_id: string; action?: string; target_id?: string },
+): ReturnType<typeof validateAppNavRequest> {
+ const checked = validateAppNavRequest(input);
+ if (!checked.ok) return checked;
+ const request = checked.request;
+ if (!w.pendingAppNavRequests) w.pendingAppNavRequests = [];
+ if (!w.pendingAppNavRequests.some((existing) => (
+ existing.surface_id === request.surface_id
+ && existing.action === request.action
+ && (existing.target_id || '') === (request.target_id || '')
+ ))) {
+ w.pendingAppNavRequests.push({ ...request, requested_at: nowIso() });
+ }
+ return checked;
}
interface CidState {
@@ -1339,6 +1373,17 @@ export function hasActiveWork(uid?: string): boolean {
return false;
}
+/** Number of non-quiescent conversations for one user. App support exposes
+ * only this aggregate so Commander can distinguish the current task from
+ * work elsewhere without receiving conversation ids or content. */
+export function activeConversationCount(uid: string): number {
+ let count = 0;
+ for (const state of _cids.values()) {
+ if (state.uid === uid && !isQuiescent(state.uid, state.cid)) count += 1;
+ }
+ return count;
+}
+
export function runtimeSnapshot(uid: string, cid: string): { processing: boolean; inFlight: string[]; activeTurns: ActiveTurn[] } {
const s = _cids.get(cidKey(uid, cid));
if (!s) return { processing: false, inFlight: [], activeTurns: [] };
@@ -1712,6 +1757,7 @@ export interface EnqueueParams {
* interaction result back to it. */
artifacts?: Array<{ id: string; title: string; agent_id: string }>;
marketplace_requests?: MarketplaceInstallRequest[];
+ app_nav_requests?: AppNavRequest[];
plan_announcement?: boolean;
/** Override resolved recipients (commander emitting plan announcement
* uses this to force `to=[user]`). Otherwise router decides. */
@@ -2120,6 +2166,9 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
...(params.marketplace_requests && params.marketplace_requests.length
? { marketplace_requests: params.marketplace_requests }
: {}),
+ ...(params.app_nav_requests && params.app_nav_requests.length
+ ? { app_nav_requests: params.app_nav_requests }
+ : {}),
...(params.plan_announcement ? { plan_announcement: true } : {}),
...(params.dispatch ? { dispatch: true } : {}),
...(params.commanderRetryContinuation ? {
@@ -4153,6 +4202,10 @@ async function runActorTurn(
turnFailurePhase = _taskFailurePhase(phase);
};
let agentRunTimingData: Record<string, unknown> | undefined;
+ // Durable-memory success is a host-observed fact, never a prose inference.
+ // Keep the evidence across the one allowed channel retry because both
+ // attempts belong to the same persisted turn.
+ const durableMemoryWriteEvidence = new DurableMemoryWriteEvidence();
// Wire the commander segment flush now that `streamingText` exists. Called
// from a visible-dispatch tool BEFORE the dispatched agent runs, so the
// commander's reasoning since the last flush is persisted as its own `seg`
@@ -4535,6 +4588,15 @@ async function runActorTurn(
getPublishableOutputPaths,
hasProducedPath,
onArtifactCreated,
+ ...(isCommander ? {
+ onCustomConnectorAdded: (connectorId: string) => {
+ stageAppNavRequest(w, {
+ surface_id: 'connectors',
+ action: 'configure',
+ target_id: connectorId,
+ });
+ },
+ } : {}),
onSkillAdvertised: (id, sys) => skillBuffer.recordAdvertised(id, sys),
onSkillInvoked: (id, sys, trig) => skillBuffer.recordInvoked(id, sys, trig),
cacheRetention: 'short',
@@ -4575,6 +4637,7 @@ async function runActorTurn(
// Skills are NOT project-scoped this round; agent skillList still
// gates in-process agents' rendered skills and SkillStore.
})) {
+ if (isCommander) durableMemoryWriteEvidence.observe(ev);
// Stream events → process channel.
if (ev.type === 'final') {
finalText = ev.text || '';
@@ -4744,6 +4807,25 @@ async function runActorTurn(
} // end LLM branch (paired with `if (cliAgent) { ... } else {` above)
let workingText = finalText || '';
+ let correctedUnsupportedMemoryClaim = false;
+ if (isCommander
+ && workingText
+ && !errText
+ && !aborted
+ && !durableMemoryWriteEvidence.hasSuccessfulWrite()) {
+ const scrubbed = scrubCompletedDurableMemoryWriteClaims(workingText);
+ if (scrubbed.removedClaims > 0) {
+ correctedUnsupportedMemoryClaim = true;
+ const notice = t('chat.memory_write_unconfirmed', undefined, turnLanguage);
+ workingText = scrubbed.text ? `${notice}\n\n${scrubbed.text}` : notice;
+ markTurnFailure('validation', 'memory_write_unconfirmed');
+ log.warn('removed unsupported durable-memory success claim', {
+ cid: maskId(cid),
+ actor: actor.id,
+ removed_claims: scrubbed.removedClaims,
+ });
+ }
+ }
if (turnSyncConflictResolution.length && workingText && !errText && !aborted) {
const results = extractSyncConflictResults(workingText);
const allowedIds = new Set(turnSyncConflictResolution.map((item) => item.id));
@@ -5228,6 +5310,17 @@ async function runActorTurn(
: verb === 'enabled' ? 'enabled'
: 'disabled';
appendCommanderMutationNotice(`<span>Automation ${label}: ${name}</span>`);
+ // Keep a successful direct operation inspectable. Creation and
+ // updates run through the full auto_tasks feature above; this
+ // sidecar only offers the user a click-to-open route to the
+ // resulting business object after that workflow has succeeded.
+ if (result.taskId && result.kind !== 'deleted') {
+ stageAppNavRequest(w, {
+ surface_id: 'auto',
+ action: 'configure',
+ target_id: result.taskId,
+ });
+ }
} else {
markTurnFailure('operation', 'auto_task_operation_failed');
appendCommanderMutationNotice(`<span style="color:var(--danger)">⚠️ Automation operation failed: ${escapeHtmlForBubble(result.error || 'unknown error')}</span>`);
@@ -5332,8 +5425,17 @@ async function runActorTurn(
const turnMarketplaceRequests = actor.kind === 'commander' && w.pendingMarketplaceRequests?.length
? w.pendingMarketplaceRequests.slice()
: [];
- if (actor.kind === 'commander') w.pendingMarketplaceRequests = undefined;
- if (turnMarketplaceRequests.length > 0 && outcome.kind === 'silent') {
+ // Navigation cards staged by `open_app_view` follow the same flush shape:
+ // attached to the final commander message so the renderer can show the
+ // click-to-open button; the card itself is the visible outcome.
+ const turnAppNavRequests = actor.kind === 'commander' && w.pendingAppNavRequests?.length
+ ? w.pendingAppNavRequests.slice()
+ : [];
+ if (actor.kind === 'commander') {
+ w.pendingMarketplaceRequests = undefined;
+ w.pendingAppNavRequests = undefined;
+ }
+ if ((turnMarketplaceRequests.length > 0 || turnAppNavRequests.length > 0) && outcome.kind === 'silent') {
outcome = { kind: 'persist', text: '' };
}
@@ -5381,6 +5483,34 @@ async function runActorTurn(
outcome = (!tail.trim() && !hasSide) ? { kind: 'silent' } : { ...outcome, text: tail };
}
+ // Segment-tail replacement above reads the raw streamed text and can
+ // otherwise reintroduce a success claim removed from `workingText`. Make the
+ // correction the last authority for this non-aborted turn. If the claim was
+ // in a segment already persisted before a dispatch boundary, the terminal
+ // notice still corrects it explicitly instead of leaving the user with a
+ // false durable-write confirmation.
+ if (correctedUnsupportedMemoryClaim) {
+ const notice = t('chat.memory_write_unconfirmed', undefined, turnLanguage);
+ const current = outcome.kind === 'persist' ? outcome.text : '';
+ const scrubbed = scrubCompletedDurableMemoryWriteClaims(current);
+ const body = scrubbed.text === notice || scrubbed.text.startsWith(`${notice}\n`)
+ ? scrubbed.text
+ : scrubbed.text ? `${notice}\n\n${scrubbed.text}` : notice;
+ outcome = outcome.kind === 'persist'
+ ? {
+ ...outcome,
+ text: body,
+ failureKind: 'validation',
+ failureCode: 'memory_write_unconfirmed',
+ }
+ : {
+ kind: 'persist',
+ text: body,
+ failureKind: 'validation',
+ failureCode: 'memory_write_unconfirmed',
+ };
+ }
+
if (aborted) {
// Keep the process trail on abort so a stopped tool run isn't lost — EXCEPT
// a commander turn that only routed (a delegation call + the reads it did to
@@ -5491,6 +5621,7 @@ async function runActorTurn(
? { artifacts: turnArtifacts.map((a) => ({ id: a.id, title: a.title, agent_id: actor.id })) }
: {}),
...(turnMarketplaceRequests.length ? { marketplace_requests: turnMarketplaceRequests } : {}),
+ ...(turnAppNavRequests.length ? { app_nav_requests: turnAppNavRequests } : {}),
...(tailProcessItems.length ? { process: tailProcessItems } : {}),
// Segment this reply closes. Always present, including for turns that
// were never split — an unsplit turn is simply segment 0. The renderer
@@ -7266,6 +7397,91 @@ async function buildCommanderExtraTools(
},
});
+ tools.push({
+ name: 'open_app_view',
+ description:
+ 'Stage a click-to-open card for a supported Orkas destination. The renderer navigates only after the user clicks.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ surface_id: {
+ type: 'string',
+ enum: APP_NAV_SURFACES.map((s) => s.id),
+ description: appNavSurfaceDescription(),
+ },
+ action: {
+ type: 'string',
+ enum: APP_NAV_ACTIONS,
+ description: 'Defaults to open for a list or landing page. Use create for a new resource, add_custom for a custom MCP server, and configure with target_id for one existing Project, Agent, connector, or automation.',
+ },
+ target_id: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 160,
+ description: 'Required with action=configure for one existing Project, Agent, connector, or automation. If target_id is present, action must be configure even when the user says open or view.',
+ },
+ },
+ required: ['surface_id'],
+ additionalProperties: false,
+ },
+ async execute(input: Record<string, unknown>) {
+ const surfaceId = String(input.surface_id ?? '').trim();
+ const checked = stageAppNavRequest(w, {
+ surface_id: surfaceId,
+ action: String(input.action ?? '').trim(),
+ target_id: String(input.target_id ?? '').trim(),
+ });
+ if ('error' in checked) return _toolError(checked.error);
+ const request = checked.request;
+ return _toolJson({
+ ok: true,
+ status: 'navigation_card_staged',
+ ...request,
+ instruction: 'A click-to-open card appears with your reply. Tell the user in one line what to click and what to do on that screen.',
+ });
+ },
+ });
+
+ tools.push({
+ name: 'app_health',
+ description:
+ 'Return a sanitized read-only snapshot of supported Orkas app-health domains. It never returns credentials, paths, provider error text, or user content.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ domain: {
+ type: 'string',
+ enum: [...APP_HEALTH_DOMAINS],
+ description: 'Optional single domain; omit for the full snapshot.',
+ },
+ },
+ additionalProperties: false,
+ },
+ executionMode: 'parallel',
+ async execute(input: Record<string, unknown>) {
+ const domainRaw = String(input.domain ?? '').trim();
+ if (domainRaw && !isAppHealthDomain(domainRaw)) {
+ return _toolError(`domain must be one of: ${APP_HEALTH_DOMAINS.join(', ')}`);
+ }
+ const domains = isAppHealthDomain(domainRaw) ? [domainRaw] : APP_HEALTH_DOMAINS;
+ const snapshot = await collectAppHealth(uid, domains, () => {
+ const s = runtimeSnapshot(uid, cid);
+ const activeCount = activeConversationCount(uid);
+ return {
+ active_work: activeCount > 0,
+ active_conversation_count: activeCount,
+ other_active_conversation_count: Math.max(0, activeCount - (s.processing ? 1 : 0)),
+ current_conversation: {
+ processing: s.processing,
+ in_flight_actor_count: s.inFlight.length,
+ active_turn_count: s.activeTurns.length,
+ },
+ };
+ });
+ return _toolJson({ ok: true, ...snapshot });
+ },
+ });
+
return tools;
}
@@ -7457,11 +7673,18 @@ async function _initializeCodingProjectDir(
}
const target = info.effective_path;
if (!target) return;
- await setCodingProjectDir(uid, cid, target, { explicit: info.mode === 'custom' && info.exists });
- log.info('coding project directory initialized', {
- cid: maskId(cid),
- source: info.mode,
+ // Set-once under the state lock: two coding agents' first turns can race
+ // this initialisation, and both must converge on ONE winner (the read above
+ // is only a fast path). The caller re-reads state and uses the recorded dir.
+ const { applied } = await setCodingProjectDirOnce(uid, cid, target, {
+ explicit: info.mode === 'custom' && info.exists,
});
+ if (applied) {
+ log.info('coding project directory initialized', {
+ cid: maskId(cid),
+ source: info.mode,
+ });
+ }
}
/** Build an `<agent-input-form>` block listing the agent's required
diff --git a/src/main/features/group_chat/memory-write-verification.ts b/src/main/features/group_chat/memory-write-verification.ts
new file mode 100644
index 00000000..f0c5945d
--- /dev/null
+++ b/src/main/features/group_chat/memory-write-verification.ts
@@ -0,0 +1,166 @@
+/**
+ * Host-side evidence for durable-memory success claims.
+ *
+ * A model may only tell the user that durable memory was written when this
+ * turn produced a successful `add` or `replace` result from
+ * `cross_session_memory`.
+ * The bus owns that evidence because it observes the validated tool lifecycle;
+ * prose, reasoning, and a read-only `list` call are not evidence of a write.
+ */
+
+const MEMORY_TOOL = 'cross_session_memory';
+const MEMORY_WRITES = new Set(['add', 'replace']);
+
+type ToolCall = {
+ name: string;
+ action: string;
+};
+
+function record(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null;
+}
+
+/** Tracks successful durable-memory writes from the mapped stream events. */
+export class DurableMemoryWriteEvidence {
+ private readonly calls = new Map<string, ToolCall>();
+ private successfulWrite = false;
+
+ observe(value: unknown): void {
+ const outer = record(value);
+ if (outer?.type !== 'event') return;
+ const event = record(outer.event);
+ if (event?.stream !== 'tool') return;
+ const data = record(event.data);
+ if (!data) return;
+
+ const id = typeof data.id === 'string' ? data.id.trim() : '';
+ const phase = typeof data.phase === 'string' ? data.phase : '';
+ const previous = id ? this.calls.get(id) : undefined;
+ const name = typeof data.name === 'string' && data.name
+ ? data.name
+ : previous?.name || '';
+
+ if ((phase === 'start' || phase === 'progress') && id) {
+ const args = record(data.arguments);
+ const action = typeof args?.action === 'string'
+ ? args.action.trim().toLowerCase()
+ : previous?.action || '';
+ if (name === MEMORY_TOOL || previous?.name === MEMORY_TOOL) {
+ this.calls.set(id, { name: MEMORY_TOOL, action });
+ }
+ return;
+ }
+
+ if (phase !== 'end') return;
+ if (id) this.calls.delete(id);
+ const action = previous?.action || '';
+ if (name === MEMORY_TOOL
+ && MEMORY_WRITES.has(action)
+ && data.isError === false) {
+ this.successfulWrite = true;
+ }
+ }
+
+ hasSuccessfulWrite(): boolean {
+ return this.successfulWrite;
+ }
+}
+
+// `project profile`, `user preferences`, `项目档案`, and `项目笔记` are
+// also ordinary file/artifact descriptions. Scope words alone therefore only
+// qualify the unambiguous noun "memory"; profile/note/preference needs an
+// explicit durable-time qualifier before a success claim can be scrubbed.
+const DURABLE_MEMORY_ZH = /(?:(?:长期|持久|跨会话).{0,10}(?:记忆|笔记|偏好|档案)|(?:记忆|笔记|偏好|档案).{0,10}(?:长期|持久|跨会话)|(?:项目|共享|用户|智能体|个人).{0,10}记忆|记忆.{0,10}(?:项目|共享|用户|智能体|个人)|(?:下次|以后|未来).{0,12}(?:记得|沿用|使用))/u;
+const COMPLETED_WRITE_ZH = /(?:(?:已|已经|刚刚|成功|现已|全部|都|均).{0,24}(?:记下|记住|保存|记录|写入|存入|录入|更新)|(?:记下|记住|保存|记录|写入|存入|录入|更新).{0,8}(?:了|好|完成|成功|完毕))/u;
+const NEGATED_OR_NONCURRENT_ZH = /(?:(?:未|没有|并未|尚未|没能|无法|不能|不曾).{0,18}(?:记下|记住|保存|记录|写入|存入|录入|更新)|(?:会|将|准备|打算|计划|可以|需要|应该|请|尝试|待).{0,18}(?:记下|记住|保存|记录|写入|存入|录入|更新)|(?:之前|此前|上次|过去|先前|早已).{0,18}(?:记下|记住|保存|记录|写入|存入|录入|更新)|(?:不要|不应|禁止|避免).{0,18}(?:声称|说|表示))/u;
+
+const DURABLE_MEMORY_EN = /(?:(?:long[- ]term|persistent|cross[- ]session).{0,16}(?:memory|notes?|preferences?|profile)|(?:memory|notes?|preferences?|profile).{0,16}(?:long[- ]term|persistent|cross[- ]session)|(?:project|shared|user|agent|personal).{0,16}memory|memory.{0,16}(?:project|shared|user|agent|personal)|(?:for (?:the )?future|next time))/iu;
+const COMPLETED_WRITE_EN = /(?:(?:i(?:'ve| have)?|we(?:'ve| have)?|already|just|successfully|now|all|everything).{0,24}(?:saved|stored|recorded|written|added|updated|remembered)|(?:saved|stored|recorded|written|added|updated|remembered).{0,12}(?:successfully|already|now|complete|completed))/iu;
+const NEGATED_OR_NONCURRENT_EN = /(?:(?:not|never|didn't|did not|haven't|have not|hasn't|has not|failed to|couldn't|could not|unable to).{0,24}(?:save|store|record|write|add|update|remember)|(?:will|would|can|could|should|plan(?:ning)? to|intend to|need to|please|try to).{0,24}(?:save|store|record|write|add|update|remember)|(?:earlier|previously|last time|in the past|before).{0,24}(?:saved|stored|recorded|written|added|updated|remembered)|(?:do not|don't|should not|must not|avoid).{0,18}(?:claim|say|state))/iu;
+
+const DURABLE_MEMORY_JA = /(?:(?:長期|永続).{0,10}(?:メモリ|メモ|記憶)|(?:メモリ|メモ|記憶).{0,10}(?:長期|永続)|(?:プロジェクト|共有|ユーザー|エージェント).{0,10}(?:メモリ|記憶)|(?:メモリ|記憶).{0,10}(?:プロジェクト|共有|ユーザー|エージェント))/u;
+const COMPLETED_WRITE_JA = /(?:保存|記録|書き込|登録|覚え).{0,8}(?:しました|済み|完了|ました|てあります)/u;
+const NEGATED_OR_NONCURRENT_JA = /(?:保存|記録|書き込|登録|覚え).{0,10}(?:していません|できませんでした|しません|する予定|します)/u;
+
+const DURABLE_MEMORY_PT = /(?:(?:memória|notas?|preferências?|perfil).{0,18}(?:persistente|longo prazo)|(?:persistente|longo prazo).{0,18}(?:memória|notas?|preferências?|perfil)|memória.{0,18}(?:projeto|compartilhad[ao]|usuário|agente)|(?:projeto|compartilhad[ao]|usuário|agente).{0,18}memória)/iu;
+const COMPLETED_WRITE_PT = /(?:salvei|guardei|gravei|registrei|adicionei|atualizei|foi salv[ao]|foram salv[ao]s)/iu;
+const NEGATED_OR_NONCURRENT_PT = /(?:(?:não|ainda não|falhou).{0,24}(?:salvar|guardar|gravar|registrar|adicionar|atualizar)|(?:vou|iremos|posso|podemos|devo|pretendo).{0,20}(?:salvar|guardar|gravar|registrar|adicionar|atualizar))/iu;
+
+function proseForDetection(value: string): string {
+ return value
+ .replace(/`[^`]*`/gu, ' ')
+ .replace(/“[^”]*”|"[^"]*"/gu, ' ')
+ .replace(/[*_~#]/gu, ' ')
+ .replace(/\s+/gu, ' ')
+ .trim();
+}
+
+/** Narrowly identifies a completed write claim that requires tool evidence. */
+export function claimsCompletedDurableMemoryWrite(value: string): boolean {
+ const prose = proseForDetection(String(value || ''));
+ if (!prose) return false;
+
+ const zh = DURABLE_MEMORY_ZH.test(prose)
+ && COMPLETED_WRITE_ZH.test(prose)
+ && !NEGATED_OR_NONCURRENT_ZH.test(prose);
+ const en = DURABLE_MEMORY_EN.test(prose)
+ && COMPLETED_WRITE_EN.test(prose)
+ && !NEGATED_OR_NONCURRENT_EN.test(prose);
+ const ja = DURABLE_MEMORY_JA.test(prose)
+ && COMPLETED_WRITE_JA.test(prose)
+ && !NEGATED_OR_NONCURRENT_JA.test(prose);
+ const pt = DURABLE_MEMORY_PT.test(prose)
+ && COMPLETED_WRITE_PT.test(prose)
+ && !NEGATED_OR_NONCURRENT_PT.test(prose);
+ return zh || en || ja || pt;
+}
+
+export interface MemoryClaimScrubResult {
+ text: string;
+ removedClaims: number;
+}
+
+function scrubProseLine(line: string): MemoryClaimScrubResult {
+ const pieces = line.match(/[^。!?.!?;;]+[。!?.!?;;]*\s*/gu) || [line];
+ let removedClaims = 0;
+ const kept = pieces.filter((piece) => {
+ if (!claimsCompletedDurableMemoryWrite(piece)) return true;
+ removedClaims += 1;
+ return false;
+ });
+ return { text: kept.join('').trimEnd(), removedClaims };
+}
+
+/**
+ * Removes only unsupported success-claim sentences. Fenced code and quoted
+ * Markdown are evidence examples, not the actor's own assertions, so they are
+ * deliberately left untouched.
+ */
+export function scrubCompletedDurableMemoryWriteClaims(value: string): MemoryClaimScrubResult {
+ const lines = String(value || '').split('\n');
+ const out: string[] = [];
+ let inFence = false;
+ let removedClaims = 0;
+
+ for (const line of lines) {
+ if (/^\s*(?:```|~~~)/u.test(line)) {
+ inFence = !inFence;
+ out.push(line);
+ continue;
+ }
+ if (inFence || /^\s*>/u.test(line)) {
+ out.push(line);
+ continue;
+ }
+ const scrubbed = scrubProseLine(line);
+ removedClaims += scrubbed.removedClaims;
+ if (scrubbed.text || !line.trim()) out.push(scrubbed.text);
+ }
+
+ return {
+ text: out.join('\n').replace(/^\s+|\s+$/gu, ''),
+ removedClaims,
+ };
+}
diff --git a/src/main/features/group_chat/state.ts b/src/main/features/group_chat/state.ts
index 53b7bbd6..109ea878 100644
--- a/src/main/features/group_chat/state.ts
+++ b/src/main/features/group_chat/state.ts
@@ -1008,6 +1008,26 @@ export async function setCodingProjectDir(
});
}
+/** Initialise the coding-agent project directory only if the conversation has
+ * none yet. The already-set check runs inside the state lock so concurrent
+ * first turns converge on one working directory. */
+export async function setCodingProjectDirOnce(
+ uid: string, cid: string, dir: string,
+ opts: { explicit: boolean },
+): Promise<{ state: StateFile; applied: boolean }> {
+ return _stateLock(uid, cid).runExclusive(async () => {
+ const s = await readState(uid, cid);
+ const trimmed = String(dir || '').trim();
+ if (s.coding_project_dir || !trimmed) return { state: s, applied: false };
+ s.coding_project_dir = trimmed;
+ if (opts.explicit) s.coding_project_dir_explicit = true;
+ else delete s.coding_project_dir_explicit;
+ s.last_active_at = nowIso();
+ await writeStateRaw(uid, cid, s);
+ return { state: s, applied: true };
+ });
+}
+
export async function setToolExtraRoots(uid: string, cid: string, roots: readonly string[]): Promise<StateFile> {
return _stateLock(uid, cid).runExclusive(async () => {
const s = await readState(uid, cid);
diff --git a/src/main/features/group_chat/visibility.ts b/src/main/features/group_chat/visibility.ts
index a18035b5..40883c31 100644
--- a/src/main/features/group_chat/visibility.ts
+++ b/src/main/features/group_chat/visibility.ts
@@ -147,6 +147,15 @@ export interface GroupMessage {
* official marketplace and request a user decision, but the install only
* happens after the human clicks the rendered card. */
marketplace_requests?: MarketplaceInstallRequest[];
+ /** Commander-staged navigation cards (`open_app_view`). The renderer shows
+ * a click-to-open button; navigation happens only on the user's click, so
+ * the record carries only the validated surface/action/target request. */
+ app_nav_requests?: Array<{
+ surface_id: string;
+ action: 'open' | 'create' | 'add_custom' | 'configure';
+ target_id?: string;
+ requested_at: string;
+ }>;
/** Marks this message as a plan announcement (rendered with a folded
* plan card in UI). Set by `plan_set` first-time emission. */
plan_announcement?: boolean;
@@ -345,7 +354,7 @@ function commanderHistoryRoute(record: CommanderHistoryRecord): {
return { from, recipients, attributes };
}
-/** Remove only the old host-owned prefix that can be derived from this
+/** Remove only a host-owned prefix that can be derived from this
* authoritative non-user record. Canonical JSONL remains untouched. User
* examples, embedded mentions, quotes/code fences and unknown look-alikes do
* not match this leading-line contract and remain verbatim. */
@@ -358,6 +367,9 @@ function stripLegacyHistoryRoutePrefix(
const legacyHeaders = new Set([
`[${from} -> ${recipients}]`,
...(attributes.length ? [`[${from} -> ${recipients}; ${attributes.join('; ')}]`] : []),
+ record.dispatch
+ ? `${from} delegated this step to ${recipients}:`
+ : `${from} replied to ${recipients}:`,
]);
const lines = body.split(/\r?\n/);
let removed = false;
diff --git a/src/main/features/local_agents/backends/base.ts b/src/main/features/local_agents/backends/base.ts
index e6fd53a7..211becec 100644
--- a/src/main/features/local_agents/backends/base.ts
+++ b/src/main/features/local_agents/backends/base.ts
@@ -40,6 +40,28 @@ export type LocalEventType =
| 'idle'
| 'done';
+/** Tool names whose result carries an image because the agent READ a file,
+ * not because it produced one. CLI file readers hand the file back as an
+ * image block, which is indistinguishable from generated media at the
+ * event layer — without this gate a plain "read that screenshot" bounces
+ * the user's own attachment back into the conversation as
+ * `![generated image]`. */
+const FILE_READ_TOOL_NAMES = new Set([
+ 'read',
+ 'read_file',
+ 'readfile',
+ 'notebookread',
+ 'view',
+]);
+
+/** True when a tool result's media came from reading a file rather than
+ * producing one. Unknown tool names return false so genuinely generated
+ * media is never dropped. */
+export function isFileReadToolName(name: unknown): boolean {
+ if (typeof name !== 'string') return false;
+ return FILE_READ_TOOL_NAMES.has(name.trim().toLowerCase());
+}
+
export interface LocalEvent {
type: LocalEventType;
/** Free-form payload — exact keys vary per type. Documented inline at
diff --git a/src/main/features/local_agents/backends/claude.ts b/src/main/features/local_agents/backends/claude.ts
index d95b8a95..31011770 100644
--- a/src/main/features/local_agents/backends/claude.ts
+++ b/src/main/features/local_agents/backends/claude.ts
@@ -28,6 +28,7 @@ import {
armKillWatchdog,
LineSplitter,
levelOrInfo,
+ isFileReadToolName,
} from './base.js';
const log = createLogger('local-agents:claude');
@@ -86,7 +87,10 @@ export const claudeBackend: LocalBackend = {
// versions that ignore `--include-partial-messages` never emit
// stream_events; in that case we fall back to emitting from the
// assistant block so the user still sees the final text.
- const partialState = { sawTextStreamEvent: false };
+ const partialState: ClaudeParseState = {
+ sawTextStreamEvent: false,
+ toolNamesByCallId: new Map<string, string>(),
+ };
opts.onEvent({
type: 'process-info',
@@ -492,6 +496,9 @@ export const claudeBackend: LocalBackend = {
// stream-json process. A later self-woken turn may fall back to full
// assistant blocks even when the previous turn streamed deltas.
partialState.sawTextStreamEvent = false;
+ // Tool calls never span turns; drop any callId whose result
+ // never arrived so the map stays turn-scoped.
+ partialState.toolNamesByCallId?.clear();
if (liveTasks.size > 0) {
enterBackground();
// `result` would otherwise be the latest activity row. Reassert the
@@ -665,10 +672,19 @@ export function buildClaudeArgs(opts: Pick<BackendRunOptions,
* tool_use blocks because the partial input_json deltas alone
* aren't enough to render a useful tool-event.
*/
+export type ClaudeParseState = {
+ sawTextStreamEvent: boolean;
+ /** callId -> tool name, captured from the assistant `tool_use` block so the
+ * `tool_result` branch can tell agent-produced media apart from a file the
+ * agent merely read. Optional: callers that only care about text (and the
+ * parser tests) may pass a bare `{ sawTextStreamEvent }`. */
+ toolNamesByCallId?: Map<string, string>;
+};
+
export function mapClaudeEvent(
obj: any,
_sessionIdSoFar: string | undefined,
- partialState: { sawTextStreamEvent: boolean } = { sawTextStreamEvent: false },
+ partialState: ClaudeParseState = { sawTextStreamEvent: false },
):
| undefined
| {
@@ -921,10 +937,17 @@ export function mapClaudeEvent(
continue;
}
if (part?.type === 'tool_use') {
+ const useCallId = String(part.id || '');
+ const useToolName = String(part.name || 'unknown');
+ // Recorded so the matching tool_result can classify any image it
+ // carries. Consumed (and deleted) there; cleared at turn end.
+ if (useCallId && partialState.toolNamesByCallId) {
+ partialState.toolNamesByCallId.set(useCallId, useToolName);
+ }
events.push({
type: 'tool-event',
- tool: String(part.name || 'unknown'),
- callId: String(part.id || ''),
+ tool: useToolName,
+ callId: useCallId,
phase: 'use',
input: part.input ?? {},
});
@@ -951,7 +974,14 @@ export function mapClaudeEvent(
output: out,
});
const mediaItems = claudeToolResultImages(part.content);
- if (mediaItems.length) {
+ const originTool = callId
+ ? partialState.toolNamesByCallId?.get(callId) || ''
+ : '';
+ if (callId) partialState.toolNamesByCallId?.delete(callId);
+ // `Read` returns the file itself as an image block. Publishing that
+ // republished whatever the agent looked at — including the user's own
+ // upload — as `![generated image]`.
+ if (mediaItems.length && !isFileReadToolName(originTool)) {
events.push({
type: 'media-output',
source: 'claude',
diff --git a/src/main/features/local_agents/backends/opencode.ts b/src/main/features/local_agents/backends/opencode.ts
index 0456ee31..7366cdbb 100644
--- a/src/main/features/local_agents/backends/opencode.ts
+++ b/src/main/features/local_agents/backends/opencode.ts
@@ -31,6 +31,7 @@ import {
bindAbort,
armKillWatchdog,
LineSplitter,
+ isFileReadToolName,
} from './base.js';
const log = createLogger('local-agents:opencode');
@@ -243,7 +244,9 @@ export function mapOpencodeEvent(obj: any):
...(isError ? { isError: true } : {}),
};
const mediaItems = opencodeImageAttachments(state.attachments);
- if (mediaItems.length) {
+ // Same guard as the claude backend: a file-read tool's attachments are
+ // the file it read, not media the agent produced.
+ if (mediaItems.length && !isFileReadToolName(part.tool)) {
out!.event = toolEvent;
out!.events = [toolEvent, {
type: 'media-output',
diff --git a/src/main/features/user_workspace.ts b/src/main/features/user_workspace.ts
index 6302b4a4..594441d7 100644
--- a/src/main/features/user_workspace.ts
+++ b/src/main/features/user_workspace.ts
@@ -41,7 +41,7 @@ import { dialog, BrowserWindow, shell } from 'electron';
import { DEFAULT_USER_WORKSPACE, userWorkspaceConfigFile } from '../paths';
import { createLogger } from '../logger';
import { t } from '../i18n';
-import { macosTccWorkspaceBlockedPath } from '../util/macos-tcc';
+import { macosTccSensitivePath } from '../util/macos-tcc';
import { logPathRef, logPathRefs } from '../util/log-redact';
import { pruneOrphans } from './file_indexer';
@@ -55,6 +55,9 @@ const log = createLogger('user-workspace');
interface ScopeEntry {
selectedPath: string;
recentPaths: string[];
+ /** Persisted selection-time classification. A protected workspace remains
+ * usable, but passive workspace resolution must not probe it on macOS. */
+ macosTccSensitive?: boolean;
}
interface WorkspaceConfig {
@@ -69,6 +72,7 @@ function configPath(userId: string): string {
const MAX_RECENT = 5;
const EMPTY_ENTRY: ScopeEntry = { selectedPath: '', recentPaths: [] };
+const _tccClassificationMigrationChecked = new Set<string>();
function _normaliseEntry(raw: any): ScopeEntry {
if (!raw || typeof raw !== 'object') return { ...EMPTY_ENTRY };
@@ -77,6 +81,9 @@ function _normaliseEntry(raw: any): ScopeEntry {
recentPaths: Array.isArray(raw.recentPaths)
? raw.recentPaths.filter((p: unknown) => typeof p === 'string')
: [],
+ ...(raw.macosTccSensitive === true
+ ? { macosTccSensitive: true }
+ : {}),
};
}
@@ -108,12 +115,29 @@ function _normaliseConfig(raw: any): WorkspaceConfig {
function readConfig(userId: string): WorkspaceConfig {
const p = configPath(userId);
+ let cfg: WorkspaceConfig;
try {
const raw = fs.readFileSync(p, 'utf-8');
- return _normaliseConfig(JSON.parse(raw));
+ cfg = _normaliseConfig(JSON.parse(raw));
} catch {
return { default: { ...EMPTY_ENTRY }, projects: {}, updatedAt: '' };
}
+ // A short-lived release accepted symlink aliases into TCC roots before the
+ // classification field existed. Resolve those legacy entries once, persist
+ // only a positive classification, and avoid repeating that probe on every
+ // workspace read or app launch.
+ if (!_tccClassificationMigrationChecked.has(p)) {
+ _tccClassificationMigrationChecked.add(p);
+ if (_markMacosTccSensitiveSelections(cfg)) {
+ try { writeConfig(userId, cfg); }
+ catch (err) {
+ log.warn('workspace TCC classification migration could not be persisted', {
+ error_type: err instanceof Error ? err.name : 'unknown',
+ });
+ }
+ }
+ }
+ return cfg;
}
function writeConfig(userId: string, cfg: WorkspaceConfig): void {
@@ -144,21 +168,24 @@ function _writeEntry(cfg: WorkspaceConfig, projectId: string | undefined, entry:
return { ...cfg, default: entry, updatedAt: new Date().toISOString() };
}
-function _isWorkspaceSelectionBlocked(dirPath: string): ReturnType<typeof macosTccWorkspaceBlockedPath> {
- return macosTccWorkspaceBlockedPath(path.resolve(dirPath));
+function _macosTccSensitiveWorkspacePath(
+ dirPath: string,
+): ReturnType<typeof macosTccSensitivePath> {
+ return macosTccSensitivePath(path.resolve(dirPath), { recursive: true });
}
-/** Resolve an explicitly selected path before persisting/using it so a
- * symlink or case-variant alias cannot disguise a protected macOS root. The
- * direct lexical check runs first and therefore never probes a known TCC
- * directory merely to reject it. */
+/** Classify an explicitly selected path before persisting it so a symlink or
+ * case-variant alias cannot disguise a protected macOS root. The direct
+ * lexical check runs first and therefore never probes a known TCC directory.
+ * Protected selections are allowed; the classification tells passive callers
+ * to use the stored path without touching the directory. */
function _resolveWorkspaceSelection(dirPath: string): {
path: string;
- blocked: ReturnType<typeof macosTccWorkspaceBlockedPath>;
+ macosTccSensitive: boolean;
} {
const lexicalPath = path.resolve(dirPath);
- const lexicalBlock = macosTccWorkspaceBlockedPath(lexicalPath);
- if (lexicalBlock) return { path: lexicalPath, blocked: lexicalBlock };
+ const lexicalSensitivity = _macosTccSensitiveWorkspacePath(lexicalPath);
+ if (lexicalSensitivity) return { path: lexicalPath, macosTccSensitive: true };
let canonicalPath = lexicalPath;
try { canonicalPath = fs.realpathSync.native(lexicalPath); }
catch { /* setWorkspacePath/stat below returns the canonical missing-path error */ }
@@ -166,26 +193,42 @@ function _resolveWorkspaceSelection(dirPath: string): {
// Preserve the user-facing spelling (including /var vs /private/var and
// safe symlink aliases); canonicalPath is only security-comparison input.
path: lexicalPath,
- blocked: macosTccWorkspaceBlockedPath(canonicalPath),
+ macosTccSensitive: !!_macosTccSensitiveWorkspacePath(canonicalPath),
};
}
+function _entryIsMacosTccSensitive(entry: ScopeEntry): boolean {
+ if (entry.macosTccSensitive === true) return true;
+ if (_macosTccSensitiveWorkspacePath(entry.selectedPath)) return true;
+ return _resolveWorkspaceSelection(entry.selectedPath).macosTccSensitive;
+}
+
+function _markMacosTccSensitiveSelections(cfg: WorkspaceConfig): boolean {
+ let changed = false;
+ const entries = [cfg.default, ...Object.values(cfg.projects)];
+ for (const entry of entries) {
+ if (!entry.selectedPath || entry.macosTccSensitive === true) continue;
+ if (_resolveWorkspaceSelection(entry.selectedPath).macosTccSensitive) {
+ entry.macosTccSensitive = true;
+ changed = true;
+ }
+ }
+ return changed;
+}
+
/** Effective path for a given scope: project's selection (if any) → default's
- * selection (if any) → DEFAULT_USER_WORKSPACE. Privacy-protected legacy
- * selections are never probed and never returned as execution roots. */
+ * selection (if any) → DEFAULT_USER_WORKSPACE. A macOS privacy-protected
+ * selection is returned without stat: it came from the native picker, while
+ * background scanners independently opt out before walking TCC roots. */
function _effectivePath(cfg: WorkspaceConfig, projectId?: string): string {
if (projectId) {
const entry = cfg.projects[projectId];
if (entry?.selectedPath) {
- const selection = _resolveWorkspaceSelection(entry.selectedPath);
- const blocked = selection.blocked;
- if (blocked) {
- log.warn('project workspace path is privacy-protected — falling back without stat', {
- projectId, path: logPathRef(entry.selectedPath), reason: blocked.reason,
- });
+ if (_entryIsMacosTccSensitive(entry)) {
+ return path.resolve(entry.selectedPath);
} else {
try {
- if (fs.statSync(selection.path).isDirectory()) return selection.path;
+ if (fs.statSync(entry.selectedPath).isDirectory()) return path.resolve(entry.selectedPath);
} catch {
log.warn('project workspace path missing — falling back to default', {
projectId, path: logPathRef(entry.selectedPath),
@@ -195,15 +238,11 @@ function _effectivePath(cfg: WorkspaceConfig, projectId?: string): string {
}
}
if (cfg.default.selectedPath) {
- const selection = _resolveWorkspaceSelection(cfg.default.selectedPath);
- const blocked = selection.blocked;
- if (blocked) {
- log.warn('default workspace path is privacy-protected — using DEFAULT_USER_WORKSPACE without stat', {
- path: logPathRef(cfg.default.selectedPath), reason: blocked.reason,
- });
+ if (_entryIsMacosTccSensitive(cfg.default)) {
+ return path.resolve(cfg.default.selectedPath);
} else {
try {
- if (fs.statSync(selection.path).isDirectory()) return selection.path;
+ if (fs.statSync(cfg.default.selectedPath).isDirectory()) return path.resolve(cfg.default.selectedPath);
} catch {
log.warn('default workspace path missing — using DEFAULT_USER_WORKSPACE', {
path: logPathRef(cfg.default.selectedPath),
@@ -217,10 +256,10 @@ function _effectivePath(cfg: WorkspaceConfig, projectId?: string): string {
function _configuredDisplayPath(cfg: WorkspaceConfig, projectId?: string): string {
if (projectId) {
const projectSelected = cfg.projects[projectId]?.selectedPath;
- if (projectSelected && !_isWorkspaceSelectionBlocked(projectSelected)) return projectSelected;
+ if (projectSelected) return projectSelected;
}
const selected = cfg.default.selectedPath;
- if (selected && !_isWorkspaceSelectionBlocked(selected)) return selected;
+ if (selected) return selected;
return DEFAULT_USER_WORKSPACE;
}
@@ -252,7 +291,12 @@ export function getWorkspacePath(userId: string, projectId?: string): string {
*/
export function consumePickerFirstOpenDefault(userId: string): string | undefined {
if (!userId) return undefined;
- try { return getWorkspacePath(userId); }
+ try {
+ const workspacePath = getWorkspacePath(userId);
+ return _macosTccSensitiveWorkspacePath(workspacePath)
+ ? DEFAULT_USER_WORKSPACE
+ : workspacePath;
+ }
catch { return undefined; }
}
@@ -276,8 +320,10 @@ export async function resolveProjectIdForCid(userId: string, cid?: string): Prom
}
/**
- * Persist a user-chosen workspace path for a given scope. The directory
- * must exist. Returns `{ ok: true, path }` or `{ ok: false, error }`.
+ * Persist a user-chosen workspace path for a given scope. Ordinary paths are
+ * validated on disk. A macOS TCC-sensitive path comes from NSOpenPanel and is
+ * persisted without another probe so selection itself does not cause a second
+ * authorization attempt. Returns `{ ok: true, path }` or `{ ok: false, error }`.
*/
export function setWorkspacePath(
userId: string,
@@ -286,18 +332,13 @@ export function setWorkspacePath(
): { ok: true; path: string } | { ok: false; error: string } {
const selection = _resolveWorkspaceSelection(dirPath);
const resolved = selection.path;
- const protectedSelection = selection.blocked;
- if (protectedSelection) {
- log.warn('refused privacy-protected workspace selection', {
- userId, projectId: projectId || '(default)', path: logPathRef(resolved), reason: protectedSelection.reason,
- });
- return { ok: false, error: t('errors.workspace_privacy_protected') };
- }
- try {
- const stat = fs.statSync(resolved);
- if (!stat.isDirectory()) return { ok: false, error: t('errors.path_not_dir') };
- } catch {
- return { ok: false, error: t('errors.dir_not_exists') };
+ if (!selection.macosTccSensitive) {
+ try {
+ const stat = fs.statSync(resolved);
+ if (!stat.isDirectory()) return { ok: false, error: t('errors.path_not_dir') };
+ } catch {
+ return { ok: false, error: t('errors.dir_not_exists') };
+ }
}
const cfg = readConfig(userId);
@@ -315,6 +356,7 @@ export function setWorkspacePath(
const next = _writeEntry(cfg, projectId, {
selectedPath: resolved,
recentPaths: recents.slice(0, MAX_RECENT),
+ ...(selection.macosTccSensitive ? { macosTccSensitive: true } : {}),
});
writeConfig(userId, next);
log.info('workspace path updated', { userId, projectId: projectId || '(default)', path: logPathRef(resolved) });
@@ -376,16 +418,15 @@ export function getWorkspaceInfo(userId: string, projectId?: string): {
} {
const cfg = readConfig(userId);
const entry = _readEntry(cfg, projectId);
- // This runs on renderer boot to paint the workspace chip. Do not touch
- // protected external directories here: macOS will surface TCC prompts for
- // paths like ~/Downloads even for a simple stat. Actual selection/use still
- // validates through setWorkspacePath/getWorkspacePath.
+ // This runs on renderer boot to paint the workspace chip. It uses configured
+ // strings only and never touches external directories.
const currentPath = _configuredDisplayPath(cfg, projectId);
- const selectedBlocked = entry.selectedPath ? _isWorkspaceSelectionBlocked(entry.selectedPath) : null;
- const isDefault = !entry.selectedPath || !!selectedBlocked;
+ const isDefault = !entry.selectedPath;
const recentPaths = (entry.recentPaths || [])
.filter((p) => p !== currentPath && p !== DEFAULT_USER_WORKSPACE)
- .filter((p) => !_isWorkspaceSelectionBlocked(p))
+ // Re-select protected recents through NSOpenPanel so the action carries
+ // fresh user intent instead of causing a passive filesystem probe.
+ .filter((p) => !_macosTccSensitiveWorkspacePath(p))
.slice(0, MAX_RECENT);
return {
currentPath,
@@ -399,7 +440,7 @@ export function getWorkspaceInfo(userId: string, projectId?: string): {
function _safeDirectoryPickerDefault(): string | undefined {
const abs = path.resolve(DEFAULT_USER_WORKSPACE);
- if (macosTccWorkspaceBlockedPath(abs)) return undefined;
+ if (_macosTccSensitiveWorkspacePath(abs)) return undefined;
try { fs.mkdirSync(abs, { recursive: true }); } catch { /* best-effort; stat below decides */ }
try { return fs.statSync(abs).isDirectory() ? abs : undefined; }
catch { return undefined; }
@@ -492,12 +533,9 @@ export async function openWorkspaceInFileManager(
const target = _effectivePath(cfg, projectId);
const fallbackUsed = !!configuredPath
&& path.resolve(configuredPath) !== path.resolve(target);
- try {
- const stat = fs.statSync(target);
- if (!stat.isDirectory()) return { ok: false, error: t('errors.target_not_dir') };
- } catch {
- return { ok: false, error: t('errors.dir_not_exists') };
- }
+ // This is an explicit user action. Delegate availability and directory
+ // handling to the OS instead of probing first: a preflight stat can trigger
+ // macOS Files & Folders authorization before Finder opens.
const err = await shell.openPath(target);
if (err) {
log.warn('failed to open workspace path', { userId, path: logPathRef(target), err });
diff --git a/src/main/features/video_studio_state.ts b/src/main/features/video_studio_state.ts
index 091aaa07..7c6df29f 100644
--- a/src/main/features/video_studio_state.ts
+++ b/src/main/features/video_studio_state.ts
@@ -395,6 +395,10 @@ export type VideoProductionActiveOperation = {
operation_id: string;
op: string;
input_hash?: string;
+ /** Effective renderer quality for draft/export. Kept separate from the
+ * authored-input hash because identical bytes can have different render
+ * costs and deterministic QA outcomes at different quality tiers. */
+ render_quality?: 'unset' | 'draft' | 'standard' | 'high';
stage: VideoProductionStage;
revision: number;
turn_id?: string;
@@ -408,6 +412,9 @@ export type VideoProductionOperationJournalEntry = {
operation_id: string;
op: string;
input_hash?: string;
+ /** Effective renderer quality for draft/export. Legacy entries omit it and
+ * therefore cannot prove that a new render is an identical attempt. */
+ render_quality?: 'unset' | 'draft' | 'standard' | 'high';
status: 'started' | 'passed' | 'failed' | 'interrupted';
turn_id?: string;
output_path?: string;
diff --git a/src/main/locales/en.json b/src/main/locales/en.json
index 2f748995..9b01ca48 100644
--- a/src/main/locales/en.json
+++ b/src/main/locales/en.json
@@ -2,7 +2,6 @@
"errors.not_utf8": "Text files must be UTF-8 encoded",
"errors.path_not_dir": "Selected path is not a directory",
"errors.dir_not_exists": "Directory does not exist",
- "errors.workspace_privacy_protected": "This folder is protected by macOS privacy controls. Choose a folder in the Orkas default workspace or a regular project directory.",
"errors.target_not_dir": "Target is not a directory",
"errors.cant_edit_index": "Cannot edit the system index directly",
"errors.cant_delete_index": "Cannot delete the system index",
@@ -161,6 +160,7 @@
"chat.agent_mutation_failed": "The Agent operation could not be completed. Please try again.",
"chat.agent_mutation_partial_failed": "Some Agent changes were completed, but others were not. Please retry the remaining changes.",
"chat.agent_edit_target_unavailable": "The Agent to edit could not be found. It may have been deleted. Confirm the target and try again.",
+ "chat.memory_write_unconfirmed": "Durable memory was not saved because no memory write completed. Please try the memory request again.",
"chat.dispatch_result_hidden": "Result handed back to the commander",
"chat.turn_limit_reached": "Reached the automatic step limit for this run and stopped. Send your message again to continue.",
"agent.cli.project_dir.label": "Project directory",
diff --git a/src/main/locales/ja.json b/src/main/locales/ja.json
index f4b9923f..2b753eff 100644
--- a/src/main/locales/ja.json
+++ b/src/main/locales/ja.json
@@ -2,7 +2,6 @@
"errors.not_utf8": "テキストファイルは UTF-8 エンコードである必要があります",
"errors.path_not_dir": "選択したパスはディレクトリではありません",
"errors.dir_not_exists": "ディレクトリが存在しません",
- "errors.workspace_privacy_protected": "このフォルダは macOS のプライバシー保護対象です。Orkas のデフォルトワークスペースまたは通常のプロジェクトディレクトリ内のフォルダを選択してください。",
"errors.target_not_dir": "対象はディレクトリではありません",
"errors.cant_edit_index": "システムインデックスを直接編集することはできません",
"errors.cant_delete_index": "システムインデックスを削除することはできません",
@@ -161,6 +160,7 @@
"chat.agent_mutation_failed": "エージェントの操作を完了できませんでした。もう一度お試しください。",
"chat.agent_mutation_partial_failed": "一部のエージェント変更は完了しましたが、残りは完了できませんでした。未完了の操作を再実行してください。",
"chat.agent_edit_target_unavailable": "編集対象のエージェントが見つかりません。削除された可能性があります。対象を確認してもう一度お試しください。",
+ "chat.memory_write_unconfirmed": "永続メモリは保存されませんでした。このターンではメモリへの書き込みが完了していません。メモリへの保存をもう一度依頼してください。",
"chat.dispatch_result_hidden": "結果は司令官に返されました",
"chat.turn_limit_reached": "今回の自動実行ステップ上限に達したため停止しました。続けるにはメッセージを再送してください。",
"agent.cli.project_dir.label": "プロジェクトディレクトリ",
diff --git a/src/main/locales/pt.json b/src/main/locales/pt.json
index 557c793c..a7494620 100644
--- a/src/main/locales/pt.json
+++ b/src/main/locales/pt.json
@@ -2,7 +2,6 @@
"errors.not_utf8": "Os arquivos de texto devem ser codificados em UTF-8",
"errors.path_not_dir": "O caminho selecionado não é um diretório",
"errors.dir_not_exists": "O diretório não existe",
- "errors.workspace_privacy_protected": "Esta pasta é protegida pelos controles de privacidade do macOS. Escolha uma pasta no espaço de trabalho padrão do Orkas ou em um diretório de projeto comum.",
"errors.target_not_dir": "O destino não é um diretório",
"errors.cant_edit_index": "Não é possível editar o índice do sistema diretamente",
"errors.cant_delete_index": "Não é possível excluir o índice do sistema",
@@ -161,6 +160,7 @@
"chat.agent_mutation_failed": "Não foi possível concluir a operação do agente. Tente novamente.",
"chat.agent_mutation_partial_failed": "Algumas alterações do agente foram concluídas, mas outras não. Tente novamente as alterações restantes.",
"chat.agent_edit_target_unavailable": "O agente a editar não foi encontrado. Ele pode ter sido excluído. Confirme o alvo e tente novamente.",
+ "chat.memory_write_unconfirmed": "A memória persistente não foi salva porque nenhuma gravação de memória foi concluída. Tente solicitar o salvamento novamente.",
"chat.dispatch_result_hidden": "Resultado entregue ao comandante",
"chat.turn_limit_reached": "Atingiu o limite automático de passos para esta execução e parou. Envie sua mensagem novamente para continuar.",
"agent.cli.project_dir.label": "Diretório do projeto",
diff --git a/src/main/locales/zh.json b/src/main/locales/zh.json
index 650453ed..f42bad6d 100644
--- a/src/main/locales/zh.json
+++ b/src/main/locales/zh.json
@@ -2,7 +2,6 @@
"errors.not_utf8": "文本类文件必须是 UTF-8 编码",
"errors.path_not_dir": "所选路径不是目录",
"errors.dir_not_exists": "目录不存在",
- "errors.workspace_privacy_protected": "这个文件夹属于 macOS 隐私保护范围。请在 Orkas 默认工作区或普通项目目录中选择一个文件夹。",
"errors.target_not_dir": "目标不是目录",
"errors.cant_edit_index": "不能直接编辑系统索引",
"errors.cant_delete_index": "不能删除系统索引",
@@ -161,6 +160,7 @@
"chat.agent_mutation_failed": "本次智能体操作未能完成,请重试。",
"chat.agent_mutation_partial_failed": "部分智能体更改已完成,其余内容未完成。请重试未完成的操作。",
"chat.agent_edit_target_unavailable": "未找到要编辑的智能体,可能已被删除。请确认目标后重试。",
+ "chat.memory_write_unconfirmed": "持久记忆未保存:本轮没有完成记忆写入。请重新发送记忆请求。",
"chat.dispatch_result_hidden": "结果已交回指挥官",
"chat.turn_limit_reached": "已达到本次自动执行的步数上限并已停止。如需继续,请重新发送消息。",
"agent.cli.project_dir.label": "项目目录",
diff --git a/src/main/model/client.ts b/src/main/model/client.ts
index 5eec3323..09b06047 100644
--- a/src/main/model/client.ts
+++ b/src/main/model/client.ts
@@ -234,6 +234,10 @@ export interface ChatOptions {
* and attaches a `artifacts[]` list to the assistant message so the
* renderer embeds each interactive web-app artifact in the bubble. */
onArtifactCreated?: (a: { id: string; title: string }) => void;
+ /** Fired only after the custom-connector manager has durably accepted a
+ * user-confirmed server. Group chat uses the stable id to offer a review
+ * shortcut; the callback is not part of installation authorization. */
+ onCustomConnectorAdded?: (connectorId: string) => void;
/** Fired at turn start with each skill id that entered the system-prompt
* index, split by source system (`A.custom` / `A.platform` / `B`).
* `features/group_chat` buffers per turn and emits `skill_advertised`
diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.ts
index 9da7659a..8165c05b 100644
--- a/src/main/model/core-agent/client.ts
+++ b/src/main/model/core-agent/client.ts
@@ -1542,6 +1542,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
getPublishableOutputPaths,
hasProducedPath,
onArtifactCreated,
+ onCustomConnectorAdded,
onSkillAdvertised,
onSkillInvoked,
cacheRetention,
@@ -1811,6 +1812,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
...(getPublishableOutputPaths ? { getPublishableOutputPaths } : {}),
...(hasProducedPath ? { hasProducedPath } : {}),
...(onArtifactCreated ? { onArtifactCreated } : {}),
+ ...(onCustomConnectorAdded ? { onCustomConnectorAdded } : {}),
...(onSkillAdvertised ? { onSkillAdvertised } : {}),
...(onSkillInvoked ? { onSkillInvoked } : {}),
onNativeSearchInjected: (info) => {
diff --git a/src/main/model/core-agent/connector-meta-tools.ts b/src/main/model/core-agent/connector-meta-tools.ts
index af43d3c4..5f259185 100644
--- a/src/main/model/core-agent/connector-meta-tools.ts
+++ b/src/main/model/core-agent/connector-meta-tools.ts
@@ -58,6 +58,9 @@ export interface ConnectorMetaToolsOpts {
allowRuntimeRefresh?: boolean;
/** Only the commander may offer installation of a custom MCP server. */
allowCustomConnectorInstall?: boolean;
+ /** Host-side post-success hook. It may expose a review shortcut but must
+ * never authorize or perform the installation itself. */
+ onCustomConnectorAdded?: (connectorId: string) => void;
/** UI-only display metadata refreshed by the same visibility checks. */
connectorDisplayNameById?: Map<string, string>;
}
@@ -329,7 +332,7 @@ function createAddCustomConnectorTool(opts: ConnectorMetaToolsOpts & { cid: stri
return {
name: 'add_custom_connector',
description:
- 'Add a specific custom MCP server only when explicitly requested by the user. Installation requires user confirmation; approved servers are then used through list_connector_tools and call_connector_tool.',
+ 'Add a specific custom MCP server only when the user explicitly requested it and already supplied the exact non-secret configuration. Installation requires user confirmation. Never ask the user to paste a missing credential, API key, or token into chat; when protected input is still required, navigate to Connectors > Add MCP server instead.',
inputSchema: {
type: 'object',
properties: {
@@ -338,8 +341,8 @@ function createAddCustomConnectorTool(opts: ConnectorMetaToolsOpts & { cid: stri
type: 'object',
description:
'Either { kind: "streamable-http", url, headers? } for a remote server, or '
- + '{ kind: "stdio", command, args?, env? } for a local command. Put API keys in '
- + 'headers (http) or env (stdio).',
+ + '{ kind: "stdio", command, args?, env? } for a local command. Use only exact '
+ + 'values already supplied in the current user request; never invent or solicit secret values in chat.',
},
},
required: ['name', 'transport'],
@@ -362,15 +365,14 @@ function createAddCustomConnectorTool(opts: ConnectorMetaToolsOpts & { cid: stri
}
try {
const inst = await manager.addCustomInstance(opts.userId, { display_name: displayName, transport });
+ try { opts.onCustomConnectorAdded?.(inst.id); }
+ catch { /* post-success navigation is best-effort */ }
if (inst.status.kind === 'connected') {
return { content: `Connected "${inst.display_name}" (id: ${inst.id}). Its tools are now available via list_connector_tools({connector_id: "${inst.id}"}).` };
}
- const msg = (inst.status.kind === 'error' || inst.status.kind === 'degraded')
- ? inst.status.message
- : inst.status.kind;
- return { content: `Added "${inst.display_name}" (id: ${inst.id}) but it could not connect yet: ${msg}. The user can retry it from the Connectors panel.` };
+ return { content: `Added "${inst.display_name}" (id: ${inst.id}) but it could not connect yet. Ask the user to review the protected configuration in Connectors and retry there.` };
} catch (err) {
- return errResult('E_INSTALL_FAILED', `could not add connector: ${(err as Error).message}`);
+ return errResult('E_INSTALL_FAILED', 'could not add connector. Ask the user to review the protected Connectors form and retry there.');
}
},
};
diff --git a/src/main/model/core-agent/file-tools.ts b/src/main/model/core-agent/file-tools.ts
index c943d148..0680f03a 100644
--- a/src/main/model/core-agent/file-tools.ts
+++ b/src/main/model/core-agent/file-tools.ts
@@ -553,28 +553,60 @@ function createReadFileTool(
let sourceStat: fs.Stats;
try { sourceStat = fs.statSync(abs); }
catch (err) {
- const siblings = findUniquifySiblings(abs);
- log.warn('read_files not found', {
+ const osCode = typeof (err as NodeJS.ErrnoException)?.code === 'string'
+ ? (err as NodeJS.ErrnoException).code!
+ : '';
+ const detail = `${displayPath}: ${displayErrorMessage(err, abs, displayPath)}`;
+ if (osCode === 'ENOENT' || osCode === 'ENOTDIR') {
+ const siblings = osCode === 'ENOENT' ? findUniquifySiblings(abs) : [];
+ log.warn('read_files not found', {
+ user_id: maskId(opts.userId),
+ path: logPathRef(abs),
+ os_code: osCode,
+ sibling_count: siblings.length,
+ error: logErrorRef(err),
+ });
+ let content = errText('E_NOT_FOUND', detail);
+ content +=
+ '\n\n<missing-file-recovery>\n'
+ + 'Do not infer this file\'s contents. If the user supplied this exact path, ask for the correct accessible path or an attachment. '
+ + 'If you inferred the path, use search_files to locate the source before asking the user.\n'
+ + '</missing-file-recovery>';
+ if (siblings.length) {
+ content +=
+ '\n\n<file-renamed-earlier>\n'
+ + 'This name was uniquified earlier in this conversation. Existing variants in the same directory:\n'
+ + siblings.map((b) => ` - ${b}`).join('\n')
+ + '\nUse one of those paths instead — the original requested name was never written.\n'
+ + '</file-renamed-earlier>';
+ }
+ return { content, isError: true };
+ }
+ if (osCode === 'EACCES' || osCode === 'EPERM') {
+ log.warn('read_files permission denied', {
+ user_id: maskId(opts.userId),
+ path: logPathRef(abs),
+ os_code: osCode,
+ error: logErrorRef(err),
+ });
+ return {
+ content: errText(
+ 'E_PERMISSION_DENIED',
+ `${detail}\nos_code=${osCode}\nThe operating system denied access. Do not retry automatically or treat the file as missing; ask the user to grant access or choose an accessible file.`,
+ ),
+ isError: true,
+ };
+ }
+ log.warn('read_files stat failed', {
user_id: maskId(opts.userId),
path: logPathRef(abs),
- sibling_count: siblings.length,
+ ...(osCode ? { os_code: osCode } : {}),
error: logErrorRef(err),
});
- let content = errText('E_NOT_FOUND', `${displayPath}: ${displayErrorMessage(err, abs, displayPath)}`);
- content +=
- '\n\n<missing-file-recovery>\n'
- + 'Do not infer this file\'s contents. If the user supplied this exact path, ask for the correct accessible path or an attachment. '
- + 'If you inferred the path, use search_files to locate the source before asking the user.\n'
- + '</missing-file-recovery>';
- if (siblings.length) {
- content +=
- '\n\n<file-renamed-earlier>\n'
- + 'This name was uniquified earlier in this conversation. Existing variants in the same directory:\n'
- + siblings.map((b) => ` - ${b}`).join('\n')
- + '\nUse one of those paths instead — the original requested name was never written.\n'
- + '</file-renamed-earlier>';
- }
- return { content, isError: true };
+ return {
+ content: errText('E_READ_FAILED', `${detail}${osCode ? `\nos_code=${osCode}` : ''}`),
+ isError: true,
+ };
}
const kind = kindOf(abs);
diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.ts
index 6d07268e..bd8aa7a1 100644
--- a/src/main/model/core-agent/local-tools.ts
+++ b/src/main/model/core-agent/local-tools.ts
@@ -97,7 +97,7 @@ import {
} from './external-mutation-risk';
import { requestBashDecision } from './bash-permissions';
import { markdownToPdf, htmlToPdf } from '../../util/md-to-pdf';
-import { uniquifyPath, renderRenameSignal } from '../../util/uniquify-path';
+import { uniquifyPathForWrite, renderRenameSignal } from '../../util/uniquify-path';
import { isPathAllowed } from '../../util/path-sandbox';
import { kindOf } from '../../features/file_indexer';
import { getWorkspacePath } from '../../features/user_workspace';
@@ -4115,11 +4115,20 @@ function createWriteFileTool(opts: LocalToolsOpts): AgentTool {
log.warn('write_file scope reject', { user_id: maskId(opts.userId), path: logPathRef(inputAbs) });
return { content: scopeErr, isError: true };
}
- const { finalPath, renamed } = await uniquifyPath(inputAbs, isMineFor(opts));
+ const { finalPath, renamed, result } = await uniquifyPathForWrite(
+ inputAbs,
+ isMineFor(opts),
+ async (decision) => ({
+ ...decision,
+ result: await coreWriteFileTool.execute(
+ decision.finalPath !== inputAbs ? { ...input, path: decision.finalPath } : input,
+ ctx,
+ ),
+ }),
+ );
const rewritten = finalPath !== inputAbs
? { ...input, path: finalPath }
: input;
- const result = await coreWriteFileTool.execute(rewritten, ctx);
if (!result.isError) {
// Stamp the just-written bytes so a follow-up edit_file accepts an edit
// without an intervening read_files call (the model already knows the content
@@ -4757,28 +4766,43 @@ function createMarkdownToPdfTool(opts: LocalToolsOpts): AgentTool {
log.warn('markdown_to_pdf scope reject', { user_id: maskId(opts.userId), path: logPathRef(inputAbs) });
return { content: scopeErr, isError: true };
}
- const { finalPath, renamed } = await uniquifyPath(inputAbs, isMineFor(opts));
- if (finalPath !== inputAbs) {
- const finalScopeErr = await gateEditPath(opts, finalPath, ctx);
- if (finalScopeErr) {
- log.warn('markdown_to_pdf final scope reject', { user_id: maskId(opts.userId), path: logPathRef(finalPath) });
- return { content: finalScopeErr, isError: true };
- }
- }
- try {
- const footerText = producedDocumentFooterText({ userId: opts.userId, cid: opts.cid, source: 'markdown_to_pdf' });
- await markdownToPdf(String(input.markdown ?? ''), finalPath, {
- ...(typeof input.title === 'string' ? { title: input.title } : {}),
- ...(typeof input.pageSize === 'string' ? { pageSize: input.pageSize as any } : {}),
- ...(typeof input.landscape === 'boolean' ? { landscape: input.landscape } : {}),
- ...(footerText ? { footerText } : {}),
- });
- if (opts.onFileWritten) await opts.onFileWritten(finalPath);
- const base = `PDF written: ${finalPath}`;
- return { content: renamed ? `${base}${renderRenameSignal(inputAbs, finalPath)}` : base };
- } catch (err) {
- return { content: `Error generating PDF: ${(err as Error).message}`, isError: true };
+ const markdown = String(input.markdown ?? '');
+ const footerText = producedDocumentFooterText({ userId: opts.userId, cid: opts.cid, source: 'markdown_to_pdf' });
+ const renderOptions = {
+ ...(typeof input.title === 'string' ? { title: input.title } : {}),
+ ...(typeof input.pageSize === 'string' ? { pageSize: input.pageSize as any } : {}),
+ ...(typeof input.landscape === 'boolean' ? { landscape: input.landscape } : {}),
+ ...(footerText ? { footerText } : {}),
+ };
+ const outcome = await uniquifyPathForWrite(
+ inputAbs,
+ isMineFor(opts),
+ async (decision): Promise<
+ { kind: 'scope'; err: string }
+ | { kind: 'render'; err: string }
+ | ({ kind: 'ok' } & typeof decision)
+ > => {
+ if (decision.finalPath !== inputAbs) {
+ const finalScopeErr = await gateEditPath(opts, decision.finalPath, ctx);
+ if (finalScopeErr) return { kind: 'scope', err: finalScopeErr };
+ }
+ try {
+ await markdownToPdf(markdown, decision.finalPath, renderOptions);
+ } catch (err) {
+ return { kind: 'render', err: `Error generating PDF: ${(err as Error).message}` };
+ }
+ return { kind: 'ok', ...decision };
+ },
+ );
+ if (outcome.kind === 'scope') {
+ log.warn('markdown_to_pdf final scope reject', { user_id: maskId(opts.userId), path: logPathRef(inputAbs) });
+ return { content: outcome.err, isError: true };
}
+ if (outcome.kind === 'render') return { content: outcome.err, isError: true };
+ const { finalPath, renamed } = outcome;
+ if (opts.onFileWritten) await opts.onFileWritten(finalPath);
+ const base = `PDF written: ${finalPath}`;
+ return { content: renamed ? `${base}${renderRenameSignal(inputAbs, finalPath)}` : base };
},
};
}
@@ -4813,27 +4837,42 @@ function createHtmlToPdfTool(opts: LocalToolsOpts): AgentTool {
log.warn('html_to_pdf scope reject', { user_id: maskId(opts.userId), path: logPathRef(inputAbs) });
return { content: scopeErr, isError: true };
}
- const { finalPath, renamed } = await uniquifyPath(inputAbs, isMineFor(opts));
- if (finalPath !== inputAbs) {
- const finalScopeErr = await gateEditPath(opts, finalPath, ctx);
- if (finalScopeErr) {
- log.warn('html_to_pdf final scope reject', { user_id: maskId(opts.userId), path: logPathRef(finalPath) });
- return { content: finalScopeErr, isError: true };
- }
- }
- try {
- const footerText = producedDocumentFooterText({ userId: opts.userId, cid: opts.cid, source: 'html_to_pdf' });
- await htmlToPdf(String(input.html ?? ''), finalPath, {
- ...(typeof input.pageSize === 'string' ? { pageSize: input.pageSize as any } : {}),
- ...(typeof input.landscape === 'boolean' ? { landscape: input.landscape } : {}),
- ...(footerText ? { footerText } : {}),
- });
- if (opts.onFileWritten) await opts.onFileWritten(finalPath);
- const base = `PDF written: ${finalPath}`;
- return { content: renamed ? `${base}${renderRenameSignal(inputAbs, finalPath)}` : base };
- } catch (err) {
- return { content: `Error generating PDF: ${(err as Error).message}`, isError: true };
+ const html = String(input.html ?? '');
+ const footerText = producedDocumentFooterText({ userId: opts.userId, cid: opts.cid, source: 'html_to_pdf' });
+ const renderOptions = {
+ ...(typeof input.pageSize === 'string' ? { pageSize: input.pageSize as any } : {}),
+ ...(typeof input.landscape === 'boolean' ? { landscape: input.landscape } : {}),
+ ...(footerText ? { footerText } : {}),
+ };
+ const outcome = await uniquifyPathForWrite(
+ inputAbs,
+ isMineFor(opts),
+ async (decision): Promise<
+ { kind: 'scope'; err: string }
+ | { kind: 'render'; err: string }
+ | ({ kind: 'ok' } & typeof decision)
+ > => {
+ if (decision.finalPath !== inputAbs) {
+ const finalScopeErr = await gateEditPath(opts, decision.finalPath, ctx);
+ if (finalScopeErr) return { kind: 'scope', err: finalScopeErr };
+ }
+ try {
+ await htmlToPdf(html, decision.finalPath, renderOptions);
+ } catch (err) {
+ return { kind: 'render', err: `Error generating PDF: ${(err as Error).message}` };
+ }
+ return { kind: 'ok', ...decision };
+ },
+ );
+ if (outcome.kind === 'scope') {
+ log.warn('html_to_pdf final scope reject', { user_id: maskId(opts.userId), path: logPathRef(inputAbs) });
+ return { content: outcome.err, isError: true };
}
+ if (outcome.kind === 'render') return { content: outcome.err, isError: true };
+ const { finalPath, renamed } = outcome;
+ if (opts.onFileWritten) await opts.onFileWritten(finalPath);
+ const base = `PDF written: ${finalPath}`;
+ return { content: renamed ? `${base}${renderRenameSignal(inputAbs, finalPath)}` : base };
},
};
}
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index f12c5d68..cab75bb0 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -242,6 +242,8 @@ export interface BuildRunnerParams {
/** Stable inbound message id used as the exclusive upper bound for
* current-conversation history tools. */
historyBoundaryMessageId?: string;
+ /** Host-side post-success hook for a user-confirmed custom Connector. */
+ onCustomConnectorAdded?: (connectorId: string) => void;
/** Current real user text, used by tools that must bind an approval action
* to explicit user intent rather than merely to the existence of a turn. */
userMessage?: string;
@@ -1052,6 +1054,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
...(params.cid ? { cid: params.cid } : {}),
...(params.richSteerEnabled ? { allowRuntimeRefresh: true } : {}),
...(isCommander ? { allowCustomConnectorInstall: true } : {}),
+ ...(params.onCustomConnectorAdded ? { onCustomConnectorAdded: params.onCustomConnectorAdded } : {}),
},
exposure === 'discover+block' ? 'discover' : 'full',
)
@@ -1193,10 +1196,11 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
: [
'read_files',
'tool_result',
- // Global Skills are deliberately absent from the initial file scope.
- // Commander needs this small discovery gate active so a successful
- // search can grant read access to only the returned Skill directories.
- ...(isCommander && availableToolNames.includes('skill_search') ? ['skill_search'] : []),
+ // App navigation is the one resident Commander support affordance:
+ // it is broadly useful, closed-set, and remains side-effect-free
+ // until the user clicks the staged card. Skill discovery and app
+ // diagnosis stay behind their focused Management child groups.
+ ...(isCommander && availableToolNames.includes('open_app_view') ? ['open_app_view'] : []),
...(params.onOutputsPublished ? ['publish_outputs'] : []),
],
restoredState: session.getToolSurfaceState(),
diff --git a/src/main/model/core-agent/skill-registry.ts b/src/main/model/core-agent/skill-registry.ts
index 20683f47..17a9eb86 100644
--- a/src/main/model/core-agent/skill-registry.ts
+++ b/src/main/model/core-agent/skill-registry.ts
@@ -666,7 +666,7 @@ export function openSkillReadRoots(uid: string): string[] {
* and keeping them search-only with no count keeps the cache prefix stable. */
const OPEN_TIER_SKILL_HINT =
'More skills may be available from your global skill folders — these are NOT listed '
- + 'above. Call the `skill_search` tool with a capability query to find them, then '
+ + 'above. Load `management.skills`, call `skill_search` with a capability query, then '
+ '`read_files` the returned run-scoped Skill ref before invoking.';
const OPEN_SEARCH_DEFAULT_LIMIT = 5;
@@ -1136,7 +1136,7 @@ export async function getSystemSkillsPromptBlock(
'',
'System skills are product protocols. They are not marketplace or custom skills.',
'',
- 'Match the whole request against every description. Before other work, read the smallest complete set of matching SKILL.md files; never load nonmatches.',
+ 'Treat each description as an activation contract. Decide from the whole request\'s intended outcome and context, not keyword overlap. Before answering or calling another tool, read the smallest complete set whose use conditions apply; never load nonmatches.',
'',
'Read one match:',
runtimeRefBySpec
diff --git a/src/main/model/core-agent/tool-catalog-revision.ts b/src/main/model/core-agent/tool-catalog-revision.ts
index e8db2a8f..4a614201 100644
--- a/src/main/model/core-agent/tool-catalog-revision.ts
+++ b/src/main/model/core-agent/tool-catalog-revision.ts
@@ -5,4 +5,4 @@
* it as their current-state oracle without pulling the Electron runtime or the
* tool catalog's logger/path dependency chain into model-eval processes.
*/
-export const TOOL_CATALOG_REVISION = '10';
+export const TOOL_CATALOG_REVISION = '12';
diff --git a/src/main/model/core-agent/tool-catalog.ts b/src/main/model/core-agent/tool-catalog.ts
index 304f6a7e..007b77d3 100644
--- a/src/main/model/core-agent/tool-catalog.ts
+++ b/src/main/model/core-agent/tool-catalog.ts
@@ -35,6 +35,10 @@ export type ToolGroupId =
| 'context'
| 'orchestration'
| 'management'
+ | 'management.app'
+ | 'management.skills'
+ | 'management.marketplace'
+ | 'management.automation'
| 'runtime';
export interface ToolGroupEntry {
@@ -91,7 +95,11 @@ export const TOOL_GROUPS: readonly ToolGroupEntry[] = [
{ id: 'connectors', title: 'Connectors', summary: 'Discover and call enabled third-party connector actions.', activation: 'loadable', agentDependency: true },
{ id: 'context', title: 'Context', summary: 'Conversation, plan, memory, and project context managed by the host.', activation: 'host-managed', agentDependency: false },
{ id: 'orchestration', title: 'Orchestration', summary: 'Commander delegation, handoff, and anonymous worker controls.', activation: 'host-managed', agentDependency: false },
- { id: 'management', title: 'Management', summary: 'Skill, marketplace, and automation management controls.', activation: 'loadable', agentDependency: false },
+ { id: 'management', title: 'Management', summary: 'App support, Skill, marketplace, and automation management controls.', activation: 'loadable', agentDependency: false },
+ { id: 'management.app', title: 'App support', summary: 'Navigate supported Orkas screens and inspect sanitized app health.', parent: 'management', activation: 'loadable', agentDependency: false },
+ { id: 'management.skills', title: 'Skill management', summary: 'Discover global-folder Skills or import a user-requested Skill package.', parent: 'management', activation: 'loadable', agentDependency: false },
+ { id: 'management.marketplace', title: 'Marketplace management', summary: 'Search the Marketplace and request a confirmed installation.', parent: 'management', activation: 'loadable', agentDependency: false },
+ { id: 'management.automation', title: 'Automation management', summary: 'Inspect scheduled and recurring automation tasks.', parent: 'management', activation: 'loadable', agentDependency: false },
{ id: 'runtime', title: 'Runtime', summary: 'Tool-surface, learned-skill, and oversized-result runtime controls.', activation: 'host-managed', agentDependency: false },
] as const;
@@ -179,12 +187,14 @@ export const TOOL_CATALOG: readonly ToolCatalogEntry[] = [
{ name: 'hand_off_to', loadGroups: ['orchestration'], summary: 'Transfer terminal ownership to another Agent.' },
{ name: 'run_worker', loadGroups: ['orchestration'], summary: 'Run an anonymous private worker.' },
- { name: 'skill_search', loadGroups: ['management'], summary: 'Search available open-tier skills.' },
- { name: 'import_skill_package', loadGroups: ['management'], summary: 'Import a user-requested skill package.' },
+ { name: 'skill_search', loadGroups: ['management.skills'], summary: 'Search available global-folder skills.' },
+ { name: 'import_skill_package', loadGroups: ['management.skills'], summary: 'Import a user-requested skill package.' },
{ name: 'skill_manage', loadGroups: ['runtime'], summary: 'Manage an Agent-owned learned skill.' },
- { name: 'marketplace_search', loadGroups: ['management'], summary: 'Search the marketplace.' },
- { name: 'marketplace_request_install', loadGroups: ['management'], summary: 'Request a user-confirmed marketplace installation.' },
- { name: 'auto_tasks_list', loadGroups: ['management'], summary: 'List automation tasks.' },
+ { name: 'marketplace_search', loadGroups: ['management.marketplace'], summary: 'Search the marketplace.' },
+ { name: 'marketplace_request_install', loadGroups: ['management.marketplace'], summary: 'Request a user-confirmed marketplace installation.' },
+ { name: 'auto_tasks_list', loadGroups: ['management.automation'], summary: 'List automation tasks.' },
+ { name: 'open_app_view', loadGroups: ['management.app'], summary: 'Stage a click-to-open navigation card to an app surface.' },
+ { name: 'app_health', loadGroups: ['management.app'], summary: 'Read-only sanitized app diagnosis snapshot.' },
{ name: 'tool_load', loadGroups: ['runtime'], summary: 'Activate one or more loadable tool groups.' },
{ name: 'tool_result', loadGroups: ['runtime'], summary: 'Search, aggregate, or page a persisted oversized tool result.' },
diff --git a/src/main/model/core-agent/video-studio-tool.ts b/src/main/model/core-agent/video-studio-tool.ts
index 294e0a57..08a33dad 100644
--- a/src/main/model/core-agent/video-studio-tool.ts
+++ b/src/main/model/core-agent/video-studio-tool.ts
@@ -5860,6 +5860,7 @@ async function startVideoStudioOperationState(input: {
statePath: string;
compositionDirAbs: string;
op: string;
+ renderQuality?: 'unset' | RenderQuality;
turnId?: string;
outputPath?: string;
reportPath?: string;
@@ -5875,6 +5876,7 @@ async function startVideoStudioOperationState(input: {
...(artifacts.composition_signature
? { input_hash: artifacts.composition_signature }
: {}),
+ ...(input.renderQuality ? { render_quality: input.renderQuality } : {}),
stage: state.stage,
revision: state.revision + 1,
...(input.turnId ? { turn_id: input.turnId } : {}),
@@ -5891,6 +5893,7 @@ async function startVideoStudioOperationState(input: {
...(artifacts.composition_signature
? { input_hash: artifacts.composition_signature }
: {}),
+ ...(input.renderQuality ? { render_quality: input.renderQuality } : {}),
status: 'started' as const,
...(input.turnId ? { turn_id: input.turnId } : {}),
...(input.outputPath ? { output_path: input.outputPath } : {}),
@@ -11739,9 +11742,21 @@ export function createVideoStudioTool(opts: VideoStudioToolOpts): AgentTool {
const renderInputSignature = (op === 'composition.draft' || op === 'composition.export')
? (await videoProductionArtifacts(compositionDirAbs)).composition_signature || 'missing-signature'
: '';
+ // The breaker must identify the render request, not just its authored
+ // bytes. A failed preview-quality delivery does not predict a failed
+ // high-quality delivery (and vice versa). `unset` is deliberate for
+ // draft: the renderer gives an omitted quality its own fps/CRF profile.
+ const renderQualityIdentity: 'unset' | RenderQuality | undefined = op === 'composition.export'
+ ? quality ?? 'high'
+ : op === 'composition.draft'
+ ? quality ?? 'unset'
+ : undefined;
const identicalRenderFailures = (stateBefore.operation_journal || []).filter(
(entry) => entry.op === op
&& entry.input_hash === renderInputSignature
+ // Legacy entries carry no quality. Fail open because they cannot
+ // prove the current render request is actually identical.
+ && entry.render_quality === renderQualityIdentity
&& entry.status === 'failed'
&& entry.consumes_same_input_attempt === true,
);
@@ -11771,6 +11786,7 @@ export function createVideoStudioTool(opts: VideoStudioToolOpts): AgentTool {
next_action: 'repair_inputs_then_retry_render',
operation_journal_evidence: {
input_hash: renderInputSignature,
+ render_quality: renderQualityIdentity,
same_input_attempts: identicalRenderAttempts,
...(identicalQaVerdicts ? { same_input_deterministic_qa_failures: identicalQaVerdicts } : {}),
durable: true,
@@ -11800,6 +11816,7 @@ export function createVideoStudioTool(opts: VideoStudioToolOpts): AgentTool {
statePath: gateStatePath,
compositionDirAbs,
op,
+ ...(renderQualityIdentity ? { renderQuality: renderQualityIdentity } : {}),
turnId: opts.turnId,
...(outputAbsPath ? { outputPath: outputAbsPath } : {}),
...(effectiveReportPath ? { reportPath: effectiveReportPath } : {}),
diff --git a/src/main/prompts/chat_commander.md b/src/main/prompts/chat_commander.md
index 55860338..a715ac44 100644
--- a/src/main/prompts/chat_commander.md
+++ b/src/main/prompts/chat_commander.md
@@ -18,6 +18,8 @@ You are the **commander** of this group chat: an orchestrator with a strong gene
Use injected memory and project instructions directly as read-only context. Durable memory or project-instruction mutations are owned by the matching System Skill.
+For a request to create, change, or remove durable state, select and read that System Skill before answering or calling its mutation tool. Decide from the intended future effect, not exact phrasing.
+
Never persist current task progress, temporary plans, one-off status, or TODO/dependency state.
$project_tasks_rules
diff --git a/src/main/prompts/chat_prompt_composer.ts b/src/main/prompts/chat_prompt_composer.ts
index 9d5062f4..239bb480 100644
--- a/src/main/prompts/chat_prompt_composer.ts
+++ b/src/main/prompts/chat_prompt_composer.ts
@@ -190,12 +190,18 @@ export function buildPlanInteractionHint(interactive: boolean): string {
].join('\n');
}
-/** Build the final response-language instruction without loading user state. */
+/** Build the final response-language precedence without loading user state. */
export function buildLanguageDirectiveText(languageName: string): string {
return [
'## User language',
'',
- `User UI language: **${languageName}**. Write all human-readable prose in ${languageName}, including replies, status text, form labels, plan titles/inputs, and natural-language text inside XML/JSON fields.`,
+ `Fallback UI language: **${languageName}**.`,
+ '',
+ "Choose the response language in this order: (1) a current explicit user language request; (2) otherwise, the clear language of the user's latest substantive prose; (3) otherwise, the fallback UI language above.",
+ '',
+ 'Quoted text, code, file contents, proper nouns, and earlier assistant messages do not switch the response language.',
+ '',
+ 'Write all human-readable prose in the chosen language, including replies, status text, form labels, plan titles/inputs, and natural-language text inside XML/JSON fields.',
'',
'Keep protocol tokens unchanged: XML tag names, JSON keys, tool/skill ids or names, file paths, code, and `select` / `multiselect` `value` strings.',
'',
diff --git a/src/main/prompts/chat_skill_setup.md b/src/main/prompts/chat_skill_setup.md
index 80c72c24..57a7512d 100644
--- a/src/main/prompts/chat_skill_setup.md
+++ b/src/main/prompts/chat_skill_setup.md
@@ -27,20 +27,14 @@ This session is bound to the skill in Runtime injection.
---
-## Installing a skill from a URL — route first
+## Installing a skill from a URL — use the owning System Skill
-Mirror of the commander routing; keep in sync with `chat_commander.md`. Applies when this session's first message asks to install/import a skill from a URL.
+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.
-Judge the source before authoring:
-- A doc page / raw SKILL.md / a repo whose only payload is skill content → author a custom skill here (Mode B), as usual.
-- A runnable open-source repo that ships its own CLI or dependencies → it should be installed verbatim as an external package, not authored here.
-
-When it could go either way, or the choice changes the outcome, recommend one and state the trade-off in one line of plain outcome language — one follows the user across devices and their agents can use it; the other runs only on this machine and is managed in the package list — then wait for the user to confirm before installing. Never name internal mechanics to the user.
-
-### When the user picks the external-package route
-1. Install with the package CLI via `bash`, following the `package-installer` skill: run install first without dependency consent; if it reports pending dependencies, show the user the exact commands, get approval, then re-run with consent. Never run npm / pip yourself.
-2. Only after the install succeeds, end your reply with this marker on its own line: `<skill-as-package name="<installed-name>"/>`. It finalizes the import — the placeholder skill opened for this URL is removed and the view switches to the installed package. Emit it ONLY on a successful external-package install; never for the custom-skill route, and never before the install succeeded.
-3. Tell the user in plain outcome language that it is installed and where to manage it. Do NOT author a `SKILL.md` for this skill.
+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/main/util/macos-tcc.ts b/src/main/util/macos-tcc.ts
index 485dbeb5..4d495fde 100644
--- a/src/main/util/macos-tcc.ts
+++ b/src/main/util/macos-tcc.ts
@@ -83,14 +83,3 @@ export function macosTccSensitivePath(
}
return null;
}
-
-/**
- * Workspaces are long-lived execution roots: agents create, stat, list, and
- * reveal files there across turns. Even if each individual scan is guarded,
- * placing the workspace under a macOS TCC root can still trigger privacy
- * prompts during normal writes or shell commands. Treat these paths as
- * ineligible workspace/default-picker roots.
- */
-export function macosTccWorkspaceBlockedPath(targetPath: string): TccSensitivePathResult | null {
- return macosTccSensitivePath(targetPath, { recursive: true });
-}
diff --git a/src/main/util/uniquify-path.ts b/src/main/util/uniquify-path.ts
index 47252b94..969540ee 100644
--- a/src/main/util/uniquify-path.ts
+++ b/src/main/util/uniquify-path.ts
@@ -27,6 +27,8 @@
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
+import { fileEditLock } from './locks';
+
export interface UniquifyResult {
finalPath: string;
renamed: boolean;
@@ -53,6 +55,29 @@ export async function uniquifyPath(
throw new Error(`uniquifyPath: exhausted ${MAX_ATTEMPTS} attempts under ${dir}`);
}
+/** Decide the unique path AND perform the write under one per-path mutex.
+ *
+ * `uniquifyPath` alone is check-then-act: between its existence probe and the
+ * caller's eventual write, a concurrent writer aimed at the same path (two
+ * parallel agent turns sharing one conversation workspace) passes the same
+ * probe, and both write one file — the silent overwrite this module exists to
+ * prevent. Serializing probe+write on the mutex keyed by the REQUESTED path
+ * (the only key both contenders share up front) makes the loser's probe see
+ * the winner's file and suffix correctly.
+ *
+ * `write` runs with the lock held, so keep it to the write itself — do not
+ * run model calls or long renders inside unless the file only materializes
+ * there. It must not acquire `fileEditLock` on the same path again. */
+export async function uniquifyPathForWrite<T>(
+ absPath: string,
+ isMine: (p: string) => boolean,
+ write: (decision: UniquifyResult) => Promise<T>,
+): Promise<T> {
+ return fileEditLock(path.resolve(absPath)).runExclusive(async () => (
+ write(await uniquifyPath(absPath, isMine))
+ ));
+}
+
async function pathExists(p: string): Promise<boolean> {
try {
await fs.access(p);
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index 43d95b55..229a9632 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -333,6 +333,11 @@
"chat.conv_del_confirm": "Delete this task?",
"chat.loading": "Loading...",
"chat.load_failed": "Load failed: {msg}",
+ "chat.app_nav_open": "Open page: {name}",
+ "chat.app_nav_create": "Create in {name}",
+ "chat.app_nav_add_custom": "Add MCP server",
+ "chat.app_nav_configure": "Configure in {name}",
+ "chat.app_nav_failed": "Couldn’t open this page. Try again or open it from the sidebar.",
"chat.turn_nav_label": "Conversation turns",
"chat.turn_nav_item": "Go to turn {n} of {total}",
"chat.turn_nav_fallback": "Turn {n}",
diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.json
index 0db15e01..47c5be21 100644
--- a/src/renderer/locales/ja.json
+++ b/src/renderer/locales/ja.json
@@ -321,6 +321,11 @@
"chat.conv_del_confirm": "このタスクを削除しますか?",
"chat.loading": "読み込み中...",
"chat.load_failed": "読み込みに失敗しました: {msg}",
+ "chat.app_nav_open": "ページを開く:{name}",
+ "chat.app_nav_create": "{name}で作成",
+ "chat.app_nav_add_custom": "MCP サーバーを追加",
+ "chat.app_nav_configure": "{name}で設定",
+ "chat.app_nav_failed": "このページを開けませんでした。もう一度試すか、サイドバーから開いてください。",
"chat.turn_nav_label": "会話ターンの移動",
"chat.turn_nav_item": "全 {total} ターン中 {n} ターン目へ移動",
"chat.turn_nav_fallback": "ターン {n}",
diff --git a/src/renderer/locales/pt.json b/src/renderer/locales/pt.json
index faacd6cc..fdce9a0a 100644
--- a/src/renderer/locales/pt.json
+++ b/src/renderer/locales/pt.json
@@ -329,6 +329,11 @@
"chat.conv_del_confirm": "Excluir esta tarefa?",
"chat.loading": "Carregando...",
"chat.load_failed": "Falha no carregamento: {msg}",
+ "chat.app_nav_open": "Abrir página: {name}",
+ "chat.app_nav_create": "Criar em {name}",
+ "chat.app_nav_add_custom": "Adicionar servidor MCP",
+ "chat.app_nav_configure": "Configurar em {name}",
+ "chat.app_nav_failed": "Não foi possível abrir esta página. Tente novamente ou use a barra lateral.",
"chat.turn_nav_label": "Navegação por turnos da conversa",
"chat.turn_nav_item": "Ir para o turno {n} de {total}",
"chat.turn_nav_fallback": "Turno {n}",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index 236738d9..99d2c9a8 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -333,6 +333,11 @@
"chat.conv_del_confirm": "删除这个任务?",
"chat.loading": "加载中...",
"chat.load_failed": "加载失败: {msg}",
+ "chat.app_nav_open": "打开页面:{name}",
+ "chat.app_nav_create": "在{name}中创建",
+ "chat.app_nav_add_custom": "添加 MCP 服务器",
+ "chat.app_nav_configure": "在{name}中配置",
+ "chat.app_nav_failed": "无法打开该页面,请重试或从侧栏进入。",
"chat.turn_nav_label": "对话轮次定位",
"chat.turn_nav_item": "定位到第 {n} 轮,共 {total} 轮",
"chat.turn_nav_fallback": "第 {n} 轮",
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 59caec51..ad54053f 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -949,9 +949,17 @@ async function openAgentDetail(agentId, options = {}) {
: _captureAgentDetailReturnTarget();
const panel = document.getElementById('panel-agents');
panel?.classList.toggle('resource-detail-overlay', _agentDetailReturnTarget.view !== 'agents');
- await _showAgentsDetailView(agentId);
+ const opened = await _showAgentsDetailView(agentId);
+ if (opened === false) {
+ _agentDetailReturnTarget = null;
+ _showAgentsGridView();
+ return false;
+ }
+ return true;
}
+window.openAgentDetail = openAgentDetail;
+
function _isAgentDetailReturnTargetCurrent(target) {
if (!target || target.view !== currentView) return false;
if (target.view === 'conversation') return target.id === currentCid;
@@ -993,7 +1001,7 @@ async function _showAgentsDetailView(agentId) {
if (detail) detail.style.display = 'flex';
// Detail has a target-scoped API below. Do not refresh/enrich the complete
// Agent catalog merely to open one agent.json.
- await selectAgent(agentId, { refreshCliOptions: true });
+ return selectAgent(agentId, { refreshCliOptions: true });
}
async function refreshSelectedAgentDetail() {
@@ -1187,12 +1195,12 @@ async function selectAgent(agentId, { refreshCliOptions = false } = {}) {
if (_isCommanderAgent(agentId)) {
await _renderCommanderAgentDetail(false);
_resetAgentDetailScroll();
- return;
+ return true;
}
try {
const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}`);
const data = await res.json();
- if (!data.ok || !data.agent) return;
+ if (!data.ok || !data.agent) return false;
data.agent.source = _agentSource(data.agent.source);
await _maybeLoadAgentSkillNames(_agentSkillIds(data.agent), data.agent.agent_id, { refresh: false });
_selectedAgent = { id: data.agent.agent_id, name: data.agent.name, source: data.agent.source };
@@ -1203,8 +1211,10 @@ async function selectAgent(agentId, { refreshCliOptions = false } = {}) {
// (style.css:4190). Without resetting the inner two the previous
// agent's mid-scroll position bleeds into the next agent's view.
_resetAgentDetailScroll();
+ return true;
} catch (e) {
_agentsLog.error('load agent failed', e);
+ return false;
}
}
@@ -4000,6 +4010,9 @@ async function refreshAgentPickerContext(anchorId) {
async function _openAgentPicker(anchorBtn, entryPoint = 'unknown') {
const picker = document.getElementById('agent-picker');
if (!anchorBtn || !picker) return;
+ if (typeof _closeOtherComposerPopovers === 'function') {
+ _closeOtherComposerPopovers('recipient');
+ }
if (anchorBtn.id === 'new-chat-recipient-chip') {
_agentsTrackClick('new_chat_recipient_picker_open', {
entry_point: entryPoint === 'recipient_chip' || entryPoint === 'at_key'
@@ -4007,7 +4020,12 @@ async function _openAgentPicker(anchorBtn, entryPoint = 'unknown') {
: 'unknown',
});
}
+ const previousAnchorId = picker.dataset.anchorId || '';
+ if (previousAnchorId && previousAnchorId !== anchorBtn.id) {
+ _setAgentPickerAnchorOpen(document.getElementById(previousAnchorId), false);
+ }
picker.dataset.anchorId = anchorBtn.id;
+ _setAgentPickerAnchorOpen(anchorBtn, true);
const openSeq = ++_agentPickerOpenSeq;
_agentPickerLoadedTabs = new Set();
// Reset project scope synchronously before painting. For project-bound
@@ -4030,13 +4048,22 @@ async function _openAgentPicker(anchorBtn, entryPoint = 'unknown') {
}).catch(() => {});
}
-function _closeAgentPicker() {
+function _setAgentPickerAnchorOpen(anchor, open) {
+ if (!anchor) return;
+ anchor.classList.toggle('is-open', !!open);
+ anchor.setAttribute('aria-expanded', open ? 'true' : 'false');
+}
+
+function _closeAgentPicker({ preserveAtKey = false } = {}) {
const picker = document.getElementById('agent-picker');
- if (picker) picker.style.display = 'none';
- // NOTE: callers that close-without-selection (Esc / click-outside) must
- // also clear `_atKeyMark` — otherwise the next picker open would consume
- // a stale `@`. Selection callers leave the mark so _triggerPickerItem can
- // use it before clearing.
+ if (picker) {
+ _setAgentPickerAnchorOpen(document.getElementById(picker.dataset.anchorId || ''), false);
+ picker.style.display = 'none';
+ }
+ // A selection closes before routing the selected item, so it preserves the
+ // typed `@` marker just long enough for _triggerPickerItem to consume it.
+ // Every other close path owns cancellation and clears the marker here.
+ if (!preserveAtKey) _atKeyMark = null;
}
function _renderAgentPickerList(filterText) {
@@ -4395,7 +4422,7 @@ function _bindAgentPickerListItems(listEl, anchorId) {
el.addEventListener('click', async () => {
const sourceType = el.dataset.pickerSourceType === 'keyboard' ? 'keyboard' : 'mouse';
delete el.dataset.pickerSourceType;
- _closeAgentPicker();
+ _closeAgentPicker({ preserveAtKey: true });
await _triggerPickerItem(
el.dataset.kind || 'agent',
el.dataset.id,
@@ -4715,6 +4742,8 @@ function bindRecipientAnchor(chipId, inputId) {
const btn = document.getElementById(chipId);
if (btn && btn.dataset.bound !== '1') {
btn.dataset.bound = '1';
+ btn.setAttribute('aria-haspopup', 'dialog');
+ btn.setAttribute('aria-expanded', 'false');
btn.addEventListener('click', async (e) => {
e.stopPropagation();
_atKeyMark = null; // chip click is not a `@`-keystroke trigger
diff --git a/src/renderer/modules/auto.js b/src/renderer/modules/auto.js
index 9142b5ca..3b65c5af 100644
--- a/src/renderer/modules/auto.js
+++ b/src/renderer/modules/auto.js
@@ -2208,6 +2208,15 @@ if (typeof window !== 'undefined') {
window.loadAutoList = loadAutoList;
window.loadProjectAutoList = loadProjectAutoList;
window.openAutoTaskDialog = openAutoTaskDialog;
+ window.openAutoTaskById = async function openAutoTaskById(taskId) {
+ const id = String(taskId || '').trim();
+ if (!id) return false;
+ await loadAutoTasks();
+ const task = _autoTasks.find((candidate) => candidate && candidate.id === id);
+ if (!task) return false;
+ openAutoTaskDialog({ task });
+ return true;
+ };
window.refreshAutoProjectOptions = _autoRefreshProjectOptions;
window._autoUploadFilesFromComposer = _autoUploadFiles;
window._autoAttachLibraryFile = _autoAttachLibraryFile;
diff --git a/src/renderer/modules/bash_permission.js b/src/renderer/modules/bash_permission.js
index 682f4fd5..7ac6da7d 100644
--- a/src/renderer/modules/bash_permission.js
+++ b/src/renderer/modules/bash_permission.js
@@ -2,8 +2,9 @@
// in-process agent wants to run a command or access a path the classifier
// flagged as sensitive, main pushes `bash:permission` and this module shows an
// allow-once / deny choice, plus a task-scoped choice only when main marks the
-// category and actor eligible. Waiting for a human click is kept alive on the
-// main side with progress heartbeats; Renderer never widens main's boundary.
+// category and actor eligible, alongside the durable local-access mode switch.
+// Waiting for a human click is kept alive on the main side with progress
+// heartbeats; Renderer never widens main's operation-approval boundary.
//
// Requests queue FIFO so concurrent workers can't stack overlapping dialogs.
@@ -362,10 +363,11 @@ function _showBashPermissionModeDialog({
btn.addEventListener('click', () => finish(btn.dataset.id || 'deny'));
});
const cancelBtn = overlay.querySelector('[data-act="cancel"]');
+ const allowOnceBtn = overlay.querySelector('[data-id="allow_once"]');
cancelBtn.addEventListener('click', () => finish('deny'));
document.addEventListener('keydown', onKey, true);
document.addEventListener('click', onDocClick, true);
- setTimeout(() => cancelBtn.focus(), 0);
+ setTimeout(() => allowOnceBtn?.focus(), 0);
});
}
@@ -407,7 +409,7 @@ async function _showBashPermissionDialog(info) {
currentMode,
requestId,
allowRun: canAllowRun,
- showModeControl: !isSensitiveApproval,
+ showModeControl: true,
onPresented: () => {
if (presented) return;
presented = true;
@@ -425,7 +427,7 @@ async function _showBashPermissionDialog(info) {
return;
}
const choice = result && typeof result === 'object' ? result.choice : result;
- const selectedMode = !isSensitiveApproval && _bashIsMode(result && result.mode)
+ const selectedMode = _bashIsMode(result && result.mode)
? result.mode
: currentMode;
const requestedDecision = (choice === 'allow_once' || choice === 'allow_run' || choice === 'allow_always')
diff --git a/src/renderer/modules/composer-model-picker.js b/src/renderer/modules/composer-model-picker.js
index 2afc3bc4..2efccc13 100644
--- a/src/renderer/modules/composer-model-picker.js
+++ b/src/renderer/modules/composer-model-picker.js
@@ -20,6 +20,29 @@ const _COMPOSER_MODEL_PICKER_TARGETS = [
const _COMPOSER_RECIPIENT_TARGETS = ['new-chat', 'conversation', 'project', 'auto'];
+/** Keep the three composer-level pickers mutually exclusive. Their anchors
+ * stop click propagation, so independent outside-click listeners cannot close
+ * a picker when another composer control opens. Centralizing that transition
+ * also keeps every anchor's visual/ARIA open state in sync with its panel. */
+function _closeOtherComposerPopovers(activeKind) {
+ if (activeKind !== 'model' && typeof _closeComposerModelMenu === 'function') {
+ _closeComposerModelMenu();
+ }
+ if (activeKind !== 'recipient' && typeof _closeAgentPicker === 'function') {
+ _closeAgentPicker();
+ }
+ if (activeKind !== 'workspace') {
+ const workspaceMenu = document.getElementById('workspace-menu');
+ if (workspaceMenu) {
+ if (typeof workspaceMenu._closeWorkspaceMenu === 'function') {
+ workspaceMenu._closeWorkspaceMenu();
+ } else {
+ workspaceMenu.remove();
+ }
+ }
+ }
+}
+
function _composerRecipientForTarget(target) {
try {
if (target === 'auto') {
@@ -591,6 +614,7 @@ async function _toggleComposerModelMenu(anchor) {
_closeComposerModelMenu();
if (wasSameAnchor) return;
}
+ _closeOtherComposerPopovers('model');
await _refreshComposerModelEntries();
await _refreshComposerModelOptions(_composerModelEntries);
diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.js
index d7b98584..d3efee7e 100644
--- a/src/renderer/modules/connectors.js
+++ b/src/renderer/modules/connectors.js
@@ -377,6 +377,19 @@ function listUsableConnectorsForPicker() {
.sort((a, b) => (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base', numeric: true }));
}
+window.focusConnectorById = async function focusConnectorById(id) {
+ const targetId = String(id || '').trim();
+ if (!targetId) return false;
+ await loadConnectors();
+ const card = Array.from(document.querySelectorAll('.connector-card[data-id]'))
+ .find((candidate) => candidate.dataset.id === targetId);
+ if (!card) return false;
+ card.setAttribute('tabindex', '-1');
+ card.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ card.focus({ preventScroll: true });
+ return true;
+};
+
// Brand color hex per PC/docs/design/README §Surface E. Used as background
// for the 32×32 letter square in `_renderCatalogCard` when no `icon_svg` is
// shipped. Lookup is by `entry.id` (catalog id, stable across releases) with
diff --git a/src/renderer/modules/conversation-view-model.js b/src/renderer/modules/conversation-view-model.js
index d2f8f7b2..0df283ff 100644
--- a/src/renderer/modules/conversation-view-model.js
+++ b/src/renderer/modules/conversation-view-model.js
@@ -133,7 +133,7 @@
const SIDECAR_FIELDS = [
'attachments', 'produced', 'references', 'form', 'created_agents', 'created_skills',
- 'artifacts', 'marketplace_requests', 'plan_announcement', 'failure_kind', 'failure_code',
+ 'artifacts', 'marketplace_requests', 'app_nav_requests', 'plan_announcement', 'failure_kind', 'failure_code',
'model_text', 'source_message_id', 'unknown_mentions', 'mentions', 'to',
];
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index a398c606..7e4f33a9 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -2443,15 +2443,22 @@ function _clearQueueEditRecipient(cid) {
* current recipient may no longer be a valid agent for the new scope.
* Reset to commander silently — the user will see the chip flip on next
* render. Called from `projects.js` post project-pick. No-op for `commander`
- * recipients and for orphan contexts (pid empty). */
-async function validateRecipientAgainstProject(target, pid) {
+ * recipients and for orphan contexts (pid empty).
+ * `boundAgentIds` lets a caller that already holds this project's bindings
+ * (project detail load) skip the second IPC and decide inside its own
+ * load-sequence guard, so a slow response for a project the user already
+ * left cannot clear the chip of the one they are on. */
+async function validateRecipientAgainstProject(target, pid, boundAgentIds) {
const cur = _activeRecipient(target);
if (!cur || cur.kind !== 'agent') return;
if (!pid) return;
try {
- const res = await window.orkas.invoke('projects.bindings.list', { projectId: pid });
- if (!res || !res.ok) return;
- const bound = new Set((res.bindings && res.bindings.agents) || []);
+ let bound = boundAgentIds ? new Set(boundAgentIds) : null;
+ if (!bound) {
+ const res = await window.orkas.invoke('projects.bindings.list', { projectId: pid });
+ if (!res || !res.ok) return;
+ bound = new Set((res.bindings && res.bindings.agents) || []);
+ }
if (!bound.has(cur.id)) {
setChatRecipient(target, { kind: 'commander' });
_renderRecipientChip(target);
@@ -4270,6 +4277,7 @@ function _groupMsgToLegacy(gm) {
...(_normalizeCreatedSkills(gm) ? { created_skills: _normalizeCreatedSkills(gm) } : {}),
...(Array.isArray(gm.artifacts) && gm.artifacts.length ? { artifacts: gm.artifacts } : {}),
...(Array.isArray(gm.marketplace_requests) && gm.marketplace_requests.length ? { marketplace_requests: gm.marketplace_requests } : {}),
+ ...(Array.isArray(gm.app_nav_requests) && gm.app_nav_requests.length ? { app_nav_requests: gm.app_nav_requests } : {}),
...(gm.plan_announcement ? { _plan_announcement: true } : {}),
...(Array.isArray(gm.process) && gm.process.length ? { process: gm.process } : {}),
...(gm.turn_id ? { _turn_id: gm.turn_id } : {}),
@@ -7875,6 +7883,11 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
const bubble = msgDiv.querySelector('.chat-bubble');
if (bubble) _mountMarketplaceInstallRequests(bubble, msgDiv, message, opts);
}
+ // Commander navigation cards are inert until the user clicks one.
+ if (role === 'assistant' && Array.isArray(message.app_nav_requests) && message.app_nav_requests.length) {
+ const bubble = msgDiv.querySelector('.chat-bubble');
+ if (bubble) _mountAppNavRequests(bubble, message);
+ }
// Interactive web-app artifacts (assistant messages only) — sandboxed
// `<iframe>` over the `chat-app://` protocol, appended after the form so it
// reads as "reply text → embedded app". See chat-artifact.js.
@@ -8260,6 +8273,193 @@ function _renderMarketplaceInstallCard(card, req, cid, msgId) {
_hydrateMarketplaceRequestMeta(card, { ...req, kind }, cid, msgId);
}
+// ── Commander navigation cards (open_app_view) ──────────────────────────
+// Maps each staged surface_id to its renderer action plus a localized display
+// name reused from the owning surface's existing keys. Must cover exactly the
+// ids in src/main/features/group_chat/app_nav.ts — parity is pinned by
+// test/main/features/group_chat/app-nav-registry.test.ts.
+const _APP_NAV_SURFACES = {
+ 'settings.models': { nameKey: 'settings.section.models', fallback: 'Models & credentials', actions: ['open'], open: () => _appNavOpenSettingsTab('credentials') },
+ 'settings.general': { nameKey: 'settings.tab.general', fallback: 'General', actions: ['open'], open: () => _appNavOpenSettingsTab('general') },
+ 'settings.data': { nameKey: 'settings.tab.data', fallback: 'Data', actions: ['open'], open: () => _appNavOpenSettingsTab('data') },
+ connectors: {
+ nameKey: 'sidebar.connectors',
+ fallback: 'Connectors',
+ actions: ['open', 'add_custom', 'configure'],
+ open: (req) => _appNavOpenFeatureView('connectors', 'connectors', async () => {
+ if (req.action === 'add_custom') {
+ const addButton = document.getElementById('connectors-add-custom-btn');
+ if (!addButton) return false;
+ addButton.click();
+ } else if (req.action === 'configure' && typeof window.focusConnectorById === 'function') {
+ return window.focusConnectorById(req.target_id);
+ }
+ return req.action === 'open' || req.action === 'add_custom';
+ }),
+ },
+ library: { nameKey: 'sidebar.contexts', fallback: 'Library', actions: ['open'], open: () => { setView('contexts'); return true; } },
+ projects: {
+ nameKey: 'sidebar.projects',
+ fallback: 'Projects',
+ actions: ['open', 'create', 'configure'],
+ open: (req) => {
+ if (typeof window.openProjectsSurface !== 'function') return false;
+ return window.openProjectsSurface(req);
+ },
+ },
+ agents: {
+ nameKey: 'sidebar.agents',
+ fallback: 'AI Team',
+ actions: ['open', 'create', 'configure'],
+ open: (req) => _appNavOpenFeatureView('agents', 'agents', async () => {
+ if (req.action === 'create' && typeof window.openAgentModal === 'function') {
+ window.openAgentModal();
+ return true;
+ } else if (req.action === 'configure' && typeof window.openAgentDetail === 'function') {
+ return window.openAgentDetail(req.target_id);
+ }
+ return req.action === 'open';
+ }),
+ },
+ skills: {
+ nameKey: 'sidebar.skills',
+ fallback: 'Skills',
+ actions: ['open', 'create'],
+ open: (req) => _appNavOpenFeatureView('skills', 'skills', () => {
+ if (req.action === 'create' && typeof window.openSkillModal === 'function') {
+ window.openSkillModal();
+ return true;
+ }
+ return req.action === 'open';
+ }),
+ },
+ auto: {
+ nameKey: 'sidebar.auto',
+ fallback: 'Auto',
+ actions: ['open', 'create', 'configure'],
+ open: (req) => _appNavOpenFeatureView('auto', 'auto', async () => {
+ if (req.action === 'create' && typeof window.openAutoTaskDialog === 'function') {
+ window.openAutoTaskDialog({});
+ return true;
+ } else if (req.action === 'configure' && typeof window.openAutoTaskById === 'function') {
+ return window.openAutoTaskById(req.target_id);
+ }
+ return req.action === 'open';
+ }),
+ },
+ apps: { nameKey: 'sidebar.apps', fallback: 'My Apps', actions: ['open'], open: () => { setView('apps'); return true; } },
+ marketplace: {
+ nameKey: 'marketplace.title',
+ fallback: 'Marketplace',
+ actions: ['open'],
+ open: () => _appNavLoadFeature('marketplace', () => {
+ if (typeof openMarketplace !== 'function') return false;
+ openMarketplace('agent', { returnView: 'conversation' });
+ return true;
+ }),
+ },
+};
+
+function _appNavLoadFeature(feature, afterLoad) {
+ const load = typeof loadRendererFeature === 'function'
+ ? loadRendererFeature
+ : window.loadRendererFeature;
+ const ready = typeof load === 'function' ? Promise.resolve(load(feature)) : Promise.resolve();
+ return ready.then(async () => {
+ const result = await afterLoad?.();
+ if (result === false) throw new Error(`app navigation target unavailable: ${feature}`);
+ return true;
+ });
+}
+
+function _appNavOpenFeatureView(view, feature, afterLoad) {
+ setView(view);
+ return _appNavLoadFeature(feature, afterLoad);
+}
+
+function _appNavOpenSettingsTab(tab) {
+ setView('settings');
+ // Settings initializes lazily with the default Account tab; wait for the
+ // owning feature when necessary, then repeat on the next turn to win its
+ // initial-render race (same shape as model-guard's credentials CTA).
+ const activate = () => {
+ if (typeof window.activateSettingsTab !== 'function') return false;
+ window.activateSettingsTab(tab);
+ return true;
+ };
+ return _appNavLoadFeature('settings', async () => {
+ if (!activate()) return false;
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ return activate();
+ });
+}
+
+function _appNavReportFailure(surfaceId, action, error) {
+ try { _convLog.warn('app navigation failed', { surface_id: surfaceId, action, error: String(error?.message || error || '') }); } catch (_) {}
+ if (typeof uiToast !== 'function') return;
+ const key = 'chat.app_nav_failed';
+ const localized = t(key);
+ uiToast(localized && localized !== key
+ ? localized
+ : 'Could not open this page. Try again or open it from the sidebar.', { variant: 'error' });
+}
+
+function _mountAppNavRequests(host, message) {
+ if (!host || !message) return;
+ const requests = Array.isArray(message.app_nav_requests) ? message.app_nav_requests : [];
+ for (const req of requests) {
+ const surfaceId = req && typeof req.surface_id === 'string' ? req.surface_id : '';
+ const surface = _APP_NAV_SURFACES[surfaceId];
+ if (!surface) continue;
+ const action = req && typeof req.action === 'string' ? req.action : 'open';
+ const targetId = req && typeof req.target_id === 'string' ? req.target_id.trim() : '';
+ if (!surface.actions.includes(action)) continue;
+ if (action === 'configure' && !targetId) continue;
+ if (action !== 'configure' && targetId) continue;
+ if (targetId.length > 160 || /[\u0000-\u001f\u007f]/.test(targetId)) continue;
+ const requestKey = JSON.stringify([surfaceId, action, targetId]);
+ if (host.querySelector(`[data-app-nav="${CSS.escape(requestKey)}"]`)) continue;
+ let row = host.querySelector('.chat-app-nav-row');
+ if (!row) {
+ row = document.createElement('div');
+ row.className = 'chat-app-nav-row';
+ host.appendChild(row);
+ }
+ const name = _quickStartText(surface.nameKey, surface.fallback);
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'btn btn-sm chat-app-nav-btn';
+ btn.dataset.appNav = requestKey;
+ const labelKey = action === 'create'
+ ? 'chat.app_nav_create'
+ : action === 'add_custom'
+ ? 'chat.app_nav_add_custom'
+ : action === 'configure'
+ ? 'chat.app_nav_configure'
+ : 'chat.app_nav_open';
+ const label = t(labelKey, { name });
+ btn.textContent = label && label !== labelKey ? label : `Open ${name}`;
+ if (typeof window.uiIconHtml === 'function') {
+ const pageIcon = document.createElement('span');
+ pageIcon.className = 'chat-app-nav-btn-page-icon';
+ pageIcon.innerHTML = window.uiIconHtml('panel-list', 'ui-icon chat-app-nav-btn-page-icon-svg');
+ btn.appendChild(pageIcon);
+ }
+ btn.addEventListener('click', async () => {
+ btn.disabled = true;
+ try {
+ const opened = await surface.open({ surface_id: surfaceId, action, target_id: targetId });
+ if (opened === false) throw new Error('app navigation target unavailable');
+ } catch (error) {
+ _appNavReportFailure(surfaceId, action, error);
+ } finally {
+ btn.disabled = false;
+ }
+ });
+ row.appendChild(btn);
+ }
+}
+
function _mountMarketplaceInstallRequests(host, msgDiv, message, opts) {
const cid = opts.cid || currentCid;
if (!cid || !host || !message) return;
@@ -13180,6 +13380,10 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
_mountMarketplaceInstallRequests(bubble, ph, reqMessage, { cid });
}
}
+ if (Array.isArray(gm.app_nav_requests) && gm.app_nav_requests.length) {
+ const bubble = ph.querySelector('.chat-bubble');
+ if (bubble) _mountAppNavRequests(bubble, { app_nav_requests: gm.app_nav_requests });
+ }
// Interactive web-app artifacts (chat-app:// iframe). Idempotent — skips
// ids already mounted in this bubble.
diff --git a/src/renderer/modules/project-detail.js b/src/renderer/modules/project-detail.js
index cd9cbbb8..7ac23e53 100644
--- a/src/renderer/modules/project-detail.js
+++ b/src/renderer/modules/project-detail.js
@@ -180,9 +180,26 @@ async function loadProjectDetail(pid) {
_stopProjectKbEventSubscription();
}
try {
+ // The project composer's recipient chip is one ephemeral value shared by
+ // every project, so a pick made in another project — or an agent unbound
+ // while this page stayed open — can leave it aimed at an agent this project
+ // does not have. The send path turns that chip into an `@name` prefix and
+ // the bus resolves mentions against the global agent registry, so the stale
+ // pick would really dispatch an out-of-project agent into the new
+ // conversation. Same rule the auto-task dialog applies when its project
+ // scope changes (`auto.js::_autoClearRecipientIfOutsideProject`). Decided
+ // off the bindings response alone rather than the whole batch below:
+ // waiting for a large library's file tree would leave the stale target
+ // sendable for that long.
+ const bindingsCall = window.orkas.invoke('projects.bindings.list', { projectId: pid });
+ bindingsCall.then((res) => {
+ if (loadSeq !== _projectDetailLoadSeq || pid !== _projectDetailPid) return;
+ if (!res?.ok || typeof validateRecipientAgainstProject !== 'function') return;
+ validateRecipientAgainstProject('project', pid, (res.bindings && res.bindings.agents) || []);
+ }).catch(() => { /* the batch below owns the load failure */ });
const [getRes, listRes, filesRes, kbRes, instrRes, autoRes] = await Promise.all([
window.orkas.invoke('projects.get', { projectId: pid }),
- window.orkas.invoke('projects.bindings.list', { projectId: pid }),
+ bindingsCall,
window.orkas.invoke('projects.files.tree', { projectId: pid }),
window.orkas.invoke('projects.files.status', { projectId: pid, skipReconcile: true }).catch((err) => ({ ok: false, error: err?.message || String(err) })),
window.orkas.invoke('projects.instructions.get', { projectId: pid }).catch((err) => ({ ok: false, error: err?.message || String(err) })),
diff --git a/src/renderer/modules/projects.js b/src/renderer/modules/projects.js
index 722d5504..1e3fcae5 100644
--- a/src/renderer/modules/projects.js
+++ b/src/renderer/modules/projects.js
@@ -993,6 +993,38 @@ function getCommanderProjectIdName(pid) {
return (p && p.name) || '';
}
+// Commander navigation uses the same sidebar/create/detail workflows as a
+// manual click. The helper resolves business ids before opening a detail so a
+// stale conversation card cannot leave the user on an empty Project shell.
+window.openProjectsSurface = async function openProjectsSurface(request) {
+ request = request || {};
+ const action = String(request.action || 'open');
+ const toggle = document.getElementById('projects-section-toggle');
+ if (!toggle) return false;
+ if (toggle.getAttribute('aria-expanded') === 'false') toggle.click();
+
+ if (action === 'open') {
+ toggle.scrollIntoView?.({ block: 'nearest' });
+ toggle.focus?.();
+ return true;
+ }
+ if (action === 'create') {
+ _startProjectInlineCreate();
+ return _projectsInlineCreate === true;
+ }
+ if (action === 'configure') {
+ const projectId = String(request.target_id || '').trim();
+ if (!projectId) return false;
+ const projects = await loadProjects(true);
+ const exists = Array.isArray(projects)
+ && projects.some((project) => project && project.project_id === projectId);
+ if (!exists || typeof setView !== 'function') return false;
+ setView('project', projectId);
+ return true;
+ }
+ return false;
+};
+
// ── Init ────────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
diff --git a/src/renderer/modules/user-workspace.js b/src/renderer/modules/user-workspace.js
index b6f589b4..3712149c 100644
--- a/src/renderer/modules/user-workspace.js
+++ b/src/renderer/modules/user-workspace.js
@@ -324,6 +324,9 @@ function _showWorkspaceDropdown(anchor, target) {
else old.remove();
return;
}
+ if (typeof _closeOtherComposerPopovers === 'function') {
+ _closeOtherComposerPopovers('workspace');
+ }
const info = _wsInfoByTarget[target] || _wsInfoByTarget['conversation'];
diff --git a/src/renderer/style.css b/src/renderer/style.css
index 5844d0d7..7e64b40f 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -7482,6 +7482,75 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
color: var(--muted);
}
+/* Commander navigation card (open_app_view): a distinct action footer at the
+ bottom of the bubble; navigation still happens only on the user's click. */
+.chat-app-nav-row {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-top: 14px;
+ padding-top: 12px;
+ border-top: 1px solid color-mix(in srgb, var(--border) 72%, transparent);
+}
+.chat-app-nav-row .chat-app-nav-btn {
+ width: fit-content;
+ max-width: 100%;
+ min-height: 40px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: flex-start;
+ gap: 8px;
+ padding: 9px 12px;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ background: transparent;
+ color: var(--text);
+ font-size: 13px;
+ font-weight: 400;
+ line-height: 20px;
+ text-align: left;
+ box-shadow: none;
+ transition: transform 140ms ease, border-color 140ms ease, background 140ms ease, box-shadow 140ms ease;
+}
+.chat-app-nav-row .chat-app-nav-btn:hover {
+ border-color: color-mix(in srgb, var(--primary) 28%, var(--border));
+ background: transparent;
+ color: var(--text);
+ box-shadow: 0 7px 18px rgba(15, 23, 42, 0.08);
+ transform: translateY(-1px);
+}
+.chat-app-nav-row .chat-app-nav-btn:active {
+ box-shadow: 0 2px 7px rgba(15, 23, 42, 0.05);
+ transform: translateY(0);
+}
+.chat-app-nav-row .chat-app-nav-btn:focus-visible {
+ outline: 2px solid color-mix(in srgb, var(--primary) 42%, transparent);
+ outline-offset: 2px;
+}
+.chat-app-nav-btn-page-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+}
+.chat-app-nav-btn-page-icon {
+ order: -1;
+ width: 16px;
+ height: 20px;
+ flex: 0 0 16px;
+ background: transparent;
+ color: var(--primary);
+}
+.chat-app-nav-btn-page-icon-svg {
+ width: 16px;
+ height: 16px;
+}
+@media (prefers-reduced-motion: reduce) {
+ .chat-app-nav-row .chat-app-nav-btn {
+ transition: none;
+ }
+}
+
+
/* Marketplace install request card. Same inline-panel scale as input forms:
the user explicitly approves before any marketplace resource is installed. */
.chat-marketplace-request {
@@ -9227,9 +9296,11 @@ body.is-sidebar-resizing iframe { pointer-events: none; }
transition: background 0.15s, border-color 0.15s, color 0.15s;
}
-.chat-recipient-chip:hover {
- background: var(--surface-3);
- color: var(--text);
+.chat-recipient-chip:hover,
+.chat-recipient-chip.is-open {
+ background: var(--primary-soft);
+ border-color: rgba(91, 87, 214, 0.18);
+ color: var(--primary-text);
}
.chat-recipient-chip .chat-recipient-prefix {
diff --git a/test/e2e/chat_e2e_model_stream.spec.ts b/test/e2e/chat_e2e_model_stream.spec.ts
index bf80af60..978ecece 100644
--- a/test/e2e/chat_e2e_model_stream.spec.ts
+++ b/test/e2e/chat_e2e_model_stream.spec.ts
@@ -842,6 +842,7 @@ test.describe('real chat pipeline with a local model', () => {
const page = await sendNewChat(modelOrkas, 'E2E allow one command, then ask me again.');
const dialog = page.locator('.bash-permission-dialog');
await expect(dialog).toContainText('first.txt', { timeout: 20_000 });
+ await expect(dialog.locator('[data-id="allow_once"]')).toBeFocused();
await dialog.locator('[data-id="allow_once"]').click();
await expect.poll(() => existsSync(firstPath)).toBe(false);
diff --git a/test/e2e/professional_agents_e2e_smoke.spec.ts b/test/e2e/professional_agents_e2e_smoke.spec.ts
index b95de3ea..b040125f 100644
--- a/test/e2e/professional_agents_e2e_smoke.spec.ts
+++ b/test/e2e/professional_agents_e2e_smoke.spec.ts
@@ -370,9 +370,9 @@ test.describe('shipped professional agents', () => {
expect(request).toContain('image-router');
expect(request).toContain('image-manifest.json');
expect(request).toContain('project.export');
- expect(request).toContain('User UI language: **Chinese (简体中文)**');
- expect(request).toContain('Write all human-readable prose in Chinese (简体中文)');
- expect(request.lastIndexOf('User UI language: **Chinese (简体中文)**'))
+ expect(request).toContain('Fallback UI language: **Chinese (简体中文)**');
+ expect(request).toContain('Write all human-readable prose in the chosen language');
+ expect(request.lastIndexOf('Fallback UI language: **Chinese (简体中文)**'))
.toBeGreaterThan(request.lastIndexOf('chat prose follows the current UI language'));
});
diff --git a/test/e2e/protocol_e2e_registration_isolation.spec.ts b/test/e2e/protocol_e2e_registration_isolation.spec.ts
new file mode 100644
index 00000000..d0de4543
--- /dev/null
+++ b/test/e2e/protocol_e2e_registration_isolation.spec.ts
@@ -0,0 +1,52 @@
+import { execFileSync } from 'node:child_process';
+
+import { expect, test } from '@playwright/test';
+
+import { OrkasTestApp } from './fixtures/orkas';
+
+type ProtocolOwnerSnapshot = {
+ handler: string;
+ applicationPath: string;
+};
+
+const MACOS_PROTOCOL_OWNER_PROBE = [
+ 'import Foundation',
+ 'import AppKit',
+ 'import CoreServices',
+ 'let scheme = "orkas"',
+ 'let handler = LSCopyDefaultHandlerForURLScheme(scheme as NSString)?.takeRetainedValue() as String? ?? ""',
+ 'let callback = URL(string: "orkas://connectors/oauth/callback?exchange_code=cancelled")!',
+ 'let applicationPath = NSWorkspace.shared.urlForApplication(toOpen: callback)?.path ?? ""',
+ 'let data = try! JSONSerialization.data(withJSONObject: ["handler": handler, "applicationPath": applicationPath], options: [.sortedKeys])',
+ 'print(String(data: data, encoding: .utf8)!)',
+].join('; ');
+
+function macosProtocolOwner(): ProtocolOwnerSnapshot {
+ const output = execFileSync('/usr/bin/swift', ['-e', MACOS_PROTOCOL_OWNER_PROBE], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ timeout: 30_000,
+ });
+ return JSON.parse(output.trim()) as ProtocolOwnerSnapshot;
+}
+
+test.describe('system protocol registration isolation', () => {
+ test.skip(process.platform !== 'darwin', 'LaunchServices ownership is a macOS contract');
+
+ test('source E2E launch and relaunch leave the real connector protocol owner unchanged', async ({}, testInfo) => {
+ const before = macosProtocolOwner();
+ const app = new OrkasTestApp(testInfo);
+
+ try {
+ await app.launch();
+ expect(macosProtocolOwner()).toEqual(before);
+
+ await app.relaunch();
+ expect(macosProtocolOwner()).toEqual(before);
+ } finally {
+ await app.dispose();
+ }
+
+ expect(macosProtocolOwner()).toEqual(before);
+ });
+});
diff --git a/test/main/features/connectors/install-confirm.test.ts b/test/main/features/connectors/install-confirm.test.ts
index bf76f8b9..54177483 100644
--- a/test/main/features/connectors/install-confirm.test.ts
+++ b/test/main/features/connectors/install-confirm.test.ts
@@ -84,13 +84,14 @@ describe('connectors/install_confirm', () => {
});
describe('add_custom_connector tool', () => {
- async function buildTool() {
+ async function buildTool(onCustomConnectorAdded?: (connectorId: string) => void) {
const ic = await import('../../../../src/main/features/connectors/install_confirm');
const metaMod = await import('../../../../src/main/model/core-agent/connector-meta-tools');
const tools = await metaMod.createConnectorMetaTools({
userId: TEST_UID,
cid: 'c1',
allowCustomConnectorInstall: true,
+ ...(onCustomConnectorAdded ? { onCustomConnectorAdded } : {}),
}, 'full');
const tool = tools.find((t) => t.name === 'add_custom_connector');
return { ic, tool };
@@ -102,6 +103,15 @@ describe('add_custom_connector tool', () => {
expect(tool).toBeTruthy();
});
+ it('keeps missing secrets in the protected Connectors flow', async () => {
+ mockMcpClient();
+ const { tool } = await buildTool();
+ expect(tool?.description).toContain('Never ask the user to paste a missing credential');
+ const transport = (tool?.inputSchema as any)?.properties?.transport?.description || '';
+ expect(transport).toContain('never invent or solicit secret values in chat');
+ expect(transport).not.toContain('Put API keys in');
+ });
+
it('is NOT exposed in discover (agent-edit) mode', async () => {
mockMcpClient();
const metaMod = await import('../../../../src/main/model/core-agent/connector-meta-tools');
@@ -111,7 +121,8 @@ describe('add_custom_connector tool', () => {
it('installs only after the user approves the confirm dialog', async () => {
mockMcpClient();
- const { ic, tool } = await buildTool();
+ const added: string[] = [];
+ const { ic, tool } = await buildTool((connectorId) => added.push(connectorId));
const pushed: any[] = [];
ic._setBroadcastForTest((_ch, payload) => pushed.push(payload));
try {
@@ -130,6 +141,7 @@ describe('add_custom_connector tool', () => {
const conns = registry.load(TEST_UID).connections;
const custom = Object.values(conns).find((c) => c.origin === 'custom');
expect(custom).toBeTruthy();
+ expect(added).toEqual([custom?.id]);
} finally {
ic._setBroadcastForTest(null);
}
@@ -137,7 +149,8 @@ describe('add_custom_connector tool', () => {
it('does not install when the user declines', async () => {
mockMcpClient();
- const { ic, tool } = await buildTool();
+ const added: string[] = [];
+ const { ic, tool } = await buildTool((connectorId) => added.push(connectorId));
const pushed: any[] = [];
ic._setBroadcastForTest((_ch, payload) => pushed.push(payload));
try {
@@ -152,6 +165,7 @@ describe('add_custom_connector tool', () => {
const registry = await import('../../../../src/main/features/connectors/registry');
expect(Object.keys(registry.load(TEST_UID).connections)).toHaveLength(0);
+ expect(added).toEqual([]);
} finally {
ic._setBroadcastForTest(null);
}
diff --git a/test/main/features/group_chat/app-nav-registry.test.ts b/test/main/features/group_chat/app-nav-registry.test.ts
new file mode 100644
index 00000000..06b3fc6c
--- /dev/null
+++ b/test/main/features/group_chat/app-nav-registry.test.ts
@@ -0,0 +1,592 @@
+import { describe, expect, it } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as vm from 'node:vm';
+
+import {
+ APP_NAV_ACTIONS,
+ APP_NAV_SURFACES,
+ appNavSurfaceDescription,
+ findAppNavSurface,
+ validateAppNavRequest,
+} from '../../../../src/main/features/group_chat/app_nav';
+import { SCHEMA_DESCRIPTION_SOFT_BUDGET_CHARS } from '../../../../src/core-agent/src/tools';
+
+const RENDERER_CONVERSATION = path.join(
+ __dirname, '..', '..', '..', '..', 'src', 'renderer', 'modules', 'conversation.js',
+);
+const RENDERER_CONNECTORS = path.join(
+ __dirname, '..', '..', '..', '..', 'src', 'renderer', 'modules', 'connectors.js',
+);
+const RENDERER_AUTO = path.join(
+ __dirname, '..', '..', '..', '..', 'src', 'renderer', 'modules', 'auto.js',
+);
+const RENDERER_PROJECTS = path.join(
+ __dirname, '..', '..', '..', '..', 'src', 'renderer', 'modules', 'projects.js',
+);
+const RENDERER_STYLE = path.join(
+ __dirname, '..', '..', '..', '..', 'src', 'renderer', 'style.css',
+);
+
+function extractAssignedAsyncFunction(source: string, marker: string): string {
+ const markerAt = source.indexOf(marker);
+ expect(markerAt, `${marker} must exist`).toBeGreaterThan(-1);
+ const functionAt = source.indexOf('async function', markerAt);
+ expect(functionAt).toBeGreaterThan(markerAt);
+ const bodyAt = source.indexOf('{', functionAt);
+ let depth = 0;
+ for (let i = bodyAt; i < source.length; i += 1) {
+ if (source[i] === '{') depth += 1;
+ else if (source[i] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(functionAt, i + 1);
+ }
+ }
+ throw new Error(`unterminated assigned function: ${marker}`);
+}
+
+function rendererSurfaceIds(): string[] {
+ const source = fs.readFileSync(RENDERER_CONVERSATION, 'utf8');
+ const start = source.indexOf('const _APP_NAV_SURFACES = {');
+ expect(start, 'renderer executor map _APP_NAV_SURFACES must exist in conversation.js').toBeGreaterThan(-1);
+ const end = source.indexOf('\n};', start);
+ expect(end).toBeGreaterThan(start);
+ const block = source.slice(start, end);
+ const ids: string[] = [];
+ // Top-level executor keys only: quoted ('settings.models') or bare
+ // (connectors) identifiers immediately followed by an object literal.
+ for (const match of block.matchAll(/^\s{2}(?:'([^']+)'|([A-Za-z_][A-Za-z0-9_]*)):\s*\{/gm)) {
+ ids.push(match[1] || match[2]!);
+ }
+ return ids;
+}
+
+function rendererSurfaceActions(): Record<string, string[]> {
+ const source = fs.readFileSync(RENDERER_CONVERSATION, 'utf8');
+ const start = source.indexOf('const _APP_NAV_SURFACES = {');
+ const end = source.indexOf('\n};', start);
+ const block = source.slice(start, end);
+ const entries = [...block.matchAll(
+ /^\s{2}(?:'([^']+)'|([A-Za-z_][A-Za-z0-9_]*)):\s*\{/gm,
+ )];
+ return Object.fromEntries(entries.map((entry, index) => {
+ const id = entry[1] || entry[2]!;
+ const body = block.slice(entry.index ?? 0, entries[index + 1]?.index ?? block.length);
+ const actionList = body.match(/actions:\s*\[([^\]]*)\]/)?.[1] ?? '';
+ return [id, [...actionList.matchAll(/'([^']+)'/g)].map((match) => match[1])];
+ }));
+}
+
+function rendererNavHarness(failingFeature = '') {
+ const source = fs.readFileSync(RENDERER_CONVERSATION, 'utf8');
+ const start = source.indexOf('const _APP_NAV_SURFACES = {');
+ const end = source.indexOf('function _mountAppNavRequests', start);
+ const calls: string[] = [];
+ const context: any = {
+ calls,
+ setView: (view: string) => calls.push(`view:${view}`),
+ loadRendererFeature: async (feature: string) => {
+ calls.push(`load:${feature}`);
+ if (feature === failingFeature) throw new Error(`feature unavailable: ${feature}`);
+ if (feature === 'settings') {
+ context.window.activateSettingsTab = (tab: string) => calls.push(`settings:${tab}`);
+ }
+ },
+ openMarketplace: (kind: string) => calls.push(`marketplace:${kind}`),
+ setTimeout: (fn: () => void) => fn(),
+ document: {
+ getElementById: (id: string) => ({ click: () => calls.push(`click:${id}`) }),
+ },
+ window: {
+ openAgentModal: () => calls.push('agent:create'),
+ openAgentDetail: async (id: string) => { calls.push(`agent:configure:${id}`); return id !== 'missing'; },
+ openSkillModal: () => calls.push('skill:create'),
+ openAutoTaskDialog: () => calls.push('auto:create'),
+ openAutoTaskById: async (id: string) => { calls.push(`auto:configure:${id}`); return id !== 'missing'; },
+ focusConnectorById: async (id: string) => { calls.push(`connector:configure:${id}`); return id !== 'missing'; },
+ openProjectsSurface: async (request: Record<string, string>) => {
+ calls.push(`project:${request.action}:${request.target_id || ''}`);
+ return request.target_id !== 'missing';
+ },
+ },
+ };
+ vm.runInNewContext(
+ `${source.slice(start, end)}\nglobalThis.__appNavSurfaces = _APP_NAV_SURFACES;`,
+ context,
+ );
+ return {
+ calls,
+ surfaces: (context as unknown as {
+ __appNavSurfaces: Record<string, { open: (request: Record<string, string>) => Promise<void> }>;
+ }).__appNavSurfaces,
+ };
+}
+
+function rendererMountHarness(failingFeature = '') {
+ const source = fs.readFileSync(RENDERER_CONVERSATION, 'utf8');
+ const start = source.indexOf('const _APP_NAV_SURFACES = {');
+ const end = source.indexOf('function _mountMarketplaceInstallRequests', start);
+ const calls: string[] = [];
+ const toasts: Array<{ message: string; variant?: string }> = [];
+
+ class FakeElement {
+ className = '';
+ dataset: Record<string, string> = {};
+ children: FakeElement[] = [];
+ textContent = '';
+ type = '';
+ disabled = false;
+ private listeners = new Map<string, Array<() => void>>();
+
+ appendChild(child: FakeElement) { this.children.push(child); return child; }
+
+ addEventListener(type: string, listener: () => void) {
+ const listeners = this.listeners.get(type) ?? [];
+ listeners.push(listener);
+ this.listeners.set(type, listeners);
+ }
+
+ click() { for (const listener of this.listeners.get('click') ?? []) listener(); }
+
+ querySelector(selector: string): FakeElement | null {
+ const descendants = this.children.flatMap((child) => [child, ...child.descendants()]);
+ if (selector === '.chat-app-nav-row') {
+ return descendants.find((node) => node.className.split(/\s+/).includes('chat-app-nav-row')) ?? null;
+ }
+ const prefix = '[data-app-nav="';
+ if (selector.startsWith(prefix) && selector.endsWith('"]')) {
+ const key = selector.slice(prefix.length, -2);
+ return descendants.find((node) => node.dataset.appNav === key) ?? null;
+ }
+ return null;
+ }
+
+ private descendants(): FakeElement[] {
+ return this.children.flatMap((child) => [child, ...child.descendants()]);
+ }
+ }
+
+ const host = new FakeElement();
+ const context = {
+ CSS: { escape: (value: string) => value },
+ document: {
+ createElement: () => new FakeElement(),
+ getElementById: (id: string) => ({ click: () => calls.push(`click:${id}`) }),
+ },
+ window: {
+ focusConnectorById: async (id: string) => { calls.push(`connector:configure:${id}`); return id !== 'missing'; },
+ openAgentModal: () => calls.push('agent:create'),
+ openAgentDetail: async (id: string) => { calls.push(`agent:configure:${id}`); return id !== 'missing'; },
+ openSkillModal: () => calls.push('skill:create'),
+ openAutoTaskDialog: () => calls.push('auto:create'),
+ openAutoTaskById: async (id: string) => { calls.push(`auto:configure:${id}`); return id !== 'missing'; },
+ openProjectsSurface: async (request: Record<string, string>) => {
+ calls.push(`project:${request.action}:${request.target_id || ''}`);
+ return request.target_id !== 'missing';
+ },
+ },
+ setView: (view: string) => calls.push(`view:${view}`),
+ loadRendererFeature: async (feature: string) => {
+ calls.push(`load:${feature}`);
+ if (feature === failingFeature) throw new Error(`feature unavailable: ${feature}`);
+ },
+ openMarketplace: (kind: string) => calls.push(`marketplace:${kind}`),
+ setTimeout: (fn: () => void) => fn(),
+ _quickStartText: (_key: string, fallback: string) => fallback,
+ t: (key: string, values: { name?: string } = {}) => `${key}:${values.name ?? ''}`,
+ uiToast: (message: string, opts: { variant?: string } = {}) => {
+ toasts.push({ message, variant: opts.variant });
+ },
+ _convLog: { warn: () => {} },
+ };
+ vm.runInNewContext(
+ `${source.slice(start, end)}\nglobalThis.__mountAppNavRequests = _mountAppNavRequests;`,
+ context,
+ );
+ return {
+ calls,
+ toasts,
+ host,
+ mount: (context as unknown as {
+ __mountAppNavRequests: (target: FakeElement, message: Record<string, unknown>) => void;
+ }).__mountAppNavRequests,
+ };
+}
+
+describe('group_chat app_nav registry', () => {
+ it('declares unique surface ids with model-facing summaries', () => {
+ const ids = APP_NAV_SURFACES.map((s) => s.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ expect(ids.length).toBeGreaterThan(0);
+ for (const surface of APP_NAV_SURFACES) {
+ expect(surface.id).toMatch(/^[a-z][a-z0-9_.]*$/);
+ expect(surface.summary.length).toBeGreaterThan(10);
+ expect(surface.actions.length).toBeGreaterThan(0);
+ expect(surface.actions).toContain('open');
+ expect(new Set(surface.actions).size).toBe(surface.actions.length);
+ }
+ expect(new Set(APP_NAV_ACTIONS)).toEqual(new Set(['open', 'create', 'add_custom', 'configure']));
+ expect(findAppNavSurface('settings.models')?.id).toBe('settings.models');
+ expect(findAppNavSurface('not-a-surface')).toBeNull();
+ const schemaDescription = appNavSurfaceDescription();
+ expect(schemaDescription.length).toBeLessThanOrEqual(SCHEMA_DESCRIPTION_SOFT_BUDGET_CHARS);
+ for (const surface of APP_NAV_SURFACES) expect(schemaDescription).toContain(surface.id);
+ });
+
+ it('carries app_nav_requests through the renderer legacy conversion', () => {
+ // Every non-streaming render path (history load, history refresh, the
+ // append fallback when the live row is already finalized) rebuilds the
+ // bubble from `_groupMsgToLegacy`. A staged card that the conversion
+ // drops is invisible after the first repaint even though the persisted
+ // message carries it — reported 2026-08-26 on the onboarding
+ // "help me set up a model" flow.
+ const source = fs.readFileSync(RENDERER_CONVERSATION, 'utf8');
+ const start = source.indexOf('function _groupMsgToLegacy');
+ expect(start, '_groupMsgToLegacy must exist in conversation.js').toBeGreaterThan(-1);
+ const end = source.indexOf('\n}', start);
+ expect(end).toBeGreaterThan(start);
+ expect(source.slice(start, end)).toContain('app_nav_requests: gm.app_nav_requests');
+ });
+
+ it('labels the default open action as page navigation in every supported locale', () => {
+ const expected = {
+ en: 'Open page: {name}',
+ zh: '打开页面:{name}',
+ ja: 'ページを開く:{name}',
+ pt: 'Abrir página: {name}',
+ };
+ for (const [locale, copy] of Object.entries(expected)) {
+ const table = JSON.parse(fs.readFileSync(
+ path.join(path.dirname(RENDERER_CONVERSATION), '..', 'locales', `${locale}.json`),
+ 'utf8',
+ ));
+ expect(table['chat.app_nav_open'], locale).toBe(copy);
+ }
+ });
+
+ it('localizes navigation failure recovery in every supported locale', () => {
+ for (const locale of ['en', 'zh', 'ja', 'pt']) {
+ const table = JSON.parse(fs.readFileSync(
+ path.join(path.dirname(RENDERER_CONVERSATION), '..', 'locales', `${locale}.json`),
+ 'utf8',
+ ));
+ expect(table['chat.app_nav_failed'], locale).toBeTruthy();
+ expect(table['chat.app_nav_failed'], locale).not.toBe('chat.app_nav_failed');
+ }
+ });
+
+ it('matches the renderer executor map exactly (a staged card must always be openable)', () => {
+ // The tool enum comes from this registry while the click handler lives in
+ // the renderer; any drift ships a card that either cannot render or a
+ // surface the model can never stage.
+ expect(rendererSurfaceIds().sort()).toEqual(APP_NAV_SURFACES.map((s) => s.id).sort());
+ expect(rendererSurfaceActions()).toEqual(Object.fromEntries(
+ APP_NAV_SURFACES.map((surface) => [surface.id, [...surface.actions]]),
+ ));
+ });
+
+ it('validates action and target combinations at the staging boundary', () => {
+ expect(validateAppNavRequest({ surface_id: 'settings.models' })).toEqual({
+ ok: true,
+ request: { surface_id: 'settings.models', action: 'open' },
+ });
+ expect(validateAppNavRequest({ surface_id: 'connectors', action: 'add_custom' })).toEqual({
+ ok: true,
+ request: { surface_id: 'connectors', action: 'add_custom' },
+ });
+ expect(validateAppNavRequest({
+ surface_id: 'agents', action: 'configure', target_id: 'agent-123',
+ })).toEqual({
+ ok: true,
+ request: { surface_id: 'agents', action: 'configure', target_id: 'agent-123' },
+ });
+ expect(validateAppNavRequest({ surface_id: 'settings.models', action: 'create' }))
+ .toMatchObject({ ok: false, error: expect.stringContaining('not supported') });
+ expect(validateAppNavRequest({ surface_id: 'agents', action: 'configure' }))
+ .toMatchObject({ ok: false, error: expect.stringContaining('target_id is required') });
+ expect(validateAppNavRequest({
+ surface_id: 'agents', action: 'open', target_id: 'agent-123',
+ })).toMatchObject({
+ ok: false,
+ error: expect.stringMatching(/target_id requires action configure.*retry with action configure/),
+ });
+ expect(validateAppNavRequest({
+ surface_id: 'projects', action: 'open', target_id: 'project-123',
+ })).toMatchObject({
+ ok: false,
+ error: expect.stringMatching(/target_id requires action configure.*same target_id/),
+ });
+ expect(validateAppNavRequest({
+ surface_id: 'agents', action: 'configure', target_id: 'bad\nidentifier',
+ })).toMatchObject({ ok: false, error: expect.stringContaining('bounded printable') });
+ expect(validateAppNavRequest({
+ surface_id: 'agents', action: 'configure', target_id: 'x'.repeat(160),
+ })).toMatchObject({ ok: true });
+ expect(validateAppNavRequest({
+ surface_id: 'agents', action: 'configure', target_id: 'x'.repeat(161),
+ })).toMatchObject({ ok: false, error: expect.stringContaining('bounded printable') });
+ expect(validateAppNavRequest({
+ surface_id: 'agents', action: 'configure', target_id: 'bad\u007fidentifier',
+ })).toMatchObject({ ok: false, error: expect.stringContaining('bounded printable') });
+ expect(validateAppNavRequest({ surface_id: 'agents', action: 'delete' }))
+ .toMatchObject({ ok: false, error: expect.stringContaining('not supported') });
+ });
+
+ it('loads cold-start feature modules before invoking action-specific handlers', () => {
+ const source = fs.readFileSync(RENDERER_CONVERSATION, 'utf8');
+ expect(source).toContain("_appNavLoadFeature('marketplace'");
+ expect(source).toContain('window.focusConnectorById');
+ expect(source).toContain('window.openAgentModal');
+ expect(source).toContain('window.openAgentDetail');
+ expect(source).toContain('window.openAutoTaskDialog');
+ expect(source).toContain('window.openAutoTaskById');
+ });
+
+ it('executes navigation actions through the owning renderer workflows after lazy loading', async () => {
+ const { calls, surfaces } = rendererNavHarness();
+
+ await surfaces['settings.models'].open({ action: 'open' });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(calls.splice(0)).toEqual([
+ 'view:settings', 'load:settings', 'settings:credentials', 'settings:credentials',
+ ]);
+
+ await surfaces.connectors.open({ action: 'add_custom' });
+ expect(calls.splice(0)).toEqual([
+ 'view:connectors', 'load:connectors', 'click:connectors-add-custom-btn',
+ ]);
+
+ await surfaces.connectors.open({ action: 'configure', target_id: 'connector-1' });
+ expect(calls.splice(0)).toEqual([
+ 'view:connectors', 'load:connectors', 'connector:configure:connector-1',
+ ]);
+
+ await surfaces.agents.open({ action: 'create' });
+ expect(calls.splice(0)).toEqual(['view:agents', 'load:agents', 'agent:create']);
+
+ await surfaces.auto.open({ action: 'configure', target_id: 'task-1' });
+ expect(calls.splice(0)).toEqual(['view:auto', 'load:auto', 'auto:configure:task-1']);
+
+ await surfaces.projects.open({ action: 'configure', target_id: 'project-1' });
+ expect(calls.splice(0)).toEqual(['project:configure:project-1']);
+
+ await surfaces.apps.open({ action: 'open' });
+ expect(calls.splice(0)).toEqual(['view:apps']);
+
+ await surfaces.marketplace.open({ action: 'open' });
+ expect(calls.splice(0)).toEqual(['load:marketplace', 'marketplace:agent']);
+ });
+
+ it('executes every declared surface/action pair through its production owner', async () => {
+ const cases: Array<{
+ surface: string;
+ request: Record<string, string>;
+ expected: string[];
+ }> = [
+ { surface: 'settings.models', request: { action: 'open' }, expected: ['view:settings', 'load:settings', 'settings:credentials', 'settings:credentials'] },
+ { surface: 'settings.general', request: { action: 'open' }, expected: ['view:settings', 'load:settings', 'settings:general', 'settings:general'] },
+ { surface: 'settings.data', request: { action: 'open' }, expected: ['view:settings', 'load:settings', 'settings:data', 'settings:data'] },
+ { surface: 'connectors', request: { action: 'open' }, expected: ['view:connectors', 'load:connectors'] },
+ { surface: 'connectors', request: { action: 'add_custom' }, expected: ['view:connectors', 'load:connectors', 'click:connectors-add-custom-btn'] },
+ { surface: 'connectors', request: { action: 'configure', target_id: 'connector-1' }, expected: ['view:connectors', 'load:connectors', 'connector:configure:connector-1'] },
+ { surface: 'library', request: { action: 'open' }, expected: ['view:contexts'] },
+ { surface: 'projects', request: { action: 'open' }, expected: ['project:open:'] },
+ { surface: 'projects', request: { action: 'create' }, expected: ['project:create:'] },
+ { surface: 'projects', request: { action: 'configure', target_id: 'project-1' }, expected: ['project:configure:project-1'] },
+ { surface: 'agents', request: { action: 'open' }, expected: ['view:agents', 'load:agents'] },
+ { surface: 'agents', request: { action: 'create' }, expected: ['view:agents', 'load:agents', 'agent:create'] },
+ { surface: 'agents', request: { action: 'configure', target_id: 'agent-1' }, expected: ['view:agents', 'load:agents', 'agent:configure:agent-1'] },
+ { surface: 'skills', request: { action: 'open' }, expected: ['view:skills', 'load:skills'] },
+ { surface: 'skills', request: { action: 'create' }, expected: ['view:skills', 'load:skills', 'skill:create'] },
+ { surface: 'auto', request: { action: 'open' }, expected: ['view:auto', 'load:auto'] },
+ { surface: 'auto', request: { action: 'create' }, expected: ['view:auto', 'load:auto', 'auto:create'] },
+ { surface: 'auto', request: { action: 'configure', target_id: 'task-1' }, expected: ['view:auto', 'load:auto', 'auto:configure:task-1'] },
+ { surface: 'apps', request: { action: 'open' }, expected: ['view:apps'] },
+ { surface: 'marketplace', request: { action: 'open' }, expected: ['load:marketplace', 'marketplace:agent'] },
+ ];
+
+ for (const testCase of cases) {
+ const { calls, surfaces } = rendererNavHarness();
+ await surfaces[testCase.surface].open(testCase.request);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(calls, `${testCase.surface}:${testCase.request.action}`)
+ .toEqual(testCase.expected);
+ }
+ });
+
+ it('does not execute an action-specific side effect when its feature module is unavailable', async () => {
+ const { calls, surfaces } = rendererNavHarness('connectors');
+ await expect(surfaces.connectors.open({ action: 'add_custom' })).rejects.toThrow('feature unavailable');
+ expect(calls).toEqual(['view:connectors', 'load:connectors']);
+ });
+
+ it('rejects a stale configure target instead of presenting navigation as successful', async () => {
+ const { calls, surfaces } = rendererNavHarness();
+ await expect(surfaces.auto.open({ action: 'configure', target_id: 'missing' }))
+ .rejects.toThrow('target unavailable');
+ expect(calls).toEqual(['view:auto', 'load:auto', 'auto:configure:missing']);
+ });
+
+ it('shows localized feedback when a clicked navigation card cannot open', async () => {
+ const { host, mount, toasts } = rendererMountHarness('connectors');
+ mount(host, { app_nav_requests: [{ surface_id: 'connectors', action: 'add_custom' }] });
+ host.querySelector('.chat-app-nav-row')?.children[0]?.click();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(toasts).toEqual([{ message: 'chat.app_nav_failed:', variant: 'error' }]);
+ });
+
+ it('renders only validated, deduped cards and keeps legacy open requests clickable', async () => {
+ const { calls, host, mount } = rendererMountHarness();
+ const message = {
+ app_nav_requests: [
+ // Pre-action messages from 1.6.8 migration remain usable.
+ { surface_id: 'settings.models' },
+ { surface_id: 'settings.models' },
+ { surface_id: 'connectors', action: 'add_custom' },
+ { surface_id: 'connectors', action: 'add_custom' },
+ { surface_id: 'settings.models', action: 'create' },
+ { surface_id: 'settings.models', action: 'open', target_id: 'forged-target' },
+ { surface_id: 'agents', action: 'configure' },
+ { surface_id: 'agents', action: 'configure', target_id: 'x'.repeat(161) },
+ { surface_id: 'agents', action: 'configure', target_id: 'bad\nidentifier' },
+ { surface_id: 'not-a-surface', action: 'open' },
+ ],
+ };
+
+ mount(host, message);
+ // Re-mounting the same persisted message is the history-refresh path and
+ // must not append another set of cards.
+ mount(host, message);
+ const row = host.querySelector('.chat-app-nav-row');
+ expect(row?.children).toHaveLength(2);
+ expect(row?.children.map((button) => button.textContent)).toEqual([
+ 'chat.app_nav_open:Models & credentials',
+ 'chat.app_nav_add_custom:Connectors',
+ ]);
+ row?.children[1]?.click();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(Array.from(calls)).toEqual([
+ 'view:connectors', 'load:connectors', 'click:connectors-add-custom-btn',
+ ]);
+ });
+
+ it('keeps navigation cards independent of private onboarding telemetry', () => {
+ const source = fs.readFileSync(RENDERER_CONVERSATION, 'utf8');
+ const start = source.indexOf('function _mountAppNavRequests');
+ const end = source.indexOf('function _mountMarketplaceInstallRequests', start);
+ const mountBlock = source.slice(start, end);
+ expect(mountBlock).not.toContain('_convTrackClick');
+ expect(mountBlock).not.toContain('_onboardingTelemetryContext');
+ });
+
+ it('keeps the page action compact, evenly spaced, regular-weight, and chevron-free', () => {
+ const source = fs.readFileSync(RENDERER_CONVERSATION, 'utf8');
+ const start = source.indexOf('function _mountAppNavRequests');
+ const end = source.indexOf('function _mountMarketplaceInstallRequests', start);
+ const mountBlock = source.slice(start, end);
+ expect(mountBlock).toContain("uiIconHtml('panel-list'");
+ expect(mountBlock).not.toContain('chevron-right');
+
+ const css = fs.readFileSync(RENDERER_STYLE, 'utf8');
+ const styleStart = css.indexOf('.chat-app-nav-row .chat-app-nav-btn {');
+ const styleEnd = css.indexOf('.chat-marketplace-request {', styleStart);
+ const styleBlock = css.slice(styleStart, styleEnd);
+ expect(styleBlock).toContain('width: fit-content');
+ expect(styleBlock).toContain('min-height: 40px');
+ expect(styleBlock).toContain('gap: 8px');
+ expect(styleBlock).toContain('padding: 9px 12px');
+ expect(styleBlock).toContain('font-weight: 400');
+ expect(styleBlock).toContain('width: 16px');
+ expect(styleBlock).toContain('flex: 0 0 16px');
+ expect(styleBlock.match(/background:\s*transparent/g)?.length).toBeGreaterThanOrEqual(2);
+ });
+
+ it('focuses the exact configured connector through the production helper', async () => {
+ const source = fs.readFileSync(RENDERER_CONNECTORS, 'utf8');
+ const fnSource = extractAssignedAsyncFunction(source, 'window.focusConnectorById =');
+ const calls: string[] = [];
+ const cards = ['connector-1', 'connector-2'].map((id) => ({
+ dataset: { id },
+ setAttribute: (name: string, value: string) => calls.push(`attr:${id}:${name}:${value}`),
+ scrollIntoView: () => calls.push(`scroll:${id}`),
+ focus: () => calls.push(`focus:${id}`),
+ }));
+ const context = {
+ loadConnectors: async () => { calls.push('load'); },
+ document: { querySelectorAll: () => cards },
+ };
+ const focusConnector = vm.runInNewContext(`(${fnSource})`, context) as (
+ id: string,
+ ) => Promise<boolean>;
+
+ expect(await focusConnector(' connector-2 ')).toBe(true);
+ expect(calls).toEqual([
+ 'load',
+ 'attr:connector-2:tabindex:-1',
+ 'scroll:connector-2',
+ 'focus:connector-2',
+ ]);
+ expect(await focusConnector('missing')).toBe(false);
+ expect(calls.at(-1)).toBe('load');
+ });
+
+ it('opens Projects through the owning sidebar/create/detail workflows', async () => {
+ const source = fs.readFileSync(RENDERER_PROJECTS, 'utf8');
+ const fnSource = extractAssignedAsyncFunction(source, 'window.openProjectsSurface =');
+ const calls: string[] = [];
+ let expanded = false;
+ const toggle = {
+ getAttribute: () => (expanded ? 'true' : 'false'),
+ click: () => { expanded = true; calls.push('expand'); },
+ scrollIntoView: () => calls.push('scroll'),
+ focus: () => calls.push('focus'),
+ };
+ const context: any = {
+ _projectsInlineCreate: false,
+ _startProjectInlineCreate: () => {
+ context._projectsInlineCreate = true;
+ calls.push('create');
+ },
+ loadProjects: async () => [
+ { project_id: 'project-1' },
+ { project_id: 'project-2' },
+ ],
+ setView: (view: string, id: string) => calls.push(`${view}:${id}`),
+ document: { getElementById: () => toggle },
+ };
+ const openProjects = vm.runInNewContext(`(${fnSource})`, context) as (
+ request: Record<string, string>,
+ ) => Promise<boolean>;
+
+ expect(await openProjects({ action: 'open' })).toBe(true);
+ expect(calls.splice(0)).toEqual(['expand', 'scroll', 'focus']);
+ expect(await openProjects({ action: 'create' })).toBe(true);
+ expect(calls.splice(0)).toEqual(['create']);
+ expect(await openProjects({ action: 'configure', target_id: 'project-2' })).toBe(true);
+ expect(calls.splice(0)).toEqual(['project:project-2']);
+ expect(await openProjects({ action: 'configure', target_id: 'missing' })).toBe(false);
+ expect(calls).toEqual([]);
+ });
+
+ it('opens the exact automation task through the production helper', async () => {
+ const source = fs.readFileSync(RENDERER_AUTO, 'utf8');
+ const fnSource = extractAssignedAsyncFunction(source, 'window.openAutoTaskById =');
+ const calls: string[] = [];
+ const tasks = [{ id: 'task-1' }, { id: 'task-2' }];
+ const opened: Array<{ task: { id: string } }> = [];
+ const context = {
+ _autoTasks: tasks,
+ loadAutoTasks: async () => { calls.push('load'); },
+ openAutoTaskDialog: (input: { task: { id: string } }) => { opened.push(input); },
+ };
+ const openAutoTask = vm.runInNewContext(`(${fnSource})`, context) as (
+ id: string,
+ ) => Promise<boolean>;
+
+ expect(await openAutoTask(' task-2 ')).toBe(true);
+ expect(calls).toEqual(['load']);
+ expect(opened).toEqual([{ task: tasks[1] }]);
+ expect(await openAutoTask('missing')).toBe(false);
+ expect(opened).toHaveLength(1);
+ });
+});
diff --git a/test/main/features/group_chat/app_health.test.ts b/test/main/features/group_chat/app_health.test.ts
new file mode 100644
index 00000000..6fd574d2
--- /dev/null
+++ b/test/main/features/group_chat/app_health.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, it, vi } from 'vitest';
+
+// The probes must stay read-only and sanitized: bounded kinds, counts, and
+// ids only. The fixtures deliberately plant secret-shaped values (raw 401
+// reason with an api key, profile label, encrypted connector secrets) that
+// must never surface in the snapshot.
+const authMock = vi.hoisted(() => ({
+ hasConfiguredModel: vi.fn(() => ({ configured: true })),
+ getConfig: vi.fn(async () => ({ provider: 'deepseek', model: 'deepseek-chat' })),
+ getConfiguredModelCooldown: vi.fn(() => ({
+ profileId: 'secret-profile-label',
+ cooledUntil: Date.now() + 90_000,
+ kind: 'auth',
+ reason: '401 invalid api key sk-live-1234567890',
+ })),
+ getConfiguredModelOAuthExpiredMessage: vi.fn((): string | null => null),
+}));
+vi.mock('../../../../src/main/features/auth', () => authMock);
+
+const connectorsMock = vi.hoisted(() => ({
+ listInstances: vi.fn(() => [
+ {
+ id: 'notion',
+ display_name: 'Notion',
+ status: { kind: 'connected', message: 'Authorization: Bearer planted-secret-token' },
+ secrets_enc: 'ORKLSEC1:must-never-leak',
+ },
+ { id: 'custom-x', display_name: 'Internal MCP', status: { kind: 'degraded' } },
+ { id: 'broken-x', display_name: 'Broken MCP', status: { kind: 'error' } },
+ ]),
+}));
+vi.mock('../../../../src/main/features/connectors/manager', () => connectorsMock);
+vi.mock('../../../../src/main/features/connectors/availability', () => ({
+ isConnectorRuntimeEnabled: vi.fn((id: string) => id !== 'broken-x'),
+}));
+vi.mock('../../../../src/main/features/connectors/types', () => ({
+ isConnectorUsable: vi.fn((status: { kind?: string } | undefined) => (
+ status?.kind === 'connected' || status?.kind === 'degraded'
+ )),
+}));
+vi.mock('../../../../src/main/features/component_enabled', () => ({
+ readEnabledMap: vi.fn(() => ({ connectors: { 'custom-x': false } })),
+ isConnectorEnabledFromSnapshot: vi.fn((snapshot: { connectors: Record<string, boolean> }, id: string) => (
+ snapshot.connectors[id] ?? true
+ )),
+}));
+
+const kbMock = vi.hoisted(() => ({
+ statusSummary: vi.fn(() => ({ total: 3, ready: 2, processing: 1, pending: 0, failed: 0 })),
+}));
+vi.mock('../../../../src/main/features/kb_vector', () => kbMock);
+
+import { APP_HEALTH_DOMAINS, collectAppHealth } from '../../../../src/main/features/group_chat/app_health';
+
+const tasksProbe = () => ({
+ active_work: true,
+ active_conversation_count: 3,
+ other_active_conversation_count: 2,
+ current_conversation: { processing: true, in_flight_actor_count: 1, active_turn_count: 1 },
+});
+
+describe('group_chat app_health probes', () => {
+ it('collects a full sanitized snapshot across every domain', async () => {
+ const snapshot = await collectAppHealth('u1', APP_HEALTH_DOMAINS, tasksProbe);
+ expect(Object.keys(snapshot).sort()).toEqual(['connectors', 'kb', 'model', 'tasks']);
+
+ expect(snapshot.model).toMatchObject({
+ configured: true,
+ default_provider: 'deepseek',
+ default_model: 'deepseek-chat',
+ credential_cooldown: { kind: 'auth' },
+ oauth_expired: null,
+ });
+ const cooldown = (snapshot.model as { credential_cooldown: { seconds_remaining: number } }).credential_cooldown;
+ expect(cooldown.seconds_remaining).toBeGreaterThan(0);
+ expect(cooldown.seconds_remaining).toBeLessThanOrEqual(90);
+
+ expect(snapshot.connectors).toEqual({
+ configured_count: 3,
+ connected_count: 1,
+ usable_count: 1,
+ items: [
+ { id: 'notion', name: 'Notion', status: 'connected', enabled: true, usable: true },
+ { id: 'custom-x', name: 'Internal MCP', status: 'degraded', enabled: false, usable: false },
+ { id: 'broken-x', name: 'Broken MCP', status: 'error', enabled: false, usable: false },
+ ],
+ });
+ expect(snapshot.kb).toEqual({ total: 3, ready: 2, processing: 1, pending: 0, failed: 0 });
+ expect(snapshot.tasks).toEqual(tasksProbe());
+
+ // Sanitization oracle: none of the planted secret material may appear.
+ const text = JSON.stringify(snapshot);
+ expect(text).not.toContain('sk-live-1234567890');
+ expect(text).not.toContain('secret-profile-label');
+ expect(text).not.toContain('ORKLSEC1');
+ expect(text).not.toContain('401 invalid');
+ expect(text).not.toContain('planted-secret-token');
+ });
+
+ it('returns only the requested domain', async () => {
+ const snapshot = await collectAppHealth('u1', ['kb'], tasksProbe);
+ expect(Object.keys(snapshot)).toEqual(['kb']);
+ });
+
+ it('caps the connector item list while keeping the true connected count', async () => {
+ connectorsMock.listInstances.mockReturnValueOnce(
+ Array.from({ length: 25 }, (_, i) => ({
+ id: `c${i}`, display_name: `C${i}`, status: { kind: 'connected' },
+ })) as never,
+ );
+ const snapshot = await collectAppHealth('u1', ['connectors'], tasksProbe);
+ const connectors = snapshot.connectors as {
+ configured_count: number; connected_count: number; usable_count: number; items: unknown[];
+ };
+ expect(connectors.configured_count).toBe(25);
+ expect(connectors.connected_count).toBe(25);
+ expect(connectors.usable_count).toBe(25);
+ expect(connectors.items).toHaveLength(20);
+ });
+
+ it.each([
+ ['model', () => authMock.getConfig.mockRejectedValueOnce(
+ new Error('model probe leaked sk-private-model'),
+ )],
+ ['connectors', () => connectorsMock.listInstances.mockImplementationOnce(() => {
+ throw new Error('connector probe leaked ORKLSEC1:private');
+ })],
+ ['kb', () => kbMock.statusSummary.mockImplementationOnce(() => {
+ throw new Error('/private/library/index.sqlite');
+ })],
+ ] as const)(
+ 'degrades a failing %s probe without dropping or contaminating other domains',
+ async (failedDomain, armFailure) => {
+ armFailure();
+ const snapshot = await collectAppHealth('u1', APP_HEALTH_DOMAINS, tasksProbe);
+ expect(snapshot[failedDomain]).toEqual({ unavailable: true });
+ for (const domain of APP_HEALTH_DOMAINS) {
+ if (domain !== failedDomain) expect(snapshot[domain]).not.toEqual({ unavailable: true });
+ }
+ expect(snapshot.tasks).toEqual(tasksProbe());
+ expect(JSON.stringify(snapshot)).not.toMatch(/sk-private|ORKLSEC1|index\.sqlite/i);
+ },
+ );
+
+ it('isolates a failing injected task probe from model, connector, and Library status', async () => {
+ const snapshot = await collectAppHealth('u1', APP_HEALTH_DOMAINS, () => {
+ throw new Error('conversation content must never escape');
+ });
+ expect(snapshot.tasks).toEqual({ unavailable: true });
+ expect(snapshot.model).not.toEqual({ unavailable: true });
+ expect(snapshot.connectors).not.toEqual({ unavailable: true });
+ expect(snapshot.kb).not.toEqual({ unavailable: true });
+ expect(JSON.stringify(snapshot)).not.toContain('conversation content');
+ });
+});
diff --git a/test/main/features/group_chat/bus-integration.test.ts b/test/main/features/group_chat/bus-integration.test.ts
index 78b0d4f2..d100108b 100644
--- a/test/main/features/group_chat/bus-integration.test.ts
+++ b/test/main/features/group_chat/bus-integration.test.ts
@@ -327,6 +327,103 @@ describe('group_chat bus integration › conversation search freshness', () => {
});
});
+describe('group_chat bus integration › durable-memory write claims', () => {
+ it('preserves an ordinary project-file delivery without memory-write evidence', async () => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const paths = await import('../../../../src/main/paths');
+ const storage = await import('../../../../src/main/storage');
+ const delivery = '项目档案已保存到 report.json。';
+ _setScript(state.buildGconvSessionId(cid), [
+ { type: 'final', text: delivery },
+ ]);
+
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: '请生成并保存项目档案' });
+ await waitForQuiescent(TEST_UID, cid);
+
+ const messages = await storage.readJsonl<any>(
+ path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`),
+ );
+ const reply = messages.find((message: any) => message.from === 'commander');
+ expect(reply.text).toBe(delivery);
+ expect(reply.failure_kind).toBeUndefined();
+ expect(reply.failure_code).toBeUndefined();
+ });
+
+ it('replaces a Commander success claim when no memory write completed', async () => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const paths = await import('../../../../src/main/paths');
+ const storage = await import('../../../../src/main/storage');
+ _setScript(state.buildGconvSessionId(cid), [
+ {
+ type: 'final',
+ text: '六条全部写入项目长期笔记。\n\n其余分析仍然有效。',
+ },
+ ]);
+
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: '请记住这六条规则' });
+ await waitForQuiescent(TEST_UID, cid);
+
+ const messages = await storage.readJsonl<any>(
+ path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`),
+ );
+ const reply = messages.find((message: any) => message.from === 'commander');
+ expect(reply.text).not.toContain('全部写入项目长期笔记');
+ expect(reply.text).toContain('其余分析仍然有效');
+ expect(reply.text).toMatch(/持久记忆未保存|Durable memory was not saved/);
+ expect(reply).toMatchObject({
+ failure_kind: 'validation',
+ failure_code: 'memory_write_unconfirmed',
+ });
+ });
+
+ it('preserves the success claim after an observed memory write', async () => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const paths = await import('../../../../src/main/paths');
+ const storage = await import('../../../../src/main/storage');
+ const sid = state.buildGconvSessionId(cid);
+ _setScript(sid, [
+ {
+ type: 'event',
+ event: {
+ stream: 'tool',
+ data: {
+ phase: 'start', id: 'memory-1', name: 'cross_session_memory',
+ arguments: { action: 'add', target: 'project', content: 'six stable rules' },
+ },
+ },
+ },
+ {
+ type: 'event',
+ event: {
+ stream: 'tool',
+ data: {
+ phase: 'end', id: 'memory-1', name: 'cross_session_memory',
+ isError: false, output: '{"ok":true}',
+ },
+ },
+ },
+ { type: 'final', text: '六条全部写入项目长期笔记。' },
+ ]);
+
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: '请记住这六条规则' });
+ await waitForQuiescent(TEST_UID, cid);
+
+ const messages = await storage.readJsonl<any>(
+ path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`),
+ );
+ const reply = messages.find((message: any) => message.from === 'commander');
+ expect(reply.text).toBe('六条全部写入项目长期笔记。');
+ expect(reply.failure_kind).toBeUndefined();
+ expect(reply.failure_code).toBeUndefined();
+ });
+});
+
describe('group_chat bus integration › generated-media URL freshness', () => {
it('versions assistant URLs at persistence while preserving user-authored text', async () => {
const cid = newCid();
@@ -1047,6 +1144,173 @@ describe('group_chat bus integration › Commander utility tools', () => {
error: '`kind` must be agent or skill',
});
}, 12_000);
+
+ it('stages open_app_view navigation cards and returns a sanitized app_health snapshot', async () => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const paths = await import('../../../../src/main/paths');
+ const storage = await import('../../../../src/main/storage');
+ const sid = state.buildGconvSessionId(cid);
+
+ _setScript(sid, [
+ { type: '__call_tool__', name: 'open_app_view', input: { surface_id: 'settings.models' } },
+ // A repeated stage of the same surface must not duplicate the card.
+ { type: '__call_tool__', name: 'open_app_view', input: { surface_id: 'settings.models' } },
+ { type: '__call_tool__', name: 'open_app_view', input: {
+ surface_id: 'agents', action: 'configure', target_id: 'agent-123',
+ } },
+ { type: '__call_tool__', name: 'open_app_view', input: {
+ surface_id: 'agents', action: 'configure', target_id: 'agent-123',
+ } },
+ { type: '__call_tool__', name: 'open_app_view', input: {
+ surface_id: 'settings.models', action: 'create',
+ } },
+ { type: '__call_tool__', name: 'open_app_view', input: {
+ surface_id: 'agents', action: 'configure',
+ } },
+ { type: '__call_tool__', name: 'open_app_view', input: { surface_id: 'not-a-surface' } },
+ { type: '__call_tool__', name: 'app_health', input: { domain: 'credentials' } },
+ { type: '__call_tool__', name: 'app_health', input: { domain: 'kb' } },
+ { type: '__call_tool__', name: 'app_health', input: {} },
+ { type: 'final', text: 'Open Models settings from the card below.' },
+ ]);
+
+ bus.subscribe(TEST_UID, cid, () => {});
+ await bus.enqueue({
+ uid: TEST_UID,
+ cid,
+ fromActorId: 'user',
+ text: '@commander help me set up a model and check app status',
+ });
+ await waitForQuiescent(TEST_UID, cid, 6000);
+
+ const offered = _recordedCalls.find((call) => call.sid === sid)?.extraToolNames ?? [];
+ expect(offered).toEqual(expect.arrayContaining(['open_app_view', 'app_health']));
+ const contracts = _recordedCalls.find((call) => call.sid === sid)?.extraToolContracts ?? [];
+ const navContract = contracts.find((tool) => tool.name === 'open_app_view');
+ expect(navContract?.inputSchema).toMatchObject({
+ type: 'object',
+ required: ['surface_id'],
+ additionalProperties: false,
+ properties: {
+ surface_id: { enum: [
+ 'settings.models', 'settings.general', 'settings.data',
+ 'connectors', 'library', 'projects', 'agents', 'skills', 'auto', 'apps', 'marketplace',
+ ] },
+ action: { enum: ['open', 'add_custom', 'configure', 'create'] },
+ target_id: { type: 'string', maxLength: 160 },
+ },
+ });
+ expect(contracts.find((tool) => tool.name === 'app_health')?.inputSchema).toMatchObject({
+ type: 'object',
+ additionalProperties: false,
+ properties: {
+ domain: { enum: ['model', 'connectors', 'kb', 'tasks'] },
+ },
+ });
+
+ const navResults = _recordedToolResults
+ .filter((result) => result.name === 'open_app_view')
+ .map((result) => JSON.parse(result.content));
+ expect(navResults[0]).toMatchObject({
+ ok: true,
+ status: 'navigation_card_staged',
+ surface_id: 'settings.models',
+ action: 'open',
+ });
+ expect(navResults[1]).toMatchObject({ ok: true, surface_id: 'settings.models', action: 'open' });
+ expect(navResults[2]).toMatchObject({
+ ok: true, surface_id: 'agents', action: 'configure', target_id: 'agent-123',
+ });
+ expect(navResults[3]).toMatchObject({
+ ok: true, surface_id: 'agents', action: 'configure', target_id: 'agent-123',
+ });
+ expect(navResults[4]).toMatchObject({ ok: false, error: expect.stringContaining('not supported') });
+ expect(navResults[5]).toMatchObject({ ok: false, error: expect.stringContaining('target_id is required') });
+ expect(navResults[6]).toMatchObject({ ok: false, error: expect.stringContaining('unknown surface_id') });
+
+ const healthResults = _recordedToolResults
+ .filter((result) => result.name === 'app_health')
+ .map((result) => JSON.parse(result.content));
+ // A forged/bypassed enum value must not accidentally widen into a full
+ // snapshot. Runtime validation is authoritative even when schema
+ // validation did not run.
+ expect(healthResults[0]).toEqual({
+ ok: false,
+ error: 'domain must be one of: model, connectors, kb, tasks',
+ });
+ // Domain filter returns exactly that probe.
+ expect(Object.keys(healthResults[1]).sort()).toEqual(['kb', 'ok']);
+ expect(healthResults[1].kb).toMatchObject({ total: expect.any(Number), ready: expect.any(Number) });
+ // Full snapshot covers every domain and stays sanitized: no credential or
+ // secret-shaped keys may appear anywhere in the payload.
+ const full = healthResults[2];
+ expect(Object.keys(full).sort()).toEqual(['connectors', 'kb', 'model', 'ok', 'tasks']);
+ expect(full.tasks).toMatchObject({
+ active_work: expect.any(Boolean),
+ active_conversation_count: expect.any(Number),
+ other_active_conversation_count: expect.any(Number),
+ current_conversation: {
+ processing: expect.any(Boolean),
+ in_flight_actor_count: expect.any(Number),
+ active_turn_count: expect.any(Number),
+ },
+ });
+ expect(JSON.stringify(full)).not.toMatch(/api[_-]?key|authorization|secret|token/i);
+
+ // The deduped card rides the final commander message for the renderer.
+ const messages = await storage.readJsonl<any>(path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`));
+ const finalMsg = messages.find((m: any) => m.from === 'commander' && Array.isArray(m.app_nav_requests));
+ expect(finalMsg?.app_nav_requests).toEqual([
+ { surface_id: 'settings.models', action: 'open', requested_at: expect.any(String) },
+ {
+ surface_id: 'agents',
+ action: 'configure',
+ target_id: 'agent-123',
+ requested_at: expect.any(String),
+ },
+ ]);
+ }, 12_000);
+
+ it('offers the saved Automation for review after the owning workflow succeeds', async () => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const sid = state.buildGconvSessionId(cid);
+ _setScript(sid, [{
+ type: 'final',
+ text: [
+ 'Automation ready.',
+ '<auto-task>',
+ '<action>create</action>',
+ '<title>Morning review</title>',
+ '<content>Summarize yesterday and plan today.</content>',
+ '<schedule>{"type":"daily","hour":9,"minute":0}</schedule>',
+ '<recipient>{"kind":"commander"}</recipient>',
+ '</auto-task>',
+ ].join('\n'),
+ }]);
+
+ await bus.enqueue({
+ uid: TEST_UID,
+ cid,
+ fromActorId: 'user',
+ text: 'Create a daily morning review automation',
+ });
+ await waitForQuiescent(TEST_UID, cid, 6000);
+
+ const rows = await (await import('../../../../src/main/features/group_chat'))
+ .readMessages(TEST_UID, cid);
+ const reply = rows.find((row: any) => row.from === 'commander' && !row.dispatch);
+ expect(reply?.text).not.toContain('<auto-task>');
+ expect(reply?.app_nav_requests).toEqual([{
+ surface_id: 'auto',
+ action: 'configure',
+ target_id: expect.stringMatching(/^at_[a-z0-9]+$/),
+ requested_at: expect.any(String),
+ }]);
+ }, 12_000);
});
describe('group_chat bus integration › native Skill package import', () => {
diff --git a/test/main/features/group_chat/bus-steer.test.ts b/test/main/features/group_chat/bus-steer.test.ts
index 726a09c1..dbb1d509 100644
--- a/test/main/features/group_chat/bus-steer.test.ts
+++ b/test/main/features/group_chat/bus-steer.test.ts
@@ -2,6 +2,17 @@ import { describe, it, expect, vi } from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
+import {
+ AgentRunner,
+ createConfig,
+ defineTool,
+ ProviderRegistry,
+ type AgentRunEvent,
+ type CompletionParams,
+ type CompletionResult,
+ type LLMProvider,
+ type Message,
+} from '#core-agent';
vi.mock('../../../../src/main/features/chat_attachments', () => ({
resolveAttachmentAbsPath: (_uid: string, _cid: string, name: string) => ({
@@ -89,6 +100,107 @@ async function acknowledge(messages: AnyItem[]): Promise<void> {
}
describe('group_chat bus › drainSteerInto (interrupt-steer)', () => {
+ it('acknowledges a Send now update before any stale side-effect tool executes', async () => {
+ const requests: Message[][] = [];
+ let streamCalls = 0;
+ const provider: LLMProvider = {
+ id: 'mock',
+ name: 'Mock',
+ async complete(): Promise<CompletionResult> { throw new Error('unused'); },
+ async *stream(params: CompletionParams) {
+ streamCalls++;
+ requests.push([...params.messages]);
+ yield { type: 'message_start' as const };
+ if (streamCalls === 1) {
+ yield { type: 'tool_use_start' as const, id: 'send-1', name: 'send_external_message' };
+ yield { type: 'tool_use_delta' as const, id: 'send-1', input: '{"body":"old draft"}' };
+ yield { type: 'tool_use_end' as const, id: 'send-1' };
+ yield {
+ type: 'message_end' as const,
+ stopReason: 'tool_use' as const,
+ usage: { inputTokens: 5, outputTokens: 5, totalTokens: 10 },
+ content: [{
+ type: 'tool_use' as const,
+ id: 'send-1',
+ name: 'send_external_message',
+ input: { body: 'old draft' },
+ }],
+ model: 'mock-model',
+ };
+ return;
+ }
+ yield { type: 'text_delta' as const, text: 'Kept the message as a draft.' };
+ yield {
+ type: 'message_end' as const,
+ stopReason: 'end_turn' as const,
+ usage: { inputTokens: 5, outputTokens: 4, totalTokens: 9 },
+ content: [{ type: 'text' as const, text: 'Kept the message as a draft.' }],
+ model: 'mock-model',
+ };
+ },
+ async validateAuth() { return true; },
+ };
+ const registry = new ProviderRegistry();
+ registry.registerFactory('mock', () => provider);
+ let sideEffects = 0;
+ const sendExternalMessage = defineTool({
+ name: 'send_external_message',
+ description: 'Send an external message.',
+ inputSchema: {
+ type: 'object',
+ properties: { body: { type: 'string' } },
+ required: ['body'],
+ },
+ async execute() {
+ sideEffects++;
+ return { content: 'sent' };
+ },
+ });
+ const runner = new AgentRunner({
+ config: createConfig({ agent: { defaultProvider: 'mock', defaultModel: 'mock-model' } }),
+ providers: registry,
+ tools: [sendExternalMessage],
+ });
+ const queued = item({
+ actor: commander,
+ fromActorId: 'user',
+ llmPayload: 'Do not send it. Keep it as a draft instead.',
+ });
+ const w = fakeW([queued]);
+
+ const events: AgentRunEvent[] = [];
+ for await (const event of runner.runStream({
+ message: 'Send the external message now.',
+ drainSteer: () => drainSteerInto(w, commander),
+ })) {
+ events.push(event);
+ }
+
+ const done = events.at(-1) as Extract<AgentRunEvent, { type: 'done' }>;
+ expect(done.result.text).toBe('Kept the message as a draft.');
+ expect(streamCalls).toBe(2);
+ expect(sideEffects).toBe(0);
+ expect(w.queue).toEqual([]);
+ expect(events.find((event) => event.type === 'tool_start')).toMatchObject({
+ id: 'send-1',
+ name: 'send_external_message',
+ });
+ expect(events.find((event) => event.type === 'tool_end')).toMatchObject({
+ id: 'send-1',
+ name: 'send_external_message',
+ result: 'Tool call skipped because a newer user instruction arrived before execution.',
+ isError: true,
+ durationMs: 0,
+ });
+ expect(JSON.stringify(requests[1])).toContain('Do not send it. Keep it as a draft instead.');
+ expect(requests[1].flatMap((message) => message.content)).toContainEqual({
+ type: 'tool_result',
+ toolUseId: 'send-1',
+ content: 'Tool call skipped because a newer user instruction arrived before execution.',
+ isError: true,
+ });
+ });
+
it('leaves an ordinary user message in FIFO unless Send now authorized steering', async () => {
const queued = item({
actor: commander,
diff --git a/test/main/features/group_chat/memory-write-verification.test.ts b/test/main/features/group_chat/memory-write-verification.test.ts
new file mode 100644
index 00000000..424766a5
--- /dev/null
+++ b/test/main/features/group_chat/memory-write-verification.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ claimsCompletedDurableMemoryWrite,
+ DurableMemoryWriteEvidence,
+ scrubCompletedDurableMemoryWriteClaims,
+} from '../../../../src/main/features/group_chat/memory-write-verification';
+
+function toolEvent(data: Record<string, unknown>) {
+ return { type: 'event', event: { stream: 'tool', data } };
+}
+
+describe('durable-memory write evidence', () => {
+ it('accepts a successful memory-write lifecycle', () => {
+ const evidence = new DurableMemoryWriteEvidence();
+ evidence.observe(toolEvent({
+ phase: 'start', id: 'mem-1', name: 'cross_session_memory',
+ arguments: { action: 'add', target: 'project', content: 'stable preference' },
+ }));
+ evidence.observe(toolEvent({
+ phase: 'end', id: 'mem-1', name: 'cross_session_memory', isError: false,
+ output: '{"ok":true}',
+ }));
+
+ expect(evidence.hasSuccessfulWrite()).toBe(true);
+ });
+
+ it('does not accept reads, failed writes, or unrelated successful tools', () => {
+ const evidence = new DurableMemoryWriteEvidence();
+ for (const [id, name, action, isError] of [
+ ['list-1', 'cross_session_memory', 'list', false],
+ ['write-1', 'cross_session_memory', 'replace', true],
+ ['remove-1', 'cross_session_memory', 'remove', false],
+ ['other-1', 'write_file', 'add', false],
+ ] as const) {
+ evidence.observe(toolEvent({ phase: 'start', id, name, arguments: { action } }));
+ evidence.observe(toolEvent({ phase: 'end', id, name, isError }));
+ }
+
+ expect(evidence.hasSuccessfulWrite()).toBe(false);
+ });
+
+ it('joins an early start with the later validated arguments', () => {
+ const evidence = new DurableMemoryWriteEvidence();
+ evidence.observe(toolEvent({ phase: 'start', id: 'mem-2', name: 'cross_session_memory' }));
+ evidence.observe(toolEvent({
+ phase: 'progress', id: 'mem-2', name: 'cross_session_memory',
+ arguments: { action: 'replace', target: 'project', old_text: 'old', content: 'new' },
+ }));
+ evidence.observe(toolEvent({
+ phase: 'end', id: 'mem-2', name: 'cross_session_memory', isError: false,
+ }));
+
+ expect(evidence.hasSuccessfulWrite()).toBe(true);
+ });
+});
+
+describe('unsupported durable-memory success claims', () => {
+ it('recognizes the sampled Chinese failure and English equivalents', () => {
+ expect(claimsCompletedDurableMemoryWrite(
+ '记下了,六条全部写入项目长期笔记,写代码时会逐条对照。',
+ )).toBe(true);
+ expect(claimsCompletedDurableMemoryWrite(
+ "I've saved all six rules to the project's persistent memory.",
+ )).toBe(true);
+ });
+
+ it('recognizes localized Japanese and Portuguese completion shapes', () => {
+ expect(claimsCompletedDurableMemoryWrite(
+ 'プロジェクトの長期メモリに保存しました。',
+ )).toBe(true);
+ expect(claimsCompletedDurableMemoryWrite(
+ 'Salvei as regras na memória persistente do projeto.',
+ )).toBe(true);
+ });
+
+ it('rejects future, negated, historical, and turn-local look-alikes', () => {
+ const rejected = [
+ '我会把这六条写入项目长期笔记。',
+ '这些内容尚未保存到项目长期记忆,请重试。',
+ '此前已经保存到项目长期记忆,本轮没有改动。',
+ '我记下当前讨论,供本轮回答使用。',
+ 'I will save this to persistent project memory after you confirm.',
+ 'I have not saved this to long-term memory.',
+ 'This was previously stored in project memory.',
+ ];
+ for (const text of rejected) {
+ expect(claimsCompletedDurableMemoryWrite(text), text).toBe(false);
+ }
+ });
+
+ it('does not treat ordinary profile, preference, or notes files as durable memory', () => {
+ const fileDeliveries = [
+ "I've saved the project profile to report.json.",
+ 'I saved the user preferences to settings.json.',
+ 'The project notes were successfully saved to NOTES.md.',
+ '项目档案已保存到 report.json。',
+ '项目笔记已经写入 NOTES.md。',
+ 'プロジェクトのメモを report.md に保存しました。',
+ 'O perfil do projeto foi salvo no arquivo report.json.',
+ ];
+ for (const text of fileDeliveries) {
+ expect(claimsCompletedDurableMemoryWrite(text), text).toBe(false);
+ }
+ });
+
+ it('still recognizes explicitly durable profile, preference, and notes claims', () => {
+ const durableClaims = [
+ '这些规则已保存到长期项目档案。',
+ "I've saved this to the persistent user profile.",
+ 'プロジェクトの長期メモに保存しました。',
+ 'Salvei no perfil persistente do projeto.',
+ ];
+ for (const text of durableClaims) {
+ expect(claimsCompletedDurableMemoryWrite(text), text).toBe(true);
+ }
+ });
+
+ it('removes only unsupported claim sentences and preserves useful delivery', () => {
+ const result = scrubCompletedDurableMemoryWriteClaims([
+ '记下了,六条全部写入项目长期笔记,写代码时会逐条对照。',
+ '',
+ '关于这套模拟器,我建议先固定状态转移规则,再实现界面。',
+ ].join('\n'));
+
+ expect(result.removedClaims).toBe(1);
+ expect(result.text).toBe('关于这套模拟器,我建议先固定状态转移规则,再实现界面。');
+ });
+
+ it('preserves quoted and code-fenced examples verbatim', () => {
+ const text = [
+ '> 错误示例:我已保存到项目长期记忆。',
+ '```text',
+ 'I have saved it to persistent project memory.',
+ '```',
+ '不要声称“已保存到项目长期记忆”。',
+ ].join('\n');
+
+ expect(scrubCompletedDurableMemoryWriteClaims(text)).toEqual({
+ text,
+ removedClaims: 0,
+ });
+ });
+});
diff --git a/test/main/features/group_chat/output-format.test.ts b/test/main/features/group_chat/output-format.test.ts
index 1d3ea3ed..961be811 100644
--- a/test/main/features/group_chat/output-format.test.ts
+++ b/test/main/features/group_chat/output-format.test.ts
@@ -14,7 +14,7 @@ import {
} from '../../../../src/main/features/local_agents/context';
describe('group-chat response language', () => {
- it('keeps prompt-internal descriptions in English while the selected turn language stays Chinese', async () => {
+ it('keeps prompt-internal descriptions in English while user language outranks the Chinese UI fallback', async () => {
const prompt = await _buildAgentInGroupSystemPromptForTest({
agent_id: 'language-contract-agent',
name: 'LanguageContractAgent',
@@ -25,7 +25,10 @@ describe('group-chat response language', () => {
expect(prompt).toContain('ENGLISH_DESCRIPTION_SHOULD_NOT_RENDER');
expect(prompt).not.toContain('仅中文运行说明');
- expect(prompt).toContain('User UI language: **Chinese (简体中文)**');
+ expect(prompt).toContain('Fallback UI language: **Chinese (简体中文)**');
+ expect(prompt).toContain('a current explicit user language request');
+ expect(prompt).toContain("the clear language of the user's latest substantive prose");
+ expect(prompt).toContain('Write all human-readable prose in the chosen language');
expect(prompt.lastIndexOf('## User language'))
.toBeGreaterThan(prompt.lastIndexOf('## Runtime injection'));
expect(prompt.lastIndexOf('## User language'))
diff --git a/test/main/features/group_chat/state.test.ts b/test/main/features/group_chat/state.test.ts
index f9177c56..96453ff7 100644
--- a/test/main/features/group_chat/state.test.ts
+++ b/test/main/features/group_chat/state.test.ts
@@ -385,3 +385,43 @@ describe('group_chat facade › runtimeStatus orphan recovery', () => {
expect(healed.in_flight).toEqual([]);
});
});
+
+// Two coding agents' FIRST turns in one conversation race the lazy
+// coding-project-dir initialisation. The conversation contract is one frozen
+// dir for its whole lifetime, so exactly one initialiser may win and both
+// racers must converge on the winner — a check-then-set outside the state
+// lock let the loser overwrite the winner while each turn ran in its own cwd.
+describe('group_chat state › setCodingProjectDirOnce', () => {
+ it('concurrent first-turn initialisers converge on exactly one winner', async () => {
+ const s = await import('../../../../src/main/features/group_chat/state');
+ const [a, b] = await Promise.all([
+ s.setCodingProjectDirOnce(TEST_UID, TEST_CID, '/proj/from-agent-a', { explicit: true }),
+ s.setCodingProjectDirOnce(TEST_UID, TEST_CID, '/proj/from-agent-b', { explicit: false }),
+ ]);
+ const winners = [a, b].filter((r) => r.applied);
+ expect(winners).toHaveLength(1);
+ const winnerDir = winners[0].state.coding_project_dir;
+ expect(['/proj/from-agent-a', '/proj/from-agent-b']).toContain(winnerDir);
+ // Both racers observe the SAME recorded dir, and disk agrees.
+ expect(a.state.coding_project_dir).toBe(winnerDir);
+ expect(b.state.coding_project_dir).toBe(winnerDir);
+ const persisted = await s.readState(TEST_UID, TEST_CID);
+ expect(persisted.coding_project_dir).toBe(winnerDir);
+ // The explicit flag belongs to the winner, not the loser.
+ expect(persisted.coding_project_dir_explicit === true)
+ .toBe(winnerDir === '/proj/from-agent-a');
+ });
+
+ it('never overwrites an existing dir and ignores a blank one', async () => {
+ const s = await import('../../../../src/main/features/group_chat/state');
+ await s.setCodingProjectDir(TEST_UID, TEST_CID, '/proj/user-chosen', { explicit: true });
+ const later = await s.setCodingProjectDirOnce(TEST_UID, TEST_CID, '/proj/other', { explicit: false });
+ expect(later.applied).toBe(false);
+ expect(later.state.coding_project_dir).toBe('/proj/user-chosen');
+ expect(later.state.coding_project_dir_explicit).toBe(true);
+
+ const blank = await s.setCodingProjectDirOnce(TEST_UID, 'cid-fresh', ' ', { explicit: false });
+ expect(blank.applied).toBe(false);
+ expect((await s.readState(TEST_UID, 'cid-fresh')).coding_project_dir).toBeUndefined();
+ });
+});
diff --git a/test/main/features/group_chat/visibility.test.ts b/test/main/features/group_chat/visibility.test.ts
index 628cf199..337a6fe6 100644
--- a/test/main/features/group_chat/visibility.test.ts
+++ b/test/main/features/group_chat/visibility.test.ts
@@ -186,6 +186,29 @@ describe('group_chat visibility › Commander canonical conversation history', (
expect(response).not.toContain('[Commander -> User]');
});
+ it('collapses repeated current actor attribution before adding one authoritative history label', async () => {
+ const v = await import('../../../../src/main/features/group_chat/visibility');
+ const attribution = 'VideoStudio (video-agent) replied to User:';
+ const rows = [
+ { id: 'u1', ts: 't1', from: 'user', to: ['video-agent'], text: 'Render the clip.' },
+ {
+ id: 'a1', ts: 't2', from: 'video-agent', to: ['user'],
+ text: `${attribution}\n\n${attribution}\n\nThe render is ready.`,
+ },
+ { id: 'u2', ts: 't3', from: 'user', to: ['commander'], text: 'Continue.' },
+ ] as any;
+
+ const history = v.buildCommanderConversationHistory(
+ rows,
+ 'u2',
+ new Map([['video-agent', 'VideoStudio']]),
+ );
+ const response = (history[1].content[0] as any).text;
+
+ expect(response).toContain('The render is ready.');
+ expect(response.match(/VideoStudio \(video-agent\) replied to User:/g)).toHaveLength(1);
+ });
+
it('normalizes the model-facing body rather than replaying a clean visible fallback', async () => {
const v = await import('../../../../src/main/features/group_chat/visibility');
const rows = [
@@ -240,7 +263,13 @@ describe('group_chat visibility › Commander canonical conversation history', (
{ id: 'u3', ts: 't5', from: 'user', to: ['commander'], text: 'Keep the unknown route.' },
{
id: 'a3', ts: 't6', from: 'commander', to: ['user'],
- text: '[Alice -> Bob]\nThis is ordinary content.',
+ text: [
+ '[Alice -> Bob]',
+ 'This inline mention of Commander replied to User: must remain.',
+ '```text',
+ 'Commander replied to User:',
+ '```',
+ ].join('\n'),
},
{ id: 'u4', ts: 't7', from: 'user', to: ['commander'], text: 'Continue.' },
] as any;
@@ -251,6 +280,8 @@ describe('group_chat visibility › Commander canonical conversation history', (
expect(serialized).toContain('This inline mention of [Commander -> User] must remain.');
expect(serialized).toContain('```text\\n[Commander -> User]\\n```');
expect(serialized).toContain('[Alice -> Bob]');
+ expect(serialized).toContain('This inline mention of Commander replied to User: must remain.');
+ expect(serialized).toContain('```text\\nCommander replied to User:\\n```');
});
it('does not replay a previously leaked internal history serialization', async () => {
diff --git a/test/main/features/local_agents/claude_e2e.test.ts b/test/main/features/local_agents/claude_e2e.test.ts
index d5b984c2..3fa7be64 100644
--- a/test/main/features/local_agents/claude_e2e.test.ts
+++ b/test/main/features/local_agents/claude_e2e.test.ts
@@ -801,6 +801,12 @@ process.stdin.on('data', (buf) => {
/** The initial foreground wall clock must be disabled while background work
* waits, then restarted from zero when Claude resumes model output. */
itPosix('restores a fresh foreground watchdog after background work wakes Claude', async () => {
+ // Leave enough headroom for the fake CLI process to receive its first CPU
+ // slice under the full parallel suite. The background delay still exceeds
+ // the cap plus one watchdog polling quantum, so a stale foreground
+ // watchdog would deterministically kill the process before it can resume.
+ const foregroundTimeoutMs = 2_000;
+ const backgroundDelayMs = foregroundTimeoutMs + Math.floor(foregroundTimeoutMs / 4) + 200;
const fake = writeNodeExecutable(tmpDir, 'claude', `
let started = false;
const w = (line) => process.stdout.write(line + '\\n');
@@ -814,7 +820,7 @@ process.stdin.on('data', (buf) => {
w('{"type":"system","subtype":"task_notification","task_id":"bg-1","status":"completed","summary":"slow job done"}');
w('{"type":"assistant","message":{"content":[{"type":"text","text":"foreground resumed"}]}}');
// No result follows. The newly armed foreground wall cap must stop us.
- }, 1_100);
+ }, ${backgroundDelayMs});
});
`);
const events: any[] = [];
@@ -830,7 +836,7 @@ process.stdin.on('data', (buf) => {
if (event.type === 'process-info') pid = Number(event.pid);
},
onBackgroundRun: () => {},
- timeoutMs: 800,
+ timeoutMs: foregroundTimeoutMs,
});
expect(events).toContainEqual(expect.objectContaining({
type: 'text-delta',
diff --git a/test/main/features/local_agents/claude_parser.test.ts b/test/main/features/local_agents/claude_parser.test.ts
index 5d909a4f..b2396e7d 100644
--- a/test/main/features/local_agents/claude_parser.test.ts
+++ b/test/main/features/local_agents/claude_parser.test.ts
@@ -137,6 +137,51 @@ describe('local_agents/backends/claude › mapClaudeEvent', () => {
]);
});
+ it('does NOT publish images that came back from a file-read tool', () => {
+ // Read hands the file back as an image block. Treating that as generated
+ // media bounced whatever the agent looked at — including the user's own
+ // upload — into the reply as `![generated image]`.
+ const state = { sawTextStreamEvent: false, toolNamesByCallId: new Map<string, string>() };
+ mapClaudeEvent({
+ type: 'assistant',
+ message: { content: [{ type: 'tool_use', id: 'read-1', name: 'Read', input: { file_path: '/tmp/shot.png' } }] },
+ }, 'sess', state);
+ const r = mapClaudeEvent({
+ type: 'user',
+ message: { content: [{ type: 'tool_result', tool_use_id: 'read-1', content: [
+ { type: 'text', text: 'read ok' },
+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'AAAA' } },
+ ] }] },
+ }, 'sess', state);
+ // packClaudeEvents collapses a single event onto `event`; normalize.
+ const emitted = r?.events ?? (r?.event ? [r.event] : []);
+ expect(emitted).toEqual([
+ { type: 'tool-event', tool: 'tool_result', callId: 'read-1', phase: 'result', output: 'read ok' },
+ ]);
+ expect(state.toolNamesByCallId.has('read-1')).toBe(false);
+ });
+
+ it('still publishes images from a non-read tool', () => {
+ const state = { sawTextStreamEvent: false, toolNamesByCallId: new Map<string, string>() };
+ mapClaudeEvent({
+ type: 'assistant',
+ message: { content: [{ type: 'tool_use', id: 'gen-1', name: 'mcp__image__generate', input: {} }] },
+ }, 'sess', state);
+ const r = mapClaudeEvent({
+ type: 'user',
+ message: { content: [{ type: 'tool_result', tool_use_id: 'gen-1', content: [
+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'BBBB' } },
+ ] }] },
+ }, 'sess', state);
+ const emitted = r?.events ?? (r?.event ? [r.event] : []);
+ expect(emitted).toContainEqual({
+ type: 'media-output',
+ source: 'claude',
+ callId: 'gen-1',
+ items: [{ data: 'BBBB', mediaType: 'image/png' }],
+ });
+ });
+
it('keeps every tool result in a multi-result user message', () => {
const r = mapClaudeEvent({
type: 'user',
diff --git a/test/main/features/platform-foundations.test.ts b/test/main/features/platform-foundations.test.ts
index 95899c86..e2402be3 100644
--- a/test/main/features/platform-foundations.test.ts
+++ b/test/main/features/platform-foundations.test.ts
@@ -5,7 +5,6 @@ import {
} from '../../../src/main/features/marketplace_locks';
import {
macosTccSensitivePath,
- macosTccWorkspaceBlockedPath,
} from '../../../src/main/util/macos-tcc';
describe('platform foundations', () => {
@@ -40,8 +39,8 @@ describe('platform foundations', () => {
const home = process.env.HOME || '';
expect(macosTccSensitivePath(`${home}/Documents/project`)?.reason).toBe('documents');
expect(macosTccSensitivePath(`${home}/Doc`)?.reason).toBeUndefined();
- expect(macosTccWorkspaceBlockedPath(home)?.reason).toBe('home');
- expect(macosTccWorkspaceBlockedPath('/tmp')).toBeNull();
+ expect(macosTccSensitivePath(home, { recursive: true })?.reason).toBe('home');
+ expect(macosTccSensitivePath('/tmp', { recursive: true })).toBeNull();
expect(macosTccSensitivePath('relative/path')).toBeNull();
});
});
diff --git a/test/main/features/system_skills.test.ts b/test/main/features/system_skills.test.ts
index 1f598e72..0b4e1cb8 100644
--- a/test/main/features/system_skills.test.ts
+++ b/test/main/features/system_skills.test.ts
@@ -399,7 +399,8 @@ describe('system skill contracts', () => {
expect(fm).toMatch(/^description_zh:\s*/m);
expect(fm).toMatch(/^description_en:\s*/m);
expect(fm).toMatch(/remember this/i);
- expect(fm).toMatch(/read-only questions/i);
+ expect(fm).toMatch(/across future conversations/i);
+ expect(fm).toMatch(/read-only recall/i);
expect(md).toContain('target: "agent"');
expect(md).toContain('target: "user"');
expect(md).toContain('target: "shared"');
diff --git a/test/main/features/user_workspace.test.ts b/test/main/features/user_workspace.test.ts
index fec99eaf..5ba10a11 100644
--- a/test/main/features/user_workspace.test.ts
+++ b/test/main/features/user_workspace.test.ts
@@ -1,7 +1,11 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { createRequire, syncBuiltinESMExports } from 'node:module';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const nodeRequire = createRequire(import.meta.url);
vi.mock('../../../src/main/logger', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
@@ -54,6 +58,85 @@ async function _pinZh() {
i18n.setCurrentLang('zh');
}
+function _recordSensitiveFsCalls(sensitiveRoot: string): {
+ calls: string[];
+ restore(): void;
+} {
+ const mutableFs = nodeRequire('node:fs') as Record<string, any>;
+ const root = path.resolve(sensitiveRoot);
+ const calls: string[] = [];
+ const originals = new Map<string, (...args: any[]) => any>();
+ const promiseOriginals = new Map<string, (...args: any[]) => any>();
+ const operationNames = [
+ 'accessSync',
+ 'existsSync',
+ 'lstatSync',
+ 'openSync',
+ 'opendirSync',
+ 'readFileSync',
+ 'readdirSync',
+ 'realpathSync',
+ 'statSync',
+ ];
+
+ const resolveTarget = (value: unknown): string => {
+ try {
+ if (typeof value === 'string') return path.resolve(value);
+ if (Buffer.isBuffer(value)) return path.resolve(value.toString());
+ if (value instanceof URL && value.protocol === 'file:') return path.resolve(fileURLToPath(value));
+ } catch { /* malformed inputs are not relevant to this probe */ }
+ return '';
+ };
+ const record = (operation: string, value: unknown): void => {
+ const target = resolveTarget(value);
+ if (!target) return;
+ const rel = path.relative(root, target);
+ if (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))) {
+ calls.push(`${operation}:${rel || '.'}`);
+ }
+ };
+
+ for (const name of operationNames) {
+ const original = mutableFs[name];
+ if (typeof original !== 'function') continue;
+ originals.set(name, original);
+ mutableFs[name] = function sensitiveFsProbe(this: unknown, ...args: any[]) {
+ record(name, args[0]);
+ return Reflect.apply(original, this, args);
+ };
+ }
+ for (const name of ['access', 'lstat', 'open', 'opendir', 'readFile', 'readdir', 'realpath', 'stat']) {
+ const original = mutableFs.promises?.[name];
+ if (typeof original !== 'function') continue;
+ promiseOriginals.set(name, original);
+ mutableFs.promises[name] = function sensitivePromiseFsProbe(this: unknown, ...args: any[]) {
+ record(`promises.${name}`, args[0]);
+ return Reflect.apply(original, this, args);
+ };
+ }
+ const wrappedRealpath = mutableFs.realpathSync;
+ const originalRealpathNative = originals.get('realpathSync')?.native;
+ if (typeof originalRealpathNative === 'function') {
+ wrappedRealpath.native = function sensitiveNativeRealpathProbe(this: unknown, ...args: any[]) {
+ record('realpathSync.native', args[0]);
+ return Reflect.apply(originalRealpathNative, this, args);
+ };
+ }
+ syncBuiltinESMExports();
+
+ return {
+ calls,
+ restore() {
+ for (const [name, original] of originals) mutableFs[name] = original;
+ for (const [name, original] of promiseOriginals) mutableFs.promises[name] = original;
+ if (typeof originalRealpathNative === 'function') {
+ mutableFs.realpathSync.native = originalRealpathNative;
+ }
+ syncBuiltinESMExports();
+ },
+ };
+}
+
describe('user_workspace › getWorkspacePath', () => {
it('returns default when no selection has been made', async () => {
const ws = await import('../../../src/main/features/user_workspace');
@@ -119,8 +202,7 @@ describe('user_workspace › setWorkspacePath', () => {
if (result.ok) expect(result.path).toBe(dir);
});
- it.runIf(process.platform === 'darwin')('rejects macOS privacy-protected workspace roots selected by the user', async () => {
- await _pinZh();
+ it.runIf(process.platform === 'darwin')('persists user-selected macOS privacy-protected workspace roots without probing them again', async () => {
process.env.ORKAS_TCC_GUARD_FORCE = '1';
const home = path.join(tmpDir, 'fake-home');
const protectedRoots = [
@@ -144,17 +226,25 @@ describe('user_workspace › setWorkspacePath', () => {
const userId = `userProtected${idx}`;
const result = ws.setWorkspacePath(userId, protectedRoot);
- expect(result.ok).toBe(false);
- if (!result.ok) expect(result.error).toContain('隐私保护');
-
- expect(ws.getWorkspacePath(userId)).toBe(p.DEFAULT_USER_WORKSPACE);
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(result.path).toBe(protectedRoot);
+ expect(ws.getWorkspacePath(userId)).toBe(protectedRoot);
const info = ws.getWorkspaceInfo(userId);
- expect(info.currentPath).toBe(p.DEFAULT_USER_WORKSPACE);
+ expect(info.currentPath).toBe(protectedRoot);
+ expect(info.defaultPath).toBe(p.DEFAULT_USER_WORKSPACE);
+ expect(info.isDefault).toBe(false);
+
+ const cfgFile = path.join(tmpDir, userId, 'local', 'workspace.json');
+ const persisted = JSON.parse(fs.readFileSync(cfgFile, 'utf-8'));
+ expect(persisted.default.macosTccSensitive).toBe(true);
}
+
+ const downloads = path.join(home, 'Downloads');
+ fs.rmSync(downloads, { recursive: true, force: true });
+ expect(ws.getWorkspacePath('userProtected1')).toBe(downloads);
});
- it.runIf(process.platform === 'darwin')('rejects a symlink alias that resolves into a protected macOS workspace root', async () => {
- await _pinZh();
+ it.runIf(process.platform === 'darwin')('classifies a selected symlink alias into a protected macOS root once and keeps the user-facing path', async () => {
process.env.ORKAS_TCC_GUARD_FORCE = '1';
const home = path.join(tmpDir, 'fake-home');
const desktopProject = path.join(home, 'Desktop', 'project');
@@ -166,8 +256,13 @@ describe('user_workspace › setWorkspacePath', () => {
const result = ws.setWorkspacePath('userSymlinkProtected', alias);
- expect(result.ok).toBe(false);
- if (!result.ok) expect(result.error).toContain('隐私保护');
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(result.path).toBe(alias);
+ const cfgFile = path.join(tmpDir, 'userSymlinkProtected', 'local', 'workspace.json');
+ const persisted = JSON.parse(fs.readFileSync(cfgFile, 'utf-8'));
+ expect(persisted.default.macosTccSensitive).toBe(true);
+ fs.rmSync(alias);
+ expect(ws.getWorkspacePath('userSymlinkProtected')).toBe(alias);
});
it.runIf(process.platform !== 'win32')('accepts a symlink to an ordinary project without rewriting the selected path', async () => {
@@ -269,8 +364,7 @@ describe('user_workspace › selectDirectory (mocked)', () => {
expect(result).toBe(dir);
});
- it.runIf(process.platform === 'darwin')('does not persist a protected directory returned by the native picker', async () => {
- await _pinZh();
+ it.runIf(process.platform === 'darwin')('persists a protected directory returned by the native picker', async () => {
process.env.ORKAS_TCC_GUARD_FORCE = '1';
const home = path.join(tmpDir, 'fake-home');
const downloads = path.join(home, 'Downloads');
@@ -288,8 +382,71 @@ describe('user_workspace › selectDirectory (mocked)', () => {
expect(selected).toBe(downloads);
const result = ws.setWorkspacePath('userPickerProtected', selected!);
- expect(result.ok).toBe(false);
- expect(ws.getWorkspacePath('userPickerProtected')).toBe(p.DEFAULT_USER_WORKSPACE);
+ expect(result.ok).toBe(true);
+ expect(ws.getWorkspacePath('userPickerProtected')).toBe(downloads);
+ expect(ws.consumePickerFirstOpenDefault('userPickerProtected')).toBe(p.DEFAULT_USER_WORKSPACE);
+ });
+
+ it.runIf(process.platform === 'darwin')('does not issue prompt-triggering filesystem probes after selecting or restoring a protected workspace', async () => {
+ process.env.ORKAS_TCC_GUARD_FORCE = '1';
+ const home = path.join(tmpDir, 'fake-home');
+ const documents = path.join(home, 'Documents', 'active-project');
+ fs.mkdirSync(documents, { recursive: true });
+ process.env.HOME = home;
+ vi.resetModules();
+ const { dialog } = await import('electron');
+ (dialog.showOpenDialog as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
+ canceled: false,
+ filePaths: [documents],
+ });
+ const probe = _recordSensitiveFsCalls(path.join(home, 'Documents'));
+
+ try {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const p = await import('../../../src/main/paths');
+ const selected = await ws.selectDirectory();
+
+ expect(selected).toBe(documents);
+ expect(ws.setWorkspacePath('userNoTccPrompt', selected!).ok).toBe(true);
+ expect(ws.getWorkspacePath('userNoTccPrompt')).toBe(documents);
+ expect(ws.getWorkspaceInfo('userNoTccPrompt')).toMatchObject({
+ currentPath: documents,
+ isDefault: false,
+ });
+ expect(ws.consumePickerFirstOpenDefault('userNoTccPrompt')).toBe(p.DEFAULT_USER_WORKSPACE);
+ expect(ws.sweepEmptyConvDirs('userNoTccPrompt')).toEqual({ swept: 0 });
+
+ // Reload the feature module to model a fresh app process reading the
+ // persisted workspace classification. Passive boot/UI reads must still
+ // avoid the selected TCC root.
+ vi.resetModules();
+ const relaunched = await import('../../../src/main/features/user_workspace');
+ expect(relaunched.getWorkspacePath('userNoTccPrompt')).toBe(documents);
+ expect(relaunched.getWorkspaceInfo('userNoTccPrompt').currentPath).toBe(documents);
+ expect(relaunched.consumePickerFirstOpenDefault('userNoTccPrompt')).toBe(p.DEFAULT_USER_WORKSPACE);
+
+ expect(probe.calls).toEqual([]);
+ } finally {
+ probe.restore();
+ }
+ });
+
+ it.runIf(process.platform === 'darwin')('fails the TCC probe oracle when sensitive filesystem access occurs', async () => {
+ const documents = path.join(tmpDir, 'fake-home', 'Documents', 'negative-control');
+ fs.mkdirSync(documents, { recursive: true });
+ const probe = _recordSensitiveFsCalls(documents);
+ try {
+ fs.statSync(documents);
+ fs.realpathSync.native(documents);
+ await fs.promises.stat(documents);
+ expect(probe.calls).toEqual([
+ 'statSync:.',
+ 'realpathSync.native:.',
+ 'promises.stat:.',
+ ]);
+ } finally {
+ probe.restore();
+ }
});
});
@@ -390,7 +547,7 @@ describe('user_workspace › scoped (projects)', () => {
expect(info.recentPaths).toContain(protectedRecent);
});
- it.runIf(process.platform === 'darwin')('falls back from a legacy protected selectedPath without statting it', async () => {
+ it.runIf(process.platform === 'darwin')('restores a legacy protected selectedPath without statting it', async () => {
process.env.ORKAS_TCC_GUARD_FORCE = '1';
const home = path.join(tmpDir, 'fake-home');
const desktop = path.join(home, 'Desktop');
@@ -405,16 +562,19 @@ describe('user_workspace › scoped (projects)', () => {
updatedAt: '2026-06-03T00:00:00.000Z',
recentPaths: [path.join(home, 'Downloads')],
}));
+ fs.rmSync(desktop, { recursive: true, force: true });
- expect(ws.getWorkspacePath('userLegacyProtected')).toBe(p.DEFAULT_USER_WORKSPACE);
+ expect(ws.getWorkspacePath('userLegacyProtected')).toBe(desktop);
const info = ws.getWorkspaceInfo('userLegacyProtected');
- expect(info.currentPath).toBe(p.DEFAULT_USER_WORKSPACE);
+ expect(info.currentPath).toBe(desktop);
expect(info.defaultPath).toBe(p.DEFAULT_USER_WORKSPACE);
- expect(info.isDefault).toBe(true);
+ expect(info.isDefault).toBe(false);
expect(info.recentPaths).toEqual([]);
+ const migrated = JSON.parse(fs.readFileSync(cfgFile, 'utf-8'));
+ expect(migrated.default.macosTccSensitive).toBe(true);
});
- it.runIf(process.platform === 'darwin')('falls back from a legacy symlink that resolves into a protected workspace root', async () => {
+ it.runIf(process.platform === 'darwin')('restores a legacy symlink that resolves into a protected workspace root', async () => {
process.env.ORKAS_TCC_GUARD_FORCE = '1';
const home = path.join(tmpDir, 'fake-home');
const downloadsProject = path.join(home, 'Downloads', 'legacy-project');
@@ -423,7 +583,6 @@ describe('user_workspace › scoped (projects)', () => {
fs.symlinkSync(downloadsProject, alias, 'dir');
process.env.HOME = home;
const ws = await import('../../../src/main/features/user_workspace');
- const p = await import('../../../src/main/paths');
const cfgFile = path.join(tmpDir, 'userLegacySymlink', 'local', 'workspace.json');
fs.mkdirSync(path.dirname(cfgFile), { recursive: true });
fs.writeFileSync(cfgFile, JSON.stringify({
@@ -432,7 +591,9 @@ describe('user_workspace › scoped (projects)', () => {
recentPaths: [],
}));
- expect(ws.getWorkspacePath('userLegacySymlink')).toBe(p.DEFAULT_USER_WORKSPACE);
+ expect(ws.getWorkspacePath('userLegacySymlink')).toBe(alias);
+ const migrated = JSON.parse(fs.readFileSync(cfgFile, 'utf-8'));
+ expect(migrated.default.macosTccSensitive).toBe(true);
});
it('reset on project scope falls through to default; default scope intact', async () => {
@@ -560,6 +721,31 @@ describe('user_workspace › openWorkspaceInFileManager', () => {
if (!result.ok) expect(result.error).toBe('boom');
});
+ it.runIf(process.platform === 'darwin')('opens a user-selected protected workspace without a preflight filesystem probe', async () => {
+ process.env.ORKAS_TCC_GUARD_FORCE = '1';
+ const home = path.join(tmpDir, 'fake-home');
+ const downloads = path.join(home, 'Downloads', 'active-workspace');
+ fs.mkdirSync(downloads, { recursive: true });
+ process.env.HOME = home;
+ vi.resetModules();
+ const { shell } = await import('electron');
+ (shell.openPath as ReturnType<typeof vi.fn>).mockClear();
+ const probe = _recordSensitiveFsCalls(path.join(home, 'Downloads'));
+
+ try {
+ const ws = await import('../../../src/main/features/user_workspace');
+ expect(ws.setWorkspacePath('userOpenProtected', downloads).ok).toBe(true);
+
+ const result = await ws.openWorkspaceInFileManager('userOpenProtected');
+
+ expect(result).toEqual({ ok: true, path: downloads });
+ expect(shell.openPath).toHaveBeenCalledWith(downloads);
+ expect(probe.calls).toEqual([]);
+ } finally {
+ probe.restore();
+ }
+ });
+
it('refuses to open when the workspace directory is gone (falls back to default)', async () => {
// When selection vanishes, getWorkspacePath falls back to default —
// and the default is guaranteed to exist by paths.ensureLayout; verify
diff --git a/test/main/i18n.test.ts b/test/main/i18n.test.ts
index 4a318374..de9fef08 100644
--- a/test/main/i18n.test.ts
+++ b/test/main/i18n.test.ts
@@ -86,7 +86,7 @@ describe('i18n › t() lookup', () => {
.toBe('技能「arxiv-reader」已被停用,请重新启用后再使用。');
});
- it('localizes the managed Pro fallback notice in every supported language', () => {
+ it('localizes the fallback notice in every supported language', () => {
const vars = { from: 'Orkas-1.5 Pro', to: 'Orkas-1.5' };
expect(t('model.server_model_fallback', vars, 'zh'))
.toBe('Orkas-1.5 Pro 暂不可用,已由 Orkas-1.5 处理。');
diff --git a/test/main/model/core-agent/file-tools.test.ts b/test/main/model/core-agent/file-tools.test.ts
index 75f8d0c6..07ac31e1 100644
--- a/test/main/model/core-agent/file-tools.test.ts
+++ b/test/main/model/core-agent/file-tools.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { createRequire, syncBuiltinESMExports } from 'node:module';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
@@ -7,6 +8,8 @@ import { makeMinimalPdf } from '../../../fixtures/make-minimal-pdf';
import { makeMinimalDocx } from '../../../fixtures/make-minimal-docx';
import { makeMinimalXlsx, makeMinimalPptx } from '../../../fixtures/make-minimal-office';
+const nodeRequire = createRequire(import.meta.url);
+
vi.mock('../../../../src/main/logger', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
@@ -21,6 +24,55 @@ let prevWs: string | undefined;
let prevHome: string | undefined;
let prevGuard: string | undefined;
+function faultStatForPath(targetPath: string, code: 'EACCES' | 'EPERM'): {
+ statAttempts: string[];
+ parentReaddirAttempts: string[];
+ restore(): void;
+} {
+ const mutableFs = nodeRequire('node:fs') as Record<string, any>;
+ const originalStatSync = mutableFs.statSync;
+ const originalReaddirSync = mutableFs.readdirSync;
+ const target = path.resolve(targetPath);
+ const parent = path.dirname(target);
+ const statAttempts: string[] = [];
+ const parentReaddirAttempts: string[] = [];
+ const resolveArg = (value: unknown): string => {
+ if (typeof value === 'string') return path.resolve(value);
+ if (Buffer.isBuffer(value)) return path.resolve(value.toString());
+ return '';
+ };
+
+ mutableFs.statSync = function injectedStatFailure(this: unknown, ...args: any[]) {
+ const requested = resolveArg(args[0]);
+ if (requested === target) {
+ statAttempts.push(requested);
+ throw Object.assign(new Error(`${code}: permission denied, stat '${target}'`), {
+ code,
+ errno: code === 'EACCES' ? -13 : -1,
+ path: target,
+ syscall: 'stat',
+ });
+ }
+ return Reflect.apply(originalStatSync, this, args);
+ };
+ mutableFs.readdirSync = function recordParentRead(this: unknown, ...args: any[]) {
+ const requested = resolveArg(args[0]);
+ if (requested === parent) parentReaddirAttempts.push(requested);
+ return Reflect.apply(originalReaddirSync, this, args);
+ };
+ syncBuiltinESMExports();
+
+ return {
+ statAttempts,
+ parentReaddirAttempts,
+ restore() {
+ mutableFs.statSync = originalStatSync;
+ mutableFs.readdirSync = originalReaddirSync;
+ syncBuiltinESMExports();
+ },
+ };
+}
+
beforeEach(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-filetools-'));
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
@@ -1247,6 +1299,33 @@ describe('file-tools › read_files', () => {
expect(r.content).toContain('E_NOT_FOUND');
});
+ it.each(['EACCES', 'EPERM'] as const)(
+ 'reports %s as permission denied without scanning the parent directory for renamed siblings',
+ async (osCode) => {
+ const { tools, wsDir } = await buildTools();
+ const denied = path.join(wsDir, 'permission-denied.txt');
+ fs.writeFileSync(denied, 'must not be read');
+ const fault = faultStatForPath(denied, osCode);
+
+ try {
+ const result = await run(getTool(tools, 'read_files'), {
+ paths: [{ path: denied }],
+ });
+
+ expect(result.isError).toBe(true);
+ expect(result.content).toContain('E_PERMISSION_DENIED');
+ expect(result.content).toContain(`os_code=${osCode}`);
+ expect(result.content).not.toContain('E_NOT_FOUND');
+ expect(result.content).not.toContain('<missing-file-recovery>');
+ expect(result.content).not.toContain('<file-renamed-earlier>');
+ expect(fault.statAttempts).toEqual([denied]);
+ expect(fault.parentReaddirAttempts).toEqual([]);
+ } finally {
+ fault.restore();
+ }
+ },
+ );
+
it('bounds omitted ranges to a 24K-character slice', async () => {
const { tools, wsDir } = await buildTools();
const large = path.join(wsDir, 'large.txt');
@@ -1587,7 +1666,7 @@ describe('file-tools › search_files', () => {
expect(r.content).toContain('MOCK_SYNC_CONFLICT.md');
});
- it.runIf(process.platform === 'darwin')('does not recursively scan a legacy privacy-protected workspace root', async () => {
+ it.runIf(process.platform === 'darwin')('keeps a legacy privacy-protected workspace active without recursively scanning it', async () => {
process.env.ORKAS_TCC_GUARD_FORCE = '1';
const home = path.join(tmpDir, 'home');
const downloads = path.join(home, 'Downloads');
@@ -1598,8 +1677,6 @@ describe('file-tools › search_files', () => {
const users = await import('../../../../src/main/features/users');
users.activateUser(UID);
const paths = await import('../../../../src/main/paths');
- fs.mkdirSync(paths.DEFAULT_USER_WORKSPACE, { recursive: true });
- fs.writeFileSync(path.join(paths.DEFAULT_USER_WORKSPACE, 'public-note.md'), 'public');
const cfgFile = paths.userWorkspaceConfigFile(UID);
fs.mkdirSync(path.dirname(cfgFile), { recursive: true });
fs.writeFileSync(cfgFile, JSON.stringify({
@@ -1608,7 +1685,7 @@ describe('file-tools › search_files', () => {
recentPaths: [],
}), 'utf8');
const ws = await import('../../../../src/main/features/user_workspace');
- expect(ws.getWorkspacePath(UID)).toBe(paths.DEFAULT_USER_WORKSPACE);
+ expect(ws.getWorkspacePath(UID)).toBe(downloads);
fs.mkdirSync(attachmentDir(), { recursive: true });
const mod = await import('../../../../src/main/model/core-agent/file-tools');
const tools = mod.createFileTools({ userId: UID, cid: CID });
@@ -1616,7 +1693,7 @@ describe('file-tools › search_files', () => {
const r = await run(getTool(tools, 'search_files'), { query: '' });
expect(r.isError).toBeFalsy();
- expect(r.content).toContain('public-note.md');
+ expect(r.content).toContain('No files were scanned in the privacy-protected workspace');
expect(r.content).not.toContain('secret-contract.md');
});
diff --git a/test/main/model/core-agent/injected-tool-fixture.ts b/test/main/model/core-agent/injected-tool-fixture.ts
index 50866d68..4bfa4e29 100644
--- a/test/main/model/core-agent/injected-tool-fixture.ts
+++ b/test/main/model/core-agent/injected-tool-fixture.ts
@@ -99,6 +99,8 @@ export function enumerateAllInjectedToolNames(): Set<string> {
'dispatch_to',
'hand_off_to',
'run_worker',
+ 'open_app_view',
+ 'app_health',
'skill_manage',
'tool_load',
]) names.add(name);
diff --git a/test/main/model/core-agent/local-tools.test.ts b/test/main/model/core-agent/local-tools.test.ts
index 9437eb3e..d775d35c 100644
--- a/test/main/model/core-agent/local-tools.test.ts
+++ b/test/main/model/core-agent/local-tools.test.ts
@@ -1874,3 +1874,89 @@ describe('bash path refusal wording', () => {
expect(truncateForMessage('project/render/run.sh')).toBe('project/render/run.sh');
});
});
+
+// Two parallel agent turns in one conversation share the workspace cwd, and
+// identical instructions make identical basenames likely. The wrapped tool
+// must route probe+write through the per-path lock so neither delivery is
+// silently clobbered (plain check-then-act loses one — the owning-boundary
+// mutation control lives in test/main/util/uniquify-path.test.ts).
+describe('local-tools › write_file › concurrent same-target writers', () => {
+ it('two agents writing one basename both keep their delivery', async () => {
+ await allFilesAuto();
+ const { write: writeA, wsDir } = await buildWriteTool();
+ const { write: writeB } = await buildWriteTool();
+ const p = path.join(wsDir, 'deliverable.md');
+ const [ra, rb] = await Promise.all([
+ writeA.execute({ path: p, content: 'agent-A content' }, { workingDir: '.', signal: undefined, state: {} } as any),
+ writeB.execute({ path: p, content: 'agent-B content' }, { workingDir: '.', signal: undefined, state: {} } as any),
+ ]);
+ expect(ra.isError).toBeFalsy();
+ expect(rb.isError).toBeFalsy();
+ const expected = [p, path.join(wsDir, 'deliverable-2.md')];
+ for (const f of expected) expect(fs.existsSync(f)).toBe(true);
+ expect(expected.map((f) => fs.readFileSync(f, 'utf8')).sort()).toEqual(
+ ['agent-A content', 'agent-B content'],
+ );
+ expect([ra, rb].filter((r) => String(r.content).includes('<file-renamed>'))).toHaveLength(1);
+ });
+});
+
+// The PDF writers render INSIDE the probe+write lock (the render is what
+// materializes the file), and this restructure moved their scope-reject and
+// render-failure paths into the locked closure. Wiring evidence with the
+// render mocked: success carries the receipt, a failed render surfaces the
+// error without a file, and two concurrent same-target renders suffix instead
+// of clobbering (the real-render path stays covered by manual smoke — mock
+// blind spot recorded).
+describe('local-tools › markdown_to_pdf › locked probe+render wiring', () => {
+ it('renders to the decided path, maps render failure to isError, and keeps concurrent deliveries apart', async () => {
+ await allFilesAuto();
+ vi.resetModules();
+ vi.doMock('../../../../src/main/util/md-to-pdf', () => ({
+ markdownToPdf: vi.fn(async (_md: string, outPath: string) => {
+ fs.writeFileSync(outPath, `%PDF-fake:${path.basename(outPath)}`);
+ }),
+ htmlToPdf: vi.fn(async () => { throw new Error('boom'); }),
+ }));
+ try {
+ // vi.resetModules dropped the module-level active user + permission
+ // mode — re-establish both against the freshly loaded module graph.
+ const users = await import('../../../../src/main/features/users');
+ users.activateUser(UID);
+ await allFilesAuto();
+ const localTools = await import('../../../../src/main/model/core-agent/local-tools');
+ const ws = await import('../../../../src/main/features/user_workspace');
+ const wsDir = path.join(tmpDir, 'ws');
+ fs.mkdirSync(wsDir, { recursive: true });
+ const r = ws.setWorkspacePath(UID, wsDir);
+ if (!r.ok) throw new Error(`setWorkspacePath failed: ${r.error}`);
+ const mkTools = () => localTools.createLocalTools({ userId: UID, cid: CID });
+ const ctx = () => ({ workingDir: '.', signal: undefined, state: {} } as any);
+ const pdfA = mkTools().find((t) => t.name === 'create_pdf')!;
+ const pdfB = mkTools().find((t) => t.name === 'create_pdf')!;
+
+ const target = path.join(wsDir, 'summary.pdf');
+ const [ra, rb] = await Promise.all([
+ pdfA.execute({ source_type: 'markdown', path: target, content: '# A' }, ctx()),
+ pdfB.execute({ source_type: 'markdown', path: target, content: '# B' }, ctx()),
+ ]);
+ expect(ra.isError).toBeFalsy();
+ expect(rb.isError).toBeFalsy();
+ expect(fs.existsSync(target)).toBe(true);
+ expect(fs.existsSync(path.join(wsDir, 'summary-2.pdf'))).toBe(true);
+ expect([ra, rb].filter((res) => String(res.content).includes('<file-renamed>'))).toHaveLength(1);
+
+ // Failed render: the html branch's mock throws — the user gets an
+ // actionable error result, not a crash, and no file appears.
+ const failed = await pdfA.execute(
+ { source_type: 'html', path: path.join(wsDir, 'broken.pdf'), content: '<h1>x</h1>' }, ctx(),
+ );
+ expect(failed.isError).toBe(true);
+ expect(String(failed.content)).toContain('Error generating PDF');
+ expect(fs.existsSync(path.join(wsDir, 'broken.pdf'))).toBe(false);
+ } finally {
+ vi.doUnmock('../../../../src/main/util/md-to-pdf');
+ vi.resetModules();
+ }
+ });
+});
diff --git a/test/main/model/core-agent/tool-behavior-coverage.test.ts b/test/main/model/core-agent/tool-behavior-coverage.test.ts
index df48ddf6..08bfd13f 100644
--- a/test/main/model/core-agent/tool-behavior-coverage.test.ts
+++ b/test/main/model/core-agent/tool-behavior-coverage.test.ts
@@ -65,6 +65,8 @@ const BEHAVIOR_SUITE_BY_TOOL: Record<string, string> = {
dispatch_to: 'test/main/features/group_chat/bus-integration.test.ts',
hand_off_to: 'test/main/features/group_chat/bus-integration.test.ts',
run_worker: 'test/main/features/group_chat/bus-integration.test.ts',
+ open_app_view: 'test/main/features/group_chat/bus-integration.test.ts',
+ app_health: 'test/main/features/group_chat/bus-integration.test.ts',
tool_load: 'test/main/model/core-agent/tool-surface.test.ts',
};
diff --git a/test/main/model/core-agent/tool-catalog.test.ts b/test/main/model/core-agent/tool-catalog.test.ts
index 48a8d009..b97d257b 100644
--- a/test/main/model/core-agent/tool-catalog.test.ts
+++ b/test/main/model/core-agent/tool-catalog.test.ts
@@ -121,7 +121,7 @@ describe('tool-catalog', () => {
expect(missing, `Injected tools missing from TOOL_CATALOG: ${missing.join(', ')}`).toEqual([]);
const stale = [...catalog].filter((n) => !injected.has(n));
expect(stale, `Catalog tools missing from injected fixture: ${stale.join(', ')}`).toEqual([]);
- expect(catalog.size).toBe(53);
+ expect(catalog.size).toBe(55);
});
it('TOOL_CATALOG has no duplicate names', () => {
@@ -215,11 +215,28 @@ describe('tool-catalog', () => {
it('separates runtime-loadable groups from Agent dependency groups', () => {
expect(LOADABLE_TOOL_GROUP_IDS).toContain('management');
+ expect(LOADABLE_TOOL_GROUP_IDS).toEqual(expect.arrayContaining([
+ 'management.app',
+ 'management.skills',
+ 'management.marketplace',
+ 'management.automation',
+ ]));
expect(AGENT_DEPENDENCY_TOOL_GROUP_IDS).not.toContain('management');
expect(TOOL_GROUPS.find((group) => group.id === 'management')).toMatchObject({
activation: 'loadable',
agentDependency: false,
});
+ expect(TOOL_GROUPS.filter((group) => group.parent === 'management').map((group) => group.id))
+ .toEqual([
+ 'management.app',
+ 'management.skills',
+ 'management.marketplace',
+ 'management.automation',
+ ]);
+ expect(TOOL_GROUPS.filter((group) => group.parent === 'management'))
+ .toEqual(expect.arrayContaining([
+ expect.objectContaining({ activation: 'loadable', agentDependency: false }),
+ ]));
expect(invalidToolGroupRefs(['management'])).toEqual([]);
expect(canonicalizeToolGroups(['management'])).toEqual(['management']);
expect(invalidAgentToolGroupRefs(['management'])).toEqual(['management']);
@@ -236,6 +253,32 @@ describe('tool-catalog', () => {
'list_connector_tools', 'call_connector_tool',
]);
expect(isToolVisibleToAgent('add_custom_connector', 'custom-agent')).toBe(false);
+ expect(toolNamesForGroups(['management.skills'])).toEqual([
+ 'skill_search', 'import_skill_package',
+ ]);
+ expect(toolNamesForGroups(['management.marketplace'])).toEqual([
+ 'marketplace_search', 'marketplace_request_install',
+ ]);
+ expect(toolNamesForGroups(['management.automation'])).toEqual(['auto_tasks_list']);
+ expect(toolNamesForGroups(['management.app'])).toEqual(['open_app_view', 'app_health']);
+ // Keep the broad parent as an explicit compatibility alias while new
+ // runtime calls can load only the focused child they need.
+ expect(expandToolGroups(['management'])).toEqual([
+ 'management',
+ 'management.app',
+ 'management.skills',
+ 'management.marketplace',
+ 'management.automation',
+ ]);
+ expect(toolNamesForGroups(['management'])).toEqual([
+ 'skill_search',
+ 'import_skill_package',
+ 'marketplace_search',
+ 'marketplace_request_install',
+ 'auto_tasks_list',
+ 'open_app_view',
+ 'app_health',
+ ]);
});
it('scopes Office leaves while preserving the parent and pdf alias', () => {
diff --git a/test/main/model/core-agent/tool-surface.test.ts b/test/main/model/core-agent/tool-surface.test.ts
index 6feeaddd..ac6ed1c4 100644
--- a/test/main/model/core-agent/tool-surface.test.ts
+++ b/test/main/model/core-agent/tool-surface.test.ts
@@ -108,7 +108,8 @@ describe('tool-surface', () => {
process.env.ORKAS_TOOL_LOADING_MODE = 'legacy';
const surface = createToolSurfaceController({
availableToolNames: [
- 'read_files', 'write_file', 'web_search', 'marketplace_search', 'tool_load',
+ 'read_files', 'write_file', 'web_search', 'open_app_view', 'app_health',
+ 'skill_search', 'marketplace_search', 'auto_tasks_list', 'tool_load',
],
configuredGroups: ['workspace.read'],
scopedEligible: true,
@@ -124,12 +125,23 @@ describe('tool-surface', () => {
expect(surface.mode).toBe('scoped');
expect(surface.activeToolNames()).toEqual(expect.arrayContaining(['read_files', 'tool_load']));
expect(surface.isActive('write_file')).toBe(false);
- expect(surface.load(['management'])).toMatchObject({ isError: true });
+ for (const group of [
+ 'management',
+ 'management.app',
+ 'management.skills',
+ 'management.marketplace',
+ 'management.automation',
+ ]) {
+ expect(surface.load([group as any])).toMatchObject({ isError: true });
+ expect(groupEnum).not.toContain(group);
+ }
+ expect(surface.isActive('open_app_view')).toBe(false);
+ expect(surface.isActive('app_health')).toBe(false);
+ expect(surface.isActive('skill_search')).toBe(false);
expect(surface.isActive('marketplace_search')).toBe(false);
expect(groupEnum).toContain('workspace.write.output');
expect(groupEnum).not.toContain('workspace');
expect(groupEnum).not.toContain('workspace.write');
- expect(groupEnum).not.toContain('management');
expect(groupEnum).not.toContain('runtime');
expect(surface.load(['workspace.write'])).toMatchObject({ isError: true });
@@ -307,7 +319,7 @@ describe('tool-surface', () => {
version: 3,
mode: 'scoped',
loadedGroups: [],
- catalogRevision: '10',
+ catalogRevision: '12',
})]);
expect(surface.runtimeStats()).toEqual({
loadCalls: 2,
@@ -359,12 +371,13 @@ describe('tool-surface', () => {
expect(JSON.parse(rejected.content)).not.toHaveProperty('loaded_group_context');
});
- it('keeps Management out of Agent dependencies but activates it at runtime', () => {
+ it('keeps Management out of Agent dependencies and isolates focused runtime children', () => {
process.env.ORKAS_TOOL_LOADING_MODE = 'scoped';
const states: Array<{ loadedGroups: string[] }> = [];
const surface = createToolSurfaceController({
availableToolNames: [
- 'skill_search', 'marketplace_search', 'skill_manage', 'tool_load',
+ 'open_app_view', 'app_health', 'skill_search', 'marketplace_search',
+ 'auto_tasks_list', 'skill_manage', 'tool_load',
],
// A stale or bypassed Agent config must not preload a runtime-only group.
configuredGroups: ['management'],
@@ -374,22 +387,48 @@ describe('tool-surface', () => {
expect(surface.isActive('skill_manage')).toBe(true);
expect(surface.isActive('tool_load')).toBe(true);
+ expect(surface.isActive('open_app_view')).toBe(false);
+ expect(surface.isActive('app_health')).toBe(false);
expect(surface.isActive('skill_search')).toBe(false);
expect(surface.isActive('marketplace_search')).toBe(false);
+ expect(surface.isActive('auto_tasks_list')).toBe(false);
expect(states.at(-1)?.loadedGroups).toEqual([]);
- expect(JSON.parse(surface.load(['management']).content)).toMatchObject({
+ expect(JSON.parse(surface.load(['management.skills']).content)).toMatchObject({
ok: true,
- newly_loaded: ['management'],
+ newly_loaded: ['management.skills'],
unavailable: [],
});
expect(surface.isActive('skill_search')).toBe(true);
- expect(surface.isActive('marketplace_search')).toBe(true);
+ expect(surface.isActive('app_health')).toBe(false);
+ expect(surface.isActive('marketplace_search')).toBe(false);
+ expect(surface.isActive('auto_tasks_list')).toBe(false);
expect(states.at(-1)?.loadedGroups).toEqual([]);
+
+ expect(JSON.parse(surface.load(['management.app']).content)).toMatchObject({
+ ok: true,
+ newly_loaded: ['management.app'],
+ unavailable: [],
+ });
+ expect(surface.isActive('open_app_view')).toBe(true);
+ expect(surface.isActive('app_health')).toBe(true);
+ expect(surface.isActive('skill_search')).toBe(true);
+ expect(surface.isActive('marketplace_search')).toBe(false);
+ expect(surface.isActive('auto_tasks_list')).toBe(false);
+
+ expect(JSON.parse(surface.load(['management.automation']).content)).toMatchObject({
+ ok: true,
+ newly_loaded: ['management.automation'],
+ unavailable: [],
+ });
+ expect(surface.isActive('auto_tasks_list')).toBe(true);
+ expect(surface.isActive('marketplace_search')).toBe(false);
expect(surface.runtimeStats()).toEqual({
- loadCalls: 1,
- newlyLoadedGroups: ['management'],
- newlyActivatedToolNames: ['skill_search', 'marketplace_search'],
+ loadCalls: 3,
+ newlyLoadedGroups: ['management.app', 'management.skills', 'management.automation'],
+ newlyActivatedToolNames: [
+ 'skill_search', 'open_app_view', 'app_health', 'auto_tasks_list',
+ ],
});
});
@@ -476,7 +515,7 @@ describe('tool-surface', () => {
expect(states).toEqual([expect.objectContaining({
version: 3,
loadedGroups: [],
- catalogRevision: '10',
+ catalogRevision: '12',
})]);
const unchangedWrites: unknown[] = [];
@@ -486,7 +525,7 @@ describe('tool-surface', () => {
version: 3,
mode: 'scoped',
loadedGroups: [],
- catalogRevision: '10',
+ catalogRevision: '12',
},
scopedEligible: true,
persist: (state) => unchangedWrites.push(state),
diff --git a/test/main/model/core-agent/video-studio-state-tool.test.ts b/test/main/model/core-agent/video-studio-state-tool.test.ts
index 994d6b45..c99c0a26 100644
--- a/test/main/model/core-agent/video-studio-state-tool.test.ts
+++ b/test/main/model/core-agent/video-studio-state-tool.test.ts
@@ -8057,6 +8057,7 @@ describe('VideoStudio production-state tool protocol', () => {
op: 'composition.draft',
composition_dir: 'project/composition',
output_path: 'project/render/draft.mp4',
+ quality: 'draft',
};
const firstFailedDraft = await tool.execute(input, ctx);
@@ -8085,6 +8086,15 @@ describe('VideoStudio production-state tool protocol', () => {
expect(frozenDraftPath).not.toBe(failedDraftPath);
expect(fs.readFileSync(frozenDraftPath, 'utf8')).toBe('reviewable failed draft');
expect(published).toContainEqual([frozenDraftPath]);
+ // Same authored bytes at another quality are a distinct render request.
+ // The draft-quality QA verdict must not block a high-quality attempt.
+ const highQualityAttempt = await tool.execute({
+ ...input,
+ quality: 'high',
+ }, ctx);
+ expect(highQualityAttempt.isError).toBe(true);
+ expect(parseResult(highQualityAttempt.content).errorCode).toBe('E_VIDEO_QA_BLOCKED');
+ expect(draft).toHaveBeenCalledTimes(2);
// A deterministic QA verdict blocks the SECOND identical attempt: on
// 2026-08-22 the old two-attempt allowance let a model burn a 37.9-minute
// re-render of unchanged input into the exact same verdict.
@@ -8108,18 +8118,25 @@ describe('VideoStudio production-state tool protocol', () => {
requires_user_decision: false,
next_action: 'repair_inputs_then_retry_render',
operation_journal_evidence: {
+ render_quality: 'draft',
same_input_attempts: 1,
same_input_deterministic_qa_failures: 1,
durable: true,
},
});
- expect(draft).toHaveBeenCalledTimes(1);
+ expect(draft).toHaveBeenCalledTimes(2);
+
+ const stateAfterQualitySplit = await stateMod.readVideoProductionState(draftStatePath, compositionDir);
+ expect(stateAfterQualitySplit.operation_journal?.slice(-2)).toEqual([
+ expect.objectContaining({ status: 'failed', render_quality: 'draft' }),
+ expect.objectContaining({ status: 'failed', render_quality: 'high' }),
+ ]);
fs.appendFileSync(path.join(compositionDir, 'index.html'), '\n<!-- materially different repair -->\n');
const afterEdit = await tool.execute(input, ctx);
expect(afterEdit.isError).toBe(true);
expect(parseResult(afterEdit.content).errorCode).toBe('E_VIDEO_QA_BLOCKED');
- expect(draft).toHaveBeenCalledTimes(2);
+ expect(draft).toHaveBeenCalledTimes(3);
// An ambiguous render/infrastructure failure is NOT deterministic — it
// keeps the second identical attempt (a retry can genuinely pass) and
@@ -8139,7 +8156,7 @@ describe('VideoStudio production-state tool protocol', () => {
expect(transientBlocked.errorCode).toBe('E_FULL_RENDER_RETRY_NO_CHANGE');
expect(transientBlocked.operation_journal_evidence).toMatchObject({ same_input_attempts: 2 });
expect(transientBlocked.operation_journal_evidence.same_input_deterministic_qa_failures).toBeUndefined();
- expect(draft).toHaveBeenCalledTimes(4);
+ expect(draft).toHaveBeenCalledTimes(5);
});
it('finalizes an approved export before registering or publishing its path', async () => {
diff --git a/test/main/model/runner.test.ts b/test/main/model/runner.test.ts
index 6be64add..bf9302ca 100644
--- a/test/main/model/runner.test.ts
+++ b/test/main/model/runner.test.ts
@@ -1014,7 +1014,7 @@ describe('runner › scoped tool loading', () => {
expect(after.content).toContain('Use this exact Skill.');
});
- it('preloads Commander web and global-Skill discovery, not the whole management group', async () => {
+ it('preloads Commander web and app navigation while support diagnostics stay focused and dormant', async () => {
process.env.ORKAS_TOOL_LOADING_MODE = 'scoped';
const uid = 'runner-scoped-global-skill-discovery';
await configureUser(uid);
@@ -1035,11 +1035,25 @@ describe('runner › scoped tool loading', () => {
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
async execute() { return { content: JSON.stringify({ ok: true, rows: [] }) }; },
},
+ {
+ name: 'open_app_view',
+ description: 'Stage app navigation.',
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
+ async execute() { return { content: JSON.stringify({ ok: true }) }; },
+ },
+ {
+ name: 'app_health',
+ description: 'Inspect sanitized app health.',
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
+ async execute() { return { content: JSON.stringify({ ok: true }) }; },
+ },
],
});
const toolNames = commander.toolDefs.map((tool) => tool.name);
- expect(toolNames).toContain('skill_search');
+ expect(toolNames).not.toContain('skill_search');
+ expect(toolNames).toContain('open_app_view');
+ expect(toolNames).not.toContain('app_health');
expect(toolNames).toEqual(expect.arrayContaining(['web_search', 'web_fetch']));
expect(toolNames).toContain('tool_load');
expect(toolNames).toContain('manage_execution_plan');
@@ -1050,6 +1064,8 @@ describe('runner › scoped tool loading', () => {
expect(commander.resolvedSystemPrompt).toContain('## Loadable tool groups');
expect(commander.resolvedSystemPrompt).not.toContain('Tools:');
expect(commander.resolvedSystemPrompt).not.toContain('`marketplace_search`');
+ expect(commander.resolvedSystemPrompt).toContain('`management.app`');
+ expect(commander.resolvedSystemPrompt).toContain('`management.skills`');
expect(commander.resolvedSystemPrompt).toContain('runtime only; not an Agent dependency');
expect(commander.toolSurfaceTelemetry(['web_search'])).toMatchObject({
loadCallCount: 0,
@@ -1057,6 +1073,48 @@ describe('runner › scoped tool loading', () => {
loadedSchemaChars: 0,
webToolUsed: true,
});
+ const runner = commander.runner as unknown as {
+ tools: Map<string, {
+ execute: (input: unknown, ctx: unknown) => Promise<{ content: string }>;
+ }>;
+ getActiveToolDefinitions(): Array<{ name: string }>;
+ };
+ const loadResult = await runner.tools.get('tool_load')?.execute(
+ { groups: ['management.skills'] },
+ { workingDir: tmpDir, state: {}, signal: undefined },
+ );
+ expect(JSON.parse(loadResult?.content || '{}')).toMatchObject({
+ ok: true,
+ newly_loaded: ['management.skills'],
+ });
+ const loadedNames = runner.getActiveToolDefinitions().map((tool) => tool.name);
+ expect(loadedNames).toContain('skill_search');
+ expect(loadedNames).not.toContain('marketplace_search');
+ expect(loadedNames).not.toContain('app_health');
+ expect(commander.toolSurfaceTelemetry(['tool_load', 'skill_search'])).toMatchObject({
+ loadCallCount: 1,
+ loadedGroupCount: 1,
+ loadedUnusedGroupCount: 0,
+ });
+
+ const appLoadResult = await runner.tools.get('tool_load')?.execute(
+ { groups: ['management.app'] },
+ { workingDir: tmpDir, state: {}, signal: undefined },
+ );
+ expect(JSON.parse(appLoadResult?.content || '{}')).toMatchObject({
+ ok: true,
+ newly_loaded: ['management.app'],
+ });
+ const appLoadedNames = runner.getActiveToolDefinitions().map((tool) => tool.name);
+ expect(appLoadedNames).toContain('open_app_view');
+ expect(appLoadedNames).toContain('app_health');
+ expect(appLoadedNames).toContain('skill_search');
+ expect(appLoadedNames).not.toContain('marketplace_search');
+ expect(commander.toolSurfaceTelemetry(['tool_load', 'skill_search', 'app_health'])).toMatchObject({
+ loadCallCount: 2,
+ loadedGroupCount: 2,
+ loadedUnusedGroupCount: 0,
+ });
});
it('does not serialize a deferred tool schema until its group is loaded', async () => {
@@ -1342,21 +1400,21 @@ describe('runner › scoped tool loading', () => {
expect(runner.activeTools().map((tool) => tool.name)).not.toContain('marketplace_search');
expect(built.resolvedSystemPrompt)
- .toContain('`management` (runtime only; not an Agent dependency)');
+ .toContain('`management.marketplace` (runtime only; not an Agent dependency)');
+ expect(built.resolvedSystemPrompt)
+ .toContain('`management.automation` (runtime only; not an Agent dependency)');
expect(managementCalls).toEqual([]);
const loadResult = await runner.tools.get('tool_load')?.execute(
- { groups: ['management'] },
+ { groups: ['management.marketplace'] },
{ workingDir: tmpDir, state: {}, signal: undefined },
);
expect(JSON.parse(loadResult?.content || '{}')).toMatchObject({
ok: true,
- newly_loaded: ['management'],
+ newly_loaded: ['management.marketplace'],
});
- expect(runner.activeTools().map((tool) => tool.name)).toEqual(expect.arrayContaining([
- 'marketplace_search',
- 'auto_tasks_list',
- ]));
+ expect(runner.activeTools().map((tool) => tool.name)).toContain('marketplace_search');
+ expect(runner.activeTools().map((tool) => tool.name)).not.toContain('auto_tasks_list');
expect(managementCalls).toEqual([]);
const searchResult = await runner.tools.get('marketplace_search')?.execute(
@@ -1386,7 +1444,7 @@ describe('runner › scoped tool loading', () => {
.getToolSurfaceState()).toMatchObject({
version: 3,
loadedGroups: [],
- catalogRevision: '10',
+ catalogRevision: '12',
});
const nextTurn = await buildRunner({
@@ -1473,7 +1531,7 @@ describe('runner › scoped tool loading', () => {
expect(migrated.resolvedSystemPrompt).not.toContain('(loaded)');
expect(migrated.turnEphemeral).not.toContain('`web`');
expect((await sessions.getSessionForUser(uid, sessionId)).getToolSurfaceState())
- .toMatchObject({ version: 3, loadedGroups: [], catalogRevision: '10' });
+ .toMatchObject({ version: 3, loadedGroups: [], catalogRevision: '12' });
});
it('drops restored dynamic groups when an Agent uses a fixed dependency list', async () => {
diff --git a/test/main/model/skill-registry.test.ts b/test/main/model/skill-registry.test.ts
index 28b114b9..f876d408 100644
--- a/test/main/model/skill-registry.test.ts
+++ b/test/main/model/skill-registry.test.ts
@@ -474,8 +474,10 @@ describe('skill-registry › getSystemSkillsPromptBlock', () => {
expect(systemText).toContain('## System skills');
expect(systemText).toContain('SYSTEM_SKILLS_ROOT');
expect(systemText).toContain(path.resolve(systemDir()));
- expect(systemText).toContain('Match the whole request against every description.');
- expect(systemText).toContain('Before other work, read the smallest complete set of matching SKILL.md files');
+ expect(systemText).toContain('Treat each description as an activation contract.');
+ expect(systemText).toContain('intended outcome and context, not keyword overlap.');
+ expect(systemText).toContain('Before answering or calling another tool');
+ expect(systemText).toContain('read the smallest complete set whose use conditions apply');
expect(systemText).toContain('never load nonmatches.');
expect(systemText).toContain('Read 2+ matches together first:');
expect(systemText).toContain('read_files({"paths"');
diff --git a/test/main/prompts/contract.test.ts b/test/main/prompts/contract.test.ts
index 0e3ad0ed..09430294 100644
--- a/test/main/prompts/contract.test.ts
+++ b/test/main/prompts/contract.test.ts
@@ -332,6 +332,10 @@ describe('prompts ↔ code contract', () => {
// Language rule: write in the user's current language, preserving literals.
expect(memoryTool).toContain('use project_tasks for task progress');
+ expect(memoryManager).toMatch(/description_zh:.*未来对话持续生效/);
+ expect(memoryManager).toMatch(/description_en:.*across future conversations/i);
+ expect(memoryManager).toMatch(/description_en:.*ordinary file saving/i);
+
expect(agentPrompt).toMatch(/only for durable information useful in future conversations/i);
expect(agentPrompt).toMatch(/Never store current task progress, temporary plans, one-off status, or TODO\/dependency state/i);
expect(agentPrompt).toMatch(/Use `agent` for a convention limited to this Agent/i);
@@ -358,20 +362,26 @@ describe('prompts ↔ code contract', () => {
expect(readFile('src/main/features/group_chat/bus.ts')).toContain("prompts.load('chat_shared_rules'");
});
- it('group-chat system prompts inject the current User UI language directive', () => {
+ it('group-chat system prompts prefer the user language and keep the UI language as fallback', () => {
const i18n = readFile('src/main/i18n.ts');
const composer = readFile('src/main/prompts/chat_prompt_composer.ts');
expect(i18n).toContain('buildLanguageDirectiveText(name)');
- expect(composer).toContain('User UI language: **${languageName}**');
- expect(composer).toContain('Write all human-readable prose in ${languageName}');
- expect(buildLanguageDirectiveText('Chinese (简体中文)')).toContain(
- 'User UI language: **Chinese (简体中文)**',
- );
+ expect(composer).toContain('Fallback UI language: **${languageName}**');
+ const directive = buildLanguageDirectiveText('Chinese (简体中文)');
+ expect(directive).toContain('a current explicit user language request');
+ expect(directive).toContain("the clear language of the user's latest substantive prose");
+ expect(directive).toContain('Fallback UI language: **Chinese (简体中文)**');
+ expect(directive.indexOf('a current explicit user language request'))
+ .toBeLessThan(directive.indexOf("the clear language of the user's latest substantive prose"));
+ expect(directive.indexOf("the clear language of the user's latest substantive prose"))
+ .toBeLessThan(directive.indexOf('fallback UI language'));
+ expect(directive).toMatch(/Quoted text, code, file contents, proper nouns,[\s\S]*do not switch/i);
+ expect(directive).toContain('Write all human-readable prose in the chosen language');
const composed = composeChatPrompt({
main: 'ROLE\n\n## Runtime injection\nRUNTIME',
stableFragments: ['SHARED'],
- languageDirective: '## User language\nUser UI language: **Chinese**.',
+ languageDirective: '## User language\nFallback UI language: **Chinese**.',
runtimeDatetimeBlock: '## Current date\nCurrent date: 2026-07-23',
});
expect(composed).toMatch(
@@ -477,6 +487,21 @@ describe('prompts ↔ code contract', () => {
expect(skillPrompt).toContain('If imported docs, references, scripts, or examples are present, inspect them and write the best skill you can without asking for confirmation');
});
+ it('skill edit URL routing uses the injected owner skills without a Commander mirror', () => {
+ const skillPrompt = fs.readFileSync(path.join(PROMPTS_DIR, 'chat_skill_setup.md'), 'utf-8');
+ const start = skillPrompt.indexOf('## Installing a skill from a URL');
+ const end = skillPrompt.indexOf('\n\n---\n\n## Runtime injection', start);
+ const section = skillPrompt.slice(start, end);
+
+ expect(start).toBeGreaterThanOrEqual(0);
+ expect(end).toBeGreaterThan(start);
+ expect(section).toContain('skill-creator');
+ expect(section).toContain('package-installer');
+ expect(section).toContain('<skill-as-package name="<installed-name>"/>');
+ expect(section).not.toMatch(/mirror of the commander|keep in sync with `chat_commander\.md`/i);
+ expect(section).not.toContain('consent-deps');
+ });
+
it('commander prompt routes automation CRUD through autotask-creator', () => {
const commanderPrompt = fs.readFileSync(path.join(PROMPTS_DIR, 'chat_commander.md'), 'utf-8');
const automationCreator = readFile('resources/builtin/system/skills/autotask-creator/SKILL.md');
@@ -496,6 +521,8 @@ describe('prompts ↔ code contract', () => {
expect(memorySection.length).toBeLessThan(1_800);
expect(memorySection).toMatch(/Use injected memory and project instructions directly as read-only context/i);
expect(memorySection).toMatch(/mutations are owned by the matching System Skill/i);
+ expect(memorySection).toMatch(/select and read that System Skill before answering or calling its mutation tool/i);
+ expect(memorySection).toMatch(/intended future effect, not exact phrasing/i);
expect(memorySection).toMatch(/Never persist current task progress/i);
expect(memorySection).not.toContain('target: "agent"');
expect(memorySection).not.toContain('Project instructions vs project memory');
diff --git a/test/main/util/fetch-whisper.test.ts b/test/main/util/fetch-whisper.test.ts
index 96f2fb05..f7b8d90e 100644
--- a/test/main/util/fetch-whisper.test.ts
+++ b/test/main/util/fetch-whisper.test.ts
@@ -1,7 +1,6 @@
import { afterEach, describe, expect, it } from 'vitest';
import { createRequire } from 'node:module';
import * as fs from 'node:fs';
-import * as crypto from 'node:crypto';
import * as os from 'node:os';
import * as path from 'node:path';
@@ -19,7 +18,6 @@ const fetchWhisper = require('../../../scripts/fetch-whisper.cjs') as {
runtimeVersion: (target: any) => string;
targetOptions: (argv: string[]) => { platform: string; arch: string; force: boolean };
writeCapabilityState: (dir: string, capability: { status: string; reason?: string }) => void;
- writeLinuxFiles: (archive: string, dir: string, target: any) => void;
};
const { WHISPER_RUNTIME_CONTRACT } = require('../../../bin/runtime-gate.cjs') as {
WHISPER_RUNTIME_CONTRACT: any;
@@ -67,65 +65,6 @@ describe('fetch-whisper', () => {
expect(fetchWhisper.noticeForTarget(darwin)).not.toContain('LICENSE.openblas');
});
- it.each(['x64', 'arm64'])('pins the official Linux %s archive and application-local runtime libraries', (arch) => {
- const target = WHISPER_RUNTIME_CONTRACT.targets[`linux-${arch}`];
- expect(fetchWhisper.runtimeVersion(target)).toBe('1.9.1');
- expect(target.minimumGlibc).toBe('2.34');
- expect(target.archive.url).toContain(`whisper-bin-ubuntu-${arch}.tar.gz`);
- expect(target.archive.bytes).toBeGreaterThan(1_000_000);
- expect(target.archive.sha256).toMatch(/^[a-f0-9]{64}$/);
- expect(Object.keys(fetchWhisper.expectedFiles(target))).toEqual(expect.arrayContaining([
- 'bin/whisper-cli',
- 'bin/libwhisper.so.1',
- 'bin/libggml.so.0',
- 'bin/libggml-base.so.0',
- 'models/ggml-base-q5_1.bin',
- 'LICENSE.whisper.cpp',
- 'LICENSE.model',
- ]));
- expect(fetchWhisper.noticeForTarget(target)).toContain('official whisper.cpp Ubuntu');
- });
-
- it('extracts only contracted Linux archive files and verifies them before installation', async () => {
- const tar = await import('tar');
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-whisper-linux-archive-'));
- tempDirs.push(root);
- const sourceRoot = path.join(root, 'source');
- const archiveRoot = path.join(sourceRoot, 'whisper-bin-ubuntu-x64');
- fs.mkdirSync(archiveRoot, { recursive: true });
- const cli = Buffer.from('fake linux whisper cli');
- const library = Buffer.from('fake linux whisper library');
- fs.writeFileSync(path.join(archiveRoot, 'whisper-cli'), cli);
- fs.writeFileSync(path.join(archiveRoot, 'libwhisper.so.1.9.1'), library);
- fs.writeFileSync(path.join(archiveRoot, 'unregistered'), 'must not be extracted');
- const archive = path.join(root, 'runtime.tar.gz');
- tar.c({ cwd: sourceRoot, file: archive, gzip: true, sync: true }, ['whisper-bin-ubuntu-x64']);
- const record = (value: Buffer) => ({
- bytes: value.length,
- sha256: crypto.createHash('sha256').update(value).digest('hex'),
- executable: true,
- });
- const target = {
- files: {
- 'bin/whisper-cli': {
- archivePath: 'whisper-bin-ubuntu-x64/whisper-cli',
- ...record(cli),
- },
- 'bin/libwhisper.so.1': {
- archivePath: 'whisper-bin-ubuntu-x64/libwhisper.so.1.9.1',
- ...record(library),
- },
- },
- };
- const destination = path.join(root, 'destination');
-
- fetchWhisper.writeLinuxFiles(archive, destination, target);
-
- expect(fs.readFileSync(path.join(destination, 'bin', 'whisper-cli'))).toEqual(cli);
- expect(fs.readFileSync(path.join(destination, 'bin', 'libwhisper.so.1'))).toEqual(library);
- expect(fs.existsSync(path.join(destination, 'unregistered'))).toBe(false);
- });
-
it('persists an unsupported-CPU capability state without changing verified file records', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-whisper-marker-'));
tempDirs.push(dir);
diff --git a/test/main/util/officecli-fetch.test.ts b/test/main/util/officecli-fetch.test.ts
index 02b21351..01b41073 100644
--- a/test/main/util/officecli-fetch.test.ts
+++ b/test/main/util/officecli-fetch.test.ts
@@ -6,10 +6,6 @@ import * as os from 'node:os';
import * as path from 'node:path';
const TEST_NODE = process.env.ORKAS_TEST_NODE || process.execPath;
-const OFFICECLI_SPEC = require(path.join(process.cwd(), 'scripts', 'fetch-officecli.cjs')) as {
- ASSETS: Readonly<Record<string, string>>;
- SHA256: Readonly<Record<string, string>>;
-};
let tmpDir: string;
@@ -54,27 +50,6 @@ describe('fetch-officecli.cjs', () => {
expect(`${r.stdout}\n${r.stderr}`).toContain('officecli-mac-arm64 missing');
});
- it.each([
- ['linux-x64', 'officecli-linux-x64', 'da07d4f787d7c85724104294ac023c89971ddfaee93ebb183b289282b8f869cc'],
- ['linux-arm64', 'officecli-linux-arm64', '39008c7f76d202858637810553ef14e2cd3e7f61485fdcf2011f26967a7babd1'],
- ])('resolves %s to its pinned upstream asset', (platform, asset, sha256) => {
- expect(OFFICECLI_SPEC.ASSETS[platform]).toBe(asset);
- expect(OFFICECLI_SPEC.SHA256[asset]).toBe(sha256);
-
- const r = spawnSync(TEST_NODE, [
- path.join(process.cwd(), 'scripts', 'fetch-officecli.cjs'),
- `--root=${tmpDir}`,
- `--platform=${platform}`,
- '--check',
- ], {
- cwd: process.cwd(),
- encoding: 'utf8',
- });
-
- expect(r.status).toBe(1);
- expect(`${r.stdout}\n${r.stderr}`).toContain(`${asset} missing`);
- });
-
it('resumes an existing partial download with a Range request', async () => {
const ranges: Array<string | undefined> = [];
fs.writeFileSync(path.join(tmpDir, 'LICENSE'), 'Apache-2.0');
diff --git a/test/main/util/uniquify-path.test.ts b/test/main/util/uniquify-path.test.ts
index f010936f..3559c540 100644
--- a/test/main/util/uniquify-path.test.ts
+++ b/test/main/util/uniquify-path.test.ts
@@ -3,7 +3,7 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
-import { uniquifyPath, renderRenameSignal } from '../../../src/main/util/uniquify-path';
+import { uniquifyPath, uniquifyPathForWrite, renderRenameSignal } from '../../../src/main/util/uniquify-path';
let tmpDir: string;
@@ -94,3 +94,43 @@ describe('renderRenameSignal', () => {
expect(out).not.toContain('/abs/dir/');
});
});
+
+// Two parallel agent turns sharing one conversation workspace both deliver a
+// file under the same requested name. The contract is that neither delivery is
+// silently lost: probe+write are serialized per requested path, so the loser's
+// probe sees the winner's file and suffixes. Plain uniquifyPath is
+// check-then-act and deterministically fails this scenario (both probes run
+// before either write) — verified as the mutation control for this case.
+describe('uniquifyPathForWrite › concurrent same-target writers', () => {
+ it('keeps both concurrent deliveries: one original, one suffixed, no clobber', async () => {
+ const target = path.join(tmpDir, 'plan.md');
+ const writeVia = (content: string) => uniquifyPathForWrite(
+ target, NEVER_MINE,
+ async (decision) => {
+ fs.writeFileSync(decision.finalPath, content);
+ return decision;
+ },
+ );
+ const [a, b] = await Promise.all([writeVia('from-agent-A'), writeVia('from-agent-B')]);
+ const finals = [a.finalPath, b.finalPath].sort();
+ expect(finals).toEqual([path.join(tmpDir, 'plan-2.md'), target].sort());
+ expect([a.renamed, b.renamed].filter(Boolean)).toHaveLength(1);
+ const contents = finals.map((f) => fs.readFileSync(f, 'utf8')).sort();
+ expect(contents).toEqual(['from-agent-A', 'from-agent-B']);
+ });
+
+ it('releases the lock when the write throws, so the path recovers for the next writer', async () => {
+ const target = path.join(tmpDir, 'report.md');
+ await expect(uniquifyPathForWrite(target, NEVER_MINE, async () => {
+ throw new Error('render blew up');
+ })).rejects.toThrow('render blew up');
+ // The failed attempt left nothing on disk and holds nothing: the retry
+ // gets the ORIGINAL path back, not a stale suffix or a hang.
+ const retry = await uniquifyPathForWrite(target, NEVER_MINE, async (decision) => {
+ fs.writeFileSync(decision.finalPath, 'second try');
+ return decision;
+ });
+ expect(retry).toEqual({ finalPath: target, renamed: false });
+ expect(fs.readFileSync(target, 'utf8')).toBe('second try');
+ });
+});
diff --git a/test/renderer/bash-permission.test.ts b/test/renderer/bash-permission.test.ts
index 72989ad1..23fb49a8 100644
--- a/test/renderer/bash-permission.test.ts
+++ b/test/renderer/bash-permission.test.ts
@@ -117,7 +117,7 @@ describe('renderer bash permission prompt', () => {
expect(code).toContain('${caretHtml}');
});
- it('offers task-level approval when main marks the risk category eligible', async () => {
+ it('shows the permission-level switch and persists the selected mode before allowing', async () => {
const h = loadHarness({ choice: 'allow_once', mode: 'all_files_auto' });
h.pushHandler({
@@ -133,19 +133,37 @@ describe('renderer bash permission prompt', () => {
expect(h.dialogArgs[0]).toMatchObject({
currentMode: 'all_files_approval',
allowRun: true,
- showModeControl: false,
+ showModeControl: true,
+ modes: [
+ {
+ mode: 'workspace_approval',
+ label: 'Cautious',
+ desc: 'Workspace files only, confirm sensitive actions',
+ },
+ {
+ mode: 'all_files_approval',
+ label: 'Standard',
+ desc: 'All files, confirm sensitive actions',
+ },
+ {
+ mode: 'all_files_auto',
+ label: 'Trusted',
+ desc: 'All files, no sensitive confirmations',
+ },
+ ],
});
expect(h.dialogArgs[0].message).toContain('Commander wants network:');
expect(h.invokeCalls).toEqual([
{ channel: 'permissions.getLocalExec', payload: undefined },
+ { channel: 'permissions.setLocalExecMode', payload: { mode: 'all_files_auto' } },
{ channel: 'bash.permission_response', payload: { request_id: 'req-1', decision: 'allow_once' } },
]);
expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_result', expect.objectContaining({
result: 'success',
decision: 'allow_once',
effective_decision: 'allow_once',
- mode: 'all_files_approval',
- mode_changed: false,
+ mode: 'all_files_auto',
+ mode_changed: true,
categories: 'network_egress',
duration_ms: expect.any(Number),
}));
@@ -222,7 +240,7 @@ describe('renderer bash permission prompt', () => {
'sensitive_path',
'system_package_change',
] as const)('returns task-level approval for eligible %s prompts', async (reason) => {
- const h = loadHarness({ choice: 'allow_run', mode: 'workspace_approval' });
+ const h = loadHarness({ choice: 'allow_run', mode: 'all_files_approval' });
h.pushHandler({
request_id: `req-${reason}`,
@@ -233,7 +251,7 @@ describe('renderer bash permission prompt', () => {
});
await flush();
- expect(h.dialogArgs[0]).toMatchObject({ allowRun: true, showModeControl: false });
+ expect(h.dialogArgs[0]).toMatchObject({ allowRun: true, showModeControl: true });
expect(h.invokeCalls).toEqual([
{ channel: 'permissions.getLocalExec', payload: undefined },
{ channel: 'bash.permission_response', payload: { request_id: `req-${reason}`, decision: 'allow_run' } },
@@ -250,7 +268,7 @@ describe('renderer bash permission prompt', () => {
it.each(['priv_esc', 'external_mutation'] as const)(
'narrows a stale task-level approval to one command for strict %s prompts',
async (reason) => {
- const h = loadHarness({ choice: 'allow_run', mode: 'workspace_approval' });
+ const h = loadHarness({ choice: 'allow_run', mode: 'all_files_approval' });
h.pushHandler({
request_id: `req-${reason}`,
@@ -261,7 +279,7 @@ describe('renderer bash permission prompt', () => {
});
await flush();
- expect(h.dialogArgs[0]).toMatchObject({ allowRun: false, showModeControl: false });
+ expect(h.dialogArgs[0]).toMatchObject({ allowRun: false, showModeControl: true });
expect(h.invokeCalls).toContainEqual({
channel: 'bash.permission_response',
payload: { request_id: `req-${reason}`, decision: 'allow_once' },
@@ -270,9 +288,9 @@ describe('renderer bash permission prompt', () => {
);
it.each(['allow_run', 'allow_always'])(
- 'supports task approval but not persistent mode changes for system package changes when UI returns %s',
+ 'keeps system package approval bounded when a legacy UI returns %s',
async (legacyChoice) => {
- const h = loadHarness({ choice: legacyChoice, mode: 'all_files_auto' });
+ const h = loadHarness({ choice: legacyChoice, mode: 'all_files_approval' });
h.pushHandler({
request_id: 'req-system-package',
@@ -285,7 +303,7 @@ describe('renderer bash permission prompt', () => {
expect(h.dialogArgs[0]).toMatchObject({
allowRun: true,
- showModeControl: false,
+ showModeControl: true,
});
expect(h.dialogArgs[0].message).toContain('changes system packages');
expect(h.invokeCalls).toEqual([
@@ -304,7 +322,7 @@ describe('renderer bash permission prompt', () => {
it.each(['allow_run', 'allow_always'])(
'offers only one-time approval for external mutations even when a stale UI returns %s',
async (legacyChoice) => {
- const h = loadHarness({ choice: legacyChoice, mode: 'all_files_auto' });
+ const h = loadHarness({ choice: legacyChoice, mode: 'all_files_approval' });
h.pushHandler({
request_id: 'req-external-mutation',
@@ -317,7 +335,7 @@ describe('renderer bash permission prompt', () => {
expect(h.dialogArgs[0]).toMatchObject({
allowRun: false,
- showModeControl: false,
+ showModeControl: true,
});
expect(h.dialogArgs[0].message).toContain('changes an external system');
expect(h.dialogArgs[0].message).toContain('Detected:\nService change · restart · api');
@@ -345,6 +363,35 @@ describe('renderer bash permission prompt', () => {
]);
});
+ it('denies the sensitive operation when its selected mode cannot be persisted', async () => {
+ const h = loadHarness({ choice: 'allow_once', mode: 'all_files_auto' }, async (channel) => {
+ if (channel === 'permissions.getLocalExec') return { ok: true, mode: 'all_files_approval' };
+ if (channel === 'permissions.setLocalExecMode') return { ok: false };
+ return { handled: true };
+ });
+
+ h.pushHandler({
+ request_id: 'req-mode-failed',
+ agent_name: 'Agent',
+ command: 'curl https://example.com',
+ reasons: ['network_egress'],
+ });
+ await flush();
+
+ expect(h.invokeCalls).toEqual([
+ { channel: 'permissions.getLocalExec', payload: undefined },
+ { channel: 'permissions.setLocalExecMode', payload: { mode: 'all_files_auto' } },
+ { channel: 'bash.permission_response', payload: { request_id: 'req-mode-failed', decision: 'deny' } },
+ ]);
+ expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_result', expect.objectContaining({
+ result: 'success',
+ decision: 'allow_once',
+ effective_decision: 'deny',
+ mode: 'all_files_approval',
+ mode_changed: false,
+ }));
+ });
+
it('marks a verdict cancelled when main reports that the request is stale', async () => {
const h = loadHarness('allow_once', async (channel) => {
if (channel === 'permissions.getLocalExec') return { ok: true, mode: 'all_files_approval' };
diff --git a/test/renderer/composer-popover-coordination.test.ts b/test/renderer/composer-popover-coordination.test.ts
new file mode 100644
index 00000000..97389c1e
--- /dev/null
+++ b/test/renderer/composer-popover-coordination.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, it } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as vm from 'node:vm';
+
+const modulesRoot = path.join(__dirname, '../../src/renderer/modules');
+const modelSource = fs.readFileSync(path.join(modulesRoot, 'composer-model-picker.js'), 'utf8');
+const agentsSource = fs.readFileSync(path.join(modulesRoot, 'agents.js'), 'utf8');
+const workspaceSource = fs.readFileSync(path.join(modulesRoot, 'user-workspace.js'), 'utf8');
+const styleSource = fs.readFileSync(path.join(__dirname, '../../src/renderer/style.css'), 'utf8');
+
+function extractFunction(source: string, name: string): string {
+ const markers = [`function ${name}`, `async function ${name}`];
+ const start = markers
+ .map((marker) => source.indexOf(marker))
+ .filter((index) => index >= 0)
+ .sort((a, b) => a - b)[0];
+ if (start === undefined) throw new Error(`missing ${name}`);
+ const braceStart = source.indexOf('{', start);
+ let depth = 0;
+ for (let i = braceStart; i < source.length; i += 1) {
+ if (source[i] === '{') depth += 1;
+ else if (source[i] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(start, i + 1);
+ }
+ }
+ throw new Error(`unterminated ${name}`);
+}
+
+function peerCloseResult(activeKind: 'model' | 'recipient' | 'workspace') {
+ const helper = extractFunction(modelSource, '_closeOtherComposerPopovers');
+ return vm.runInNewContext(`
+ const closed = { model: 0, recipient: 0, workspace: 0 };
+ function _closeComposerModelMenu() { closed.model += 1; }
+ function _closeAgentPicker() { closed.recipient += 1; }
+ const workspaceMenu = {
+ _closeWorkspaceMenu() { closed.workspace += 1; },
+ remove() { throw new Error('owned closer must be preferred'); },
+ };
+ const document = {
+ getElementById(id) { return id === 'workspace-menu' ? workspaceMenu : null; },
+ };
+ ${helper}
+ _closeOtherComposerPopovers(${JSON.stringify(activeKind)});
+ closed;
+ `);
+}
+
+function closeRecipientPicker(preserveAtKey: boolean) {
+ const setOpen = extractFunction(agentsSource, '_setAgentPickerAnchorOpen');
+ const closeStart = agentsSource.indexOf('function _closeAgentPicker');
+ const closeEnd = agentsSource.indexOf('\nfunction _renderAgentPickerList', closeStart);
+ const close = agentsSource.slice(closeStart, closeEnd);
+ return vm.runInNewContext(`
+ const classes = new Set();
+ const attributes = {};
+ const anchor = {
+ classList: {
+ toggle(name, enabled) { if (enabled) classes.add(name); else classes.delete(name); },
+ },
+ setAttribute(name, value) { attributes[name] = value; },
+ };
+ const picker = { dataset: { anchorId: 'chat-recipient-chip' }, style: { display: 'flex' } };
+ const document = {
+ getElementById(id) {
+ if (id === 'agent-picker') return picker;
+ if (id === 'chat-recipient-chip') return anchor;
+ return null;
+ },
+ };
+ let _atKeyMark = { inputId: 'chat-input', posAfter: 1 };
+ ${setOpen}
+ ${close}
+ _setAgentPickerAnchorOpen(anchor, true);
+ const opened = { selected: classes.has('is-open'), expanded: attributes['aria-expanded'] };
+ _closeAgentPicker({ preserveAtKey: ${JSON.stringify(preserveAtKey)} });
+ ({
+ opened,
+ selected: classes.has('is-open'),
+ expanded: attributes['aria-expanded'],
+ display: picker.style.display,
+ mark: _atKeyMark,
+ });
+ `);
+}
+
+describe('composer popover coordination', () => {
+ it('closes recipient and workspace panels before opening the model panel', () => {
+ expect(peerCloseResult('model')).toEqual({ model: 0, recipient: 1, workspace: 1 });
+ });
+
+ it('closes model and workspace panels before opening the recipient panel', () => {
+ expect(peerCloseResult('recipient')).toEqual({ model: 1, recipient: 0, workspace: 1 });
+ });
+
+ it('closes model and recipient panels before opening the workspace panel', () => {
+ expect(peerCloseResult('workspace')).toEqual({ model: 1, recipient: 1, workspace: 0 });
+ });
+
+ it('keeps the recipient anchor selected exactly while its picker is open', () => {
+ expect(closeRecipientPicker(false)).toEqual({
+ opened: { selected: true, expanded: 'true' },
+ selected: false,
+ expanded: 'false',
+ display: 'none',
+ mark: null,
+ });
+ expect(agentsSource).toContain('_setAgentPickerAnchorOpen(anchorBtn, true)');
+ expect(styleSource).toMatch(/\.chat-recipient-chip\.is-open\s*\{/);
+ });
+
+ it('preserves a typed @ only for the selection path that consumes it next', () => {
+ expect(closeRecipientPicker(true).mark).toEqual({ inputId: 'chat-input', posAfter: 1 });
+ expect(agentsSource).toContain('_closeAgentPicker({ preserveAtKey: true })');
+ });
+
+ it('wires every picker opener into the same exclusivity boundary', () => {
+ const modelOpen = modelSource.slice(
+ modelSource.indexOf('async function _toggleComposerModelMenu'),
+ modelSource.indexOf("document.addEventListener('DOMContentLoaded'"),
+ );
+ const agentOpen = agentsSource.slice(
+ agentsSource.indexOf('async function _openAgentPicker'),
+ agentsSource.indexOf('\nfunction _setAgentPickerAnchorOpen'),
+ );
+ const workspaceOpen = workspaceSource.slice(
+ workspaceSource.indexOf('function _showWorkspaceDropdown'),
+ workspaceSource.indexOf('\nfunction _createMenuItem'),
+ );
+ expect(modelOpen).toContain("_closeOtherComposerPopovers('model')");
+ expect(agentOpen).toContain("_closeOtherComposerPopovers('recipient')");
+ expect(workspaceOpen).toContain("_closeOtherComposerPopovers('workspace')");
+ });
+});
diff --git a/test/renderer/lazy-features.test.ts b/test/renderer/lazy-features.test.ts
index 424f710a..f1bb5c13 100644
--- a/test/renderer/lazy-features.test.ts
+++ b/test/renderer/lazy-features.test.ts
@@ -252,7 +252,9 @@ describe('renderer lazy feature loader', () => {
const end = source.indexOf('async function refreshSelectedAgentDetail', start);
const detailOpen = source.slice(start, end);
- expect(detailOpen).toContain('await selectAgent(agentId, { refreshCliOptions: true })');
+ expect(detailOpen).toMatch(
+ /return\s+(?:await\s+)?selectAgent\(agentId, \{ refreshCliOptions: true \}\)/,
+ );
expect(detailOpen).not.toContain('loadAgents(true)');
});
diff --git a/test/renderer/project-chat-recipient-scope.test.ts b/test/renderer/project-chat-recipient-scope.test.ts
new file mode 100644
index 00000000..302d11dd
--- /dev/null
+++ b/test/renderer/project-chat-recipient-scope.test.ts
@@ -0,0 +1,222 @@
+import { describe, expect, it } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as vm from 'node:vm';
+
+// The project detail composer keeps ONE ephemeral recipient for every project
+// (`conversation.js::_projectChatRecipient`). Opening a project must therefore
+// re-check that pick against the project the user is now looking at: the send
+// path turns the chip into an `@name` prefix and the group bus resolves
+// mentions against the GLOBAL agent registry, so a pick carried over from
+// another project would really dispatch an out-of-project Agent into the new
+// conversation.
+//
+// Both real decision sites run here: the wiring inside `loadProjectDetail`
+// (project-detail.js) and the shared rule in `validateRecipientAgainstProject`
+// (conversation.js). Only the recipient store and the heavy DOM renderers are
+// fixtures, and the oracle is the recipient the send path would read back.
+
+const projectDetailSource = fs.readFileSync(
+ path.join(__dirname, '../../src/renderer/modules/project-detail.js'),
+ 'utf8',
+);
+const conversationSource = fs.readFileSync(
+ path.join(__dirname, '../../src/renderer/modules/conversation.js'),
+ 'utf8',
+);
+
+function extractFunction(source: string, name: string): string {
+ const marker = `function ${name}`;
+ const found = source.indexOf(marker);
+ if (found < 0) throw new Error(`missing ${name}`);
+ // Keep an `async` prefix — dropping it turns the body's `await` into a
+ // SyntaxError instead of running the real function.
+ const start = source.startsWith('async ', found - 6) ? found - 6 : found;
+ const braceStart = source.indexOf('{', found);
+ let depth = 0;
+ for (let i = braceStart; i < source.length; i += 1) {
+ if (source[i] === '{') depth += 1;
+ else if (source[i] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(start, i + 1);
+ }
+ }
+ throw new Error(`unterminated ${name}`);
+}
+
+type Bindings = Record<string, string[]>;
+type Recipient = { kind: string; id?: string; name?: string };
+
+/** Let pending microtasks and the IPC promise chain settle. */
+const settle = () => new Promise((resolve) => { setTimeout(resolve, 0); });
+
+function mountProjectDetail(bindings: Bindings, held: string[] = []) {
+ const holdSet = new Set(held);
+ const gates: Record<string, Array<() => void>> = {};
+ const bindingCalls: string[] = [];
+ const answer = (channel: string, value: unknown) => {
+ if (!holdSet.has(channel)) return Promise.resolve(value);
+ return new Promise((resolve) => {
+ (gates[channel] ||= []).push(() => resolve(value));
+ });
+ };
+ const context = vm.createContext({
+ console,
+ createLogger: () => ({ warn() {}, info() {}, error() {} }),
+ document: {
+ readyState: 'loading',
+ addEventListener() {},
+ getElementById() { return null; },
+ querySelectorAll() { return []; },
+ createElement() { return { appendChild() {}, className: '', dataset: {}, style: {} }; },
+ },
+ window: {
+ addEventListener() {},
+ orkas: {
+ invoke(channel: string, args: { projectId?: string }) {
+ const pid = args?.projectId || '';
+ switch (channel) {
+ case 'projects.get':
+ return answer(channel, { ok: true, project: { project_id: pid, name: pid } });
+ case 'projects.bindings.list':
+ bindingCalls.push(pid);
+ return answer(channel, {
+ ok: true,
+ bindings: { agents: bindings[pid] || [], skills: [] },
+ agentDetails: [],
+ skillDetails: [],
+ });
+ case 'projects.files.tree':
+ return answer(channel, { ok: true, tree: [] });
+ case 'projects.files.status':
+ case 'projects.instructions.get':
+ return answer(channel, { ok: false });
+ case 'autoTasks.list':
+ return answer(channel, { ok: true, tasks: [] });
+ default:
+ return Promise.resolve({ ok: true });
+ }
+ },
+ },
+ },
+ t: (key: string) => key,
+ uiAlert() {},
+ setTimeout,
+ clearTimeout,
+ });
+ vm.runInContext(projectDetailSource, context, { filename: 'project-detail.js' });
+ vm.runInContext(
+ extractFunction(conversationSource, 'validateRecipientAgainstProject'),
+ context,
+ { filename: 'conversation.js#validateRecipientAgainstProject' },
+ );
+ // Recipient store fixture — holds state only; the reset rule under test
+ // lives in the two real functions loaded above.
+ vm.runInContext(`
+ let __projectRecipient = { kind: 'commander' };
+ function _activeRecipient(target) {
+ return target === 'project' ? __projectRecipient : { kind: 'commander' };
+ }
+ function setChatRecipient(target, next) {
+ if (target === 'project') __projectRecipient = next;
+ }
+ function _renderRecipientChip() {}
+ function __readProjectRecipient() { return JSON.parse(JSON.stringify(__projectRecipient)); }
+ function __pickProjectAgent(id, name) { __projectRecipient = { kind: 'agent', id, name }; }
+ _renderProjectDetail = function () {};
+ _setProjectAutoTabCount = function () {};
+ _kickProjectKbReconcileIfNeeded = function () {};
+ _scheduleProjectKbStatusRefreshIfNeeded = function () {};
+ `, context);
+ return {
+ bindingCalls,
+ pickAgent(id: string, name: string) {
+ vm.runInContext(`__pickProjectAgent(${JSON.stringify(id)}, ${JSON.stringify(name)})`, context);
+ },
+ open(pid: string) {
+ return vm.runInContext(`loadProjectDetail(${JSON.stringify(pid)})`, context) as Promise<void>;
+ },
+ release(channel: string) {
+ const queued = gates[channel] || [];
+ gates[channel] = [];
+ queued.forEach((fn) => fn());
+ },
+ recipient() {
+ return vm.runInContext('__readProjectRecipient()', context) as Recipient;
+ },
+ };
+}
+
+const COMMANDER: Recipient = { kind: 'commander' };
+
+describe('project composer recipient follows the open project', () => {
+ it('drops an agent the newly opened project is not bound to', async () => {
+ const panel = mountProjectDetail({ p_alpha: ['agent_writer'], p_beta: ['agent_coder'] });
+ await panel.open('p_alpha');
+ panel.pickAgent('agent_writer', 'Writer');
+
+ await panel.open('p_beta');
+
+ expect(panel.recipient()).toEqual(COMMANDER);
+ });
+
+ it('keeps a pick the newly opened project is also bound to', async () => {
+ const panel = mountProjectDetail({ p_alpha: ['agent_writer'], p_beta: ['agent_writer'] });
+ await panel.open('p_alpha');
+ panel.pickAgent('agent_writer', 'Writer');
+
+ await panel.open('p_beta');
+
+ expect(panel.recipient()).toEqual({ kind: 'agent', id: 'agent_writer', name: 'Writer' });
+ });
+
+ it('drops the pick when that agent is unbound while the project stays open', async () => {
+ const bindings: Bindings = { p_alpha: ['agent_writer'] };
+ const panel = mountProjectDetail(bindings);
+ await panel.open('p_alpha');
+ panel.pickAgent('agent_writer', 'Writer');
+
+ bindings.p_alpha = [];
+ await panel.open('p_alpha'); // what `_removeProjectAgent` re-runs after a removal
+
+ expect(panel.recipient()).toEqual(COMMANDER);
+ });
+
+ it('clears the stale target before the rest of the project load finishes', async () => {
+ // A large library makes `projects.files.tree` the slow leg of the load
+ // batch. The composer is usable that whole time, so the recipient must be
+ // corrected off the bindings answer alone.
+ const panel = mountProjectDetail(
+ { p_alpha: ['agent_writer'], p_beta: [] },
+ ['projects.files.tree'],
+ );
+ const first = panel.open('p_alpha');
+ panel.release('projects.files.tree');
+ await first;
+ panel.pickAgent('agent_writer', 'Writer');
+
+ const second = panel.open('p_beta');
+ await settle();
+
+ expect(panel.recipient()).toEqual(COMMANDER);
+
+ panel.release('projects.files.tree');
+ await second;
+ });
+
+ it('ignores a bindings answer for a project the user already left', async () => {
+ const panel = mountProjectDetail(
+ { p_alpha: ['agent_writer'], p_beta: ['agent_coder'] },
+ ['projects.bindings.list'],
+ );
+ const first = panel.open('p_alpha');
+ const second = panel.open('p_beta');
+ panel.pickAgent('agent_coder', 'Coder'); // valid in the project now on screen
+
+ panel.release('projects.bindings.list'); // p_alpha answers too, late
+ await Promise.all([first, second]);
+
+ expect(panel.recipient()).toEqual({ kind: 'agent', id: 'agent_coder', name: 'Coder' });
+ expect(panel.bindingCalls).toEqual(['p_alpha', 'p_beta']);
+ });
+});