Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
feat(reflection orchestrator + window state + signals patch suggester + plan polish)
wyta0911ac905b9
diff --git a/CLAUDE.md b/CLAUDE.mdindex 5d809d76..0a932371 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -85,22 +85,10 @@ util/ Pure-function utilities (stdlib only or single third-party dException: env-var names with the project prefix (`ORKAS_NODE` / `ORKAS_PC_DIR`) are allowed when actually referenced in bash. Before adding/changing a prompt, `grep "Orkas\|/Users/\|/home/\|PC/data\|PC/src" src/main/prompts/*.md` should come back clean.-**Platform-editing language constraint**: when the inline edit chat targets a platform-installed skill / agent (dev mode only — see §6), the system-prompt tail uses `i18n.ts::buildBuiltinEditingConstraint()` instead of `buildLanguageDirective()`. The directive forces English output for every field except `description_zh`, regardless of the user's UI language. **Why:** platform content ships to a multilingual user base; source files must stay English-only (see §6) and per-user UI language must not influence what gets published.-**Authoring rules live in platform skills, not in `chat_*.md`**: the canonical authoring rules for agents (`<agent>` container) and skills (`<skill>` container + `<<<skill-file>>>` blocks) live in two platform skills installed from the marketplace under ids `agent-creator` and `skill-creator`. The four prompts that previously copy-pasted these rules (`chat_commander.md`, `chat_agent_setup.md`, `chat_agent_setup_cli.md`, `chat_skill_setup.md`) now carry only a session-shell + `read_file <ROOT>/agent-creator/SKILL.md` (or skill-creator) pointer. **Why:** the long authoring rules are ~200 lines each and were duplicated across four prompts (~600 lines drift surface), kept in sync only by reviewer attention; the duplication caused the commander prompt to balloon past 460 lines, putting the rules in the lost-in-the-middle band. Moving them to platform skills cuts the always-loaded system prompt by ~590 lines and gives every authoring surface a single source of truth — the LLM `read_file`s the skill on demand. Field-level authoring details, including `category` candidate codes, belong in the matching creator skill; if the category set changes, update `agent-creator/SKILL.md` and `skill-creator/SKILL.md` together. The writer backfills a default category on missing/unsafe values; missing category is an advisory, not a write-blocking schema failure.**Cross-prompt sync constraint for residual shared rules**: a few smaller cross-prompt concepts still live inline (`<agent-input-form>` / `<agent-input-submission>` extract-first protocol in `chat_agent_in_group.md`, the `chat_shared_rules.md` web/PDF/file-output block injected by `bus.ts::concatSharedRules`). For those, the historical principle stands: pick one authoritative prompt as truth, downstream sites carry only the principle (no field detail / schema tables / full translation tables). Before touching the truth source, run `grep -E "<agent-input-form>|<agent-input-submission>" src/main/prompts/*.md` to reconcile downstream.-**Adding prompt text**: lean-prompt discipline applies to **every LLM-facing prompt** — `prompts/*.md`, SKILL.md bodies, agent / skill specs, and CLAUDE.md itself. Before adding any new clause, run two checks:--1. **Is each clause necessary?** Cut narrative filler ("…and is what users complain about most"), redundant cross-references to globally-declared rules ("(in the user's UI language — the trailing language directive sets that)"), and double-emphasis ("even one token, even one field"). Keep the rule, the *Why* for counter-intuitive choices, and a concrete example when the rule is structural. **The test:** delete the clause; if the model behaves the same, drop it.--2. **Does it conflict with or duplicate existing content?** Grep the same prompt md and its peers (`chat_*.md` share a domain; `chat_shared_rules.md` is injected into multiple roles — see the cross-prompt sync constraint above). Partial overlap → **merge** into one tighter rule, don't ship a parallel paragraph (parallel rules dilute each other; the model honours neither cleanly). Contradiction → **fix one to match the other**, don't ship both.--3. **Show the audit (process enforcement)**: any response that submits a prompt-md edit MUST contain a visible per-clause audit — one row per newly added clause marked ✅ (necessary; which Keep category) or ❌ (cut; which redundancy reason from check 1). Without the audit in the response, treat the edit as incomplete. This binds checks 1 and 2 to a concrete moment so they aren't silently skipped.--**Why:** prompt text sits in the cached prefix and shapes every turn. We shipped "don't paste absolute paths" + "don't enumerate bash scratch" as two parallel paragraphs in `chat_shared_rules.md` and watched the model honour neither until the merge. We also shipped this rule itself as advisory at first and watched the audit get skipped on every subsequent prompt-md edit until the audit-as-artifact step made skipping visible. Merge first, write second; show the audit.-**Prompt-md cache layout** (KV-cache prefix discipline): every `src/main/prompts/<name>.md` is split into two halves — **static rules first, then a single trailing `## Runtime injection` section that collects every `$variable` substitution** (with the most volatile field at the bottom of that section). Final assembled order = `<role>.md` static body → `chat_shared_rules.md` (when applicable) → `<role>.md` `## Runtime injection` → `buildLanguageDirective()`. The shared block is wedged in front of the runtime block by `bus.ts::concatSharedRules`; the language directive is appended last by `appendLanguageDirective`. **No `## Current xxx` / "current state" block at the top of the file** — anything the LLM itself rewrites mid-session (`<agent>` writeback / `<<<skill-file>>>` / `plan_set` / form submissions: `$name` / `$description*` / `$workflow` / `$skill_dir` / `$skill_files` / `$plan_state` / `$agents_index` / `$inputs_schema` / `$interactive`) goes only into the trailing runtime section. **Why:** putting volatile fields up front means the very next turn rewrites the cache prefix and we eat a full re-prefill; `chat_agent_setup.md` / `chat_agent_setup_cli.md` / `chat_skill_setup.md` shipped with a top-of-file `## Current agent` / `## Current skill` block, every edit turn invalidated the cache, and the fix was to consolidate those into the trailing `## Runtime injection` section. Same applies to any new prompt md added under `src/main/prompts/`. Path-constants that are fixed for the lifetime of a session (`$builtin_*_dir` / `$custom_*_dir` / `$working_dir`) are session-stable and may stay inline in the body; only fields that the LLM or bus mutate within a session are forbidden in the prefix.---@@ -142,7 +130,7 @@ Top-level three-way split: **cloud** (user-private, synced across devices) / **l**Hard constraints**:1. **At top level**, only `users.json` / `logs/` / `<uid>/` are allowed; per-user data must land under `<uid>/{cloud,local}/`. There is no shipped global `builtin/` tree (retired with the marketplace cutover; one-shot migration in `util/migrate-marketplace.ts` moves any legacy `data/builtin/` into the active uid's cloud tree on first launch, then deletes it).2. **Platform agents / skills are marketplace-only**: published to the server via `marketplace_dev.upload*` (dev only), installed via `marketplace.installMarketplace*` to `<uid>/local/marketplace/{agents,skills}/<id>/`. The on-disk dir contains the same shape as a custom one (`agent.json` for agents, `SKILL.md` + script files for skills) plus a `_install.json` with `(version, published_at)` used by reconcile to detect drift. The cloud-synced manifest `<uid>/cloud/marketplace/installs.json` records `{id, version, published_at, url}` per entry; `marketplace_reconcile.reconcileInstalls(uid)` runs on startup, parallel-fetches anything missing from the local tree, and re-pulls when the manifest version disagrees with `_install.json`. Immediately before reconcile, `checkServerUpdatesForInstalls(uid)` sweeps every installed id against the server `/marketplace/{agents,skills}/list` endpoint and bumps the manifest's `(version, published_at)` when the server is newer — admin republishes propagate to every client on next startup without user action; offline boots swallow the network error and fall through to a normal reconcile against the stale manifest. **Why this split**: content is binary-blob / catalog-versioned and would tear cloud sync if every machine wrote the same bytes; per-machine local copy + tiny cloud-synced manifest = single source of truth at the manifest level, machine-private at the content level. The loaders scan `[<uid>/cloud/{agents,skills}/, <uid>/local/marketplace/{agents,skills}/]`; custom takes precedence over a platform install with the same id.-3. **Agent directory shape (per-agent asset aggregation)**: `<uid>/cloud/agents/<aid>/` contains `agent.json` (the sole UI display source — pure spec) + `meta/` (metacognition: COMPETENCE.md + LEARNING_STRATEGIES.md) + `skills/` (SkillStore self-evolved skills, visible only to this agent, not injected into the SkillLoader system-prompt block). Deleting an agent = `rm -rf <aid>/`, no cascade. See `docs/plans/agent-as-directory.md`. **Do not** revert to the old top-level `meta/` or `PC/skills/` (the SkillStore default cwd).+3. **Agent directory shape (per-agent asset aggregation)**: `<uid>/cloud/agents/<aid>/` contains `agent.json` (the sole UI display source — pure spec) + `meta/` (metacognition: COMPETENCE.md + LEARNING_STRATEGIES.md) + `skills/` (SkillStore self-evolved skills, visible only to this agent, not injected into the SkillLoader system-prompt block). Deleting an agent = `rm -rf <aid>/`, no cascade. **Do not** revert to the old top-level `meta/` or `PC/skills/` (the SkillStore default cwd).4. **`search/` indexes are purely derived**: never synced; mtime+size reconcile self-heals before each query; 1-second debounced flush + force flush on `before-quit`; rebuild automatically on schema change or corruption.5. **The KB vector store is NOT cloud-synced (batch 2 decision)**: only `cloud/contexts/` source files cross devices; the `vector.db` + its `config.json` live at `<uid>/local/contexts/.kb/` (machine-private, NOT under cloud/). Each device's startup `kb_indexer.reconcile(uid)` rebuilds the index from the synced sources idempotently by sha1. One-shot migration `util/migrate-kb-to-local.ts` moves a pre-existing `<uid>/cloud/contexts/.kb/` directory into local/ on first launch (stamped under `.migrations`). **Why path mirrors cloud/contexts/ under local/contexts/**: keeps the mental model "KB lives under .../contexts/.kb/" intact across the cloud/local divide, so the cloud→local split is reflected in the path without renaming the `.kb` segment. **Why this changed from the earlier "vector.db IS synced" rule**: a single-doc edit kicks a hundreds-of-MB whole-DB re-upload — economics broke down once we wired the actual sync engine. Index rebuild is per-spec idempotent, so reuse it. **Journal mode is still DELETE, not WAL** (no benefit from switching; `kb_files` rows already use it).6. **Multi-device sync (plan: `PC/docs/plans/multi-device-sync.md`)**: COS bucket prefix = **`private/<oauth_user_id>/`** (NOT the local 8-digit `uid`); per-machine path stays `<container>/data/<local_uid>/cloud/`, and `private/<oauth_user_id>/` is the cloud-side mirror. **Why the `private/` namespace**: leaves the rest of the bucket (e.g. `public/marketplace/skills/`) freely STS-scoped for non-user-private content; without it, widening any future public scope risks colliding with user data prefixes. **Why oauth_user_id (not local uid)**: same OAuth user has different local `uid` on each device — using local uid would scatter cloud data. The `features/sync/` engine is the **sole** writer of cloud→COS traffic and `private/<oauth_user_id>/cloud/*` keys; `features/sync/manifest.ts::commitManifest` (POST `/sync/manifest/commit`) is the **sole** writer of `private/<oauth_user_id>/manifest.json` (Server enforces atomicity via per-user lock + generation CAS + quota delta; see `Server/CLAUDE.md` §4). PC's STS scope is `private/<oauth_user_id>/*` for read, `private/<oauth_user_id>/cloud/*` for write — `manifest.json` is read-only for PC by design. **Five canonical sync triggers** funnel through `DirtyBus` / `engine.syncNow`: startup (post-marketplace reconcile), debounce-fired dirty event, manual ("立即同步" button), 5-minute periodic safety-net ticker (`engine.ts::PERIODIC_INTERVAL_MS`, bound to engine lifetime so the master switch gates it for free), before-quit. The 30s global floor between auto runs (`engine.ts::GLOBAL_FLOOR_MS`) applies to all except manual + before-quit (which bypass it intentionally; periodic respects it — a recent pass for any reason defers the next tick). **3-way pull classification** (`manifest.ts::classifyPullCandidates`, called from `_passBody` step 5): every path `diff()` puts into `need_pull` is routed by the (base, disk, remote) sha tuple — case A `base==disk` (local untouched, remote moved) → straight overwrite, **never push**; case B `base==remote` (local moved, remote untouched) → reclassify to push (legacy 3-way diff); case C three-way divergence → content-aware merge, then push the merge result back. **Why case A must not push**: a path whose on-disk bytes differ from base usually came from a prior merge's residue, NOT a fresh user edit — pushing it would publish the engine's own historical output as if it were a user change. We shipped this bug for a while and saw `pulled: 4 / pushed: 0` every pass for the same set of jsonl + mutable-json paths; the case A bucket is the load-bearing fix.@@ -150,7 +138,7 @@ Top-level three-way split: **cloud** (user-private, synced across devices) / **l- **`LOCAL_DATA_VERSION` data-version gate** (`features/sync/data_version.ts`): every PC build carries an integer schema-version constant; on each pass the engine compares it to `manifest.data_version` post-fetch and aborts with `pause_reason = 'version_outdated'` when `remote > LOCAL_DATA_VERSION` (Server mirrors the same gate on commit → `client_outdated` / 50404, which the engine handles as a sticky pause rather than a retry-able error). **When to bump + when NOT to + bumping procedure** are the MUST / MUST-NOT checklists in `data_version.ts`'s header comment — that file is the single source of truth for the call; don't restate the criteria elsewhere. **Why a third version field** when `manifest_v` and per-entry `schema_v` exist: they answer different questions — `manifest_v` is the manifest JSON's own structure, `schema_v` is per-file content format (with consumption logic still TODO in `merge/`), and `data_version` is the *global* application-data contract gate. Don't conflate them.8. **`<uid>/local/cache/<bucket>/` is the user-clearable cache umbrella**. Anything dropped under `cache/` is fair game for the "clear cache" UI button (`features/cache_clearable.ts::clearAllClearable`). Distinct from `config/` (user prefs — never auto-cleared) and `biz/` (server-sourced reference data — refresh-on-need but not user-clearable). The marketplace content cache lives at `cache/marketplace/{agents,skills}/<id>/` with a per-entry `_cache.json` carrying `(server_id, version, published_at, fetched_at, last_used_at)`; entry-time sweep evicts entries idle > 7d AND LRU-trims when total > 100 MB (see `features/marketplace_cache.ts::sweepIfNeeded`, called once per `openMarketplace`). **Note**: `local/marketplace/{agents,skills}/<id>/` (the install target — constraint 2) is NOT under `cache/` and is NOT user-clearable; only the staging cache for browsing detail is. Future migration: `file_cache/` and `tool-results/` will move under `cache/` so a single "clear cache" hits all of them — DON'T yet rely on this; each owner module updates its path helper before the move.-9. **`<uid>/local/signals/<yyyy-mm-dd>.jsonl` is the expert-signal stream** (T0/T1 user-behavior records — retry / skip / form_left_blank / silence / tool_failure / accept / correction / reject / edit / skill_advertised / skill_invoked / skill_ineffective / agent_dispatched). Local-only, append-only, daily-rotated. **Sole writer for the features layer = `features/expert_signals/emitSignal`**; chokepoint sites are `features/group_chat/bus.ts::runTurn` end + `_enqueueBody` USER_ID branch + `features/group_chat/index.ts::{retryStep, skipStep, markFormSubmittedAndDispatch}` + `features/group_chat/plan_executor.ts::dispatchReady`. **Model-layer signals route through `ChatOptions.{onSkillAdvertised, onSkillInvoked}` callbacks** drained at bus turn-end (`expert_signals/turn_hooks.ts::createSkillTurnBuffer`); **the model layer must never `import { emitSignal }` directly** (would reverse-import features/ and violate §3 layering). **Why centralized**: scattered `emitSignal` across `features/*` (or, post-callback, scattered model-layer imports) violates the single-dispatch-primitive rule (§5) and produces signals whose order disagrees with turn order — downstream reflection / patch suggester / critic (phase 1+) all assume turn-aligned causality. **`turn_id` convention**: every signal's `turn_id` is the agent msg id the signal reacts to or is produced by (agent-side = self; user-reaction = previous agent msg; retry/skip = `step.output_msg_id`; agent_dispatched = synthetic `<cid>:plan:dispatch:<ts>:<i>` since no commander msg id is plumbed through plan_executor yet). Direct JOIN on `turn_id` recovers cross-signal causality (skill_invoked × correction, retry × tool_failure). Phase 0 has NO redaction layer (see §10). Plans: `docs/plans/expert-signals-phase-0.md`, `docs/plans/expert-signals-skill-attribution.md` (phase 0 follow-up for skill / agent attribution).+9. **`<uid>/local/signals/<yyyy-mm-dd>.jsonl` is the expert-signal stream** (T0/T1 user-behavior records — retry / skip / form_left_blank / silence / tool_failure / accept / correction / reject / edit / skill_advertised / skill_invoked / skill_ineffective / agent_dispatched). Local-only, append-only, daily-rotated. **Sole writer for the features layer = `features/expert_signals/emitSignal`**; chokepoint sites are `features/group_chat/bus.ts::runTurn` end + `_enqueueBody` USER_ID branch + `features/group_chat/index.ts::{retryStep, skipStep, markFormSubmittedAndDispatch}` + `features/group_chat/plan_executor.ts::dispatchReady`. **Model-layer signals route through `ChatOptions.{onSkillAdvertised, onSkillInvoked}` callbacks** drained at bus turn-end (`expert_signals/turn_hooks.ts::createSkillTurnBuffer`); **the model layer must never `import { emitSignal }` directly** (would reverse-import features/ and violate §3 layering). **Why centralized**: scattered `emitSignal` across `features/*` (or, post-callback, scattered model-layer imports) violates the single-dispatch-primitive rule (§5) and produces signals whose order disagrees with turn order — downstream reflection / patch suggester / critic (phase 1+) all assume turn-aligned causality. **`turn_id` convention**: every signal's `turn_id` is the agent msg id the signal reacts to or is produced by (agent-side = self; user-reaction = previous agent msg; retry/skip = `step.output_msg_id`; agent_dispatched = synthetic `<cid>:plan:dispatch:<ts>:<i>` since no commander msg id is plumbed through plan_executor yet). Direct JOIN on `turn_id` recovers cross-signal causality (skill_invoked × correction, retry × tool_failure). Phase 0 has NO redaction layer (see §10).**uid lifecycle** (`features/users.ts`): on startup, `initActiveUser()` reads or creates `users.json` and calls `activateUser(uid)` (skeleton mkdir + injecting `process.env.CORE_AGENT_AUTH_DIR` + clearing caches + running migrations including `migrateLegacySessionIds`). All user-scoped features get the uid via `getActiveUserId()` (throws if not activated). One active uid at a time for now. **uid shape is unconstrained** — OrkasOpen first-boot generates 8-digit numeric via `genUserId()`; Hosted Orkas reconciles the local uid with the OAuth-issued user_id via `reconcileDevUid`, which today carries through whatever the server emits (UUID with dashes is real). Code that uses `<uid>/...` as a path segment is fine with any shape (single segment, no parsing). Code that USED to embed `<uid>-` into session_id has been removed (§5 — session_id is now `<kind>-<tail>`); never reintroduce that pattern.@@ -320,7 +308,7 @@ Third-party integrations attach via MCP servers (`@modelcontextprotocol/sdk`); O**Catalog bundles** (`CatalogEntry.bundle_member_ids`): a catalog entry can declare itself a **UI-only grouping** that fans out on connect. The bundle entry has `transport_template: null` and never becomes a ConnectorInstance — `manager.connectViaOAuth` runs OAuth once for the bundle (Server returns a grant with the union of all members' scopes, e.g. `_SCOPES_BY_CATALOG_ID['google-workspace']`) and provisions one instance per member with a deep-cloned grant. **Model view is unchanged**: each member stays a distinct connector with its own tools. Renderer hides member entries, shows the bundle card; disconnect / enable-toggle fan out across all members. Used today for `google-workspace`.-**OrkasOpen**: nothing in `features/connectors/` is stripped — connectors are 100% client-side. (A future marketplace-style recommended-connectors UI would gate the same way `marketplace_dev` does — see §9 OrkasOpen contract.)+**OrkasOpen**: nothing in `features/connectors/` is stripped — connectors, including Google Workspace catalog entries and stdio adapters, sync to the open-source build. (A future marketplace-style recommended-connectors UI would gate the same way `marketplace_dev` does — see §9 OrkasOpen contract.)---@@ -332,7 +320,7 @@ Third-party integrations attach via MCP servers (`@modelcontextprotocol/sdk`); O- **Embedder is fixed at `bge-small-zh-v1.5`, 512 dims**; switching models requires a full rebuild (`config.json` lock prevents accidental swaps). The model is ~95 MB and ships via the installer's `extraResources`, so zero download / zero network at runtime.- **Journal mode is DELETE, not WAL** — kept for continuity with existing `kb_files` rows (the original "WAL would tear cloud sync" rationale is moot now that vector.db is machine-private, but switching brings no benefit).- **No `worker_threads` for multiple ONNX sessions**: empirically the native layer SIGSEGVs (OpenMP threadpool + concurrent allocator init is a known dangerous combination); for true parallelism use `child_process`.-- The model side may use only `kb_search` / `kb_read` tools; **`cat` / `rg` access to `$contexts_dir/` is forbidden** (stated in `chat_core.md`).+- The model side may use only `kb_search` / `kb_read` tools; **`cat` / `rg` access to `$contexts_dir/` is forbidden**.- Chunk cap is `EMBED_MAX_CHARS=400` chars (matching the 512-token window); no overlap across segments to avoid topic pollution.- `_INDEX.md` is generated only at the root of contexts for users browsing in Finder; **the model does not read it**.- Cloud-sync conflicts take the newer mtime; the loser runs `reconcile` at startup to backfill via sha1; the `kb_files` table is the manifest, no separate manifest file is needed.diff --git a/bin/run-skill.cjs b/bin/run-skill.cjsindex 4047dba1..38c11d15 100755--- a/bin/run-skill.cjs+++ b/bin/run-skill.cjs@@ -61,13 +61,6 @@ function parseArgs(argv) {return { skillId, scriptBase, scriptArgs };}-// Sibling directories of WS_ROOT that are NOT user-id dirs. See paths.ts —-// users.json / window-state.json are files (filtered by isDirectory above);-// these are the directories we must not treat as uids.-const RESERVED_WS_DIRS = new Set([- 'logs', 'config', 'user_workspaces', 'builtin',-]);-function locateSkillScript(skillId, scriptBase) {const wsRoot = process.env.ORKAS_WORKSPACE_ROOT|| process.env.ORKAS_WS_ROOT@@ -75,17 +68,26 @@ function locateSkillScript(skillId, scriptBase) {// Candidate skill dirs — mirror SkillRegistry's// [<uid>/cloud/skills, <uid>/local/marketplace/skills] resolution, with a// dev/source-tree fallback for unpacked builtins.- const skillDirs = [];+ //// Per-user skills live under <ws>/<uid>/cloud/skills/<id> and// <ws>/<uid>/local/marketplace/skills/<id>. uid can be numeric or a UUID,- // so we scan every non-reserved subdirectory rather than regex-matching.+ // so we scan every subdirectory rather than regex-matching. Skip the deny-+ // list approach (had to hand-maintain a list of `logs / config / ...`+ // sibling names that would drift the moment a new top-level data dir gets+ // added under PC/CLAUDE.md §4); instead, only KEEP an entry if it actually+ // contains the skill under one of the two SkillRegistry-aware shapes. This+ // is the strict invariant — a real uid dir always has one of those shapes+ // when the skill is installed for that user; any sibling dir that doesn't+ // is irrelevant by construction.+ const skillDirs = [];try {for (const entry of fs.readdirSync(wsRoot, { withFileTypes: true })) {if (!entry.isDirectory()) continue;if (entry.name.startsWith('.')) continue;- if (RESERVED_WS_DIRS.has(entry.name)) continue;- skillDirs.push(path.join(wsRoot, entry.name, 'cloud', 'skills', skillId));- skillDirs.push(path.join(wsRoot, entry.name, 'local', 'marketplace', 'skills', skillId));+ const cloud = path.join(wsRoot, entry.name, 'cloud', 'skills', skillId);+ const marketplace = path.join(wsRoot, entry.name, 'local', 'marketplace', 'skills', skillId);+ if (fs.existsSync(cloud)) skillDirs.push(cloud);+ if (fs.existsSync(marketplace)) skillDirs.push(marketplace);}} catch { /* no data dir yet */ }if (process.env.ORKAS_PC_DIR) {diff --git a/bootstrap.cjs b/bootstrap.cjsindex 0fed8e91..bd55dcd6 100644--- a/bootstrap.cjs+++ b/bootstrap.cjs@@ -18,6 +18,38 @@'use strict';require('./src/main/install-data-root.cjs');+const fs = require('node:fs');+const path = require('node:path');++function configurePackagedEsbuildBinary() {+ if (!process.versions.electron || !process.resourcesPath || process.env.ESBUILD_BINARY_PATH) {+ return;+ }++ const platformPackages = {+ 'darwin:arm64': ['@esbuild', 'darwin-arm64', 'bin', 'esbuild'],+ 'darwin:x64': ['@esbuild', 'darwin-x64', 'bin', 'esbuild'],+ 'linux:arm64': ['@esbuild', 'linux-arm64', 'bin', 'esbuild'],+ 'linux:x64': ['@esbuild', 'linux-x64', 'bin', 'esbuild'],+ 'win32:arm64': ['@esbuild', 'win32-arm64', 'esbuild.exe'],+ 'win32:ia32': ['@esbuild', 'win32-ia32', 'esbuild.exe'],+ 'win32:x64': ['@esbuild', 'win32-x64', 'esbuild.exe'],+ };+ const parts = platformPackages[`${process.platform}:${process.arch}`];+ if (!parts) return;++ const bin = path.join(+ process.resourcesPath,+ 'app.asar.unpacked',+ 'node_modules',+ ...parts,+ );+ if (fs.existsSync(bin)) {+ process.env.ESBUILD_BINARY_PATH = bin;+ }+}++configurePackagedEsbuildBinary();require('tsx/cjs');require('tsx/esm/api').register();diff --git a/package-lock.json b/package-lock.jsonindex 6c6e181a..b33337d6 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,14 @@{"name": "orkas","version": "2026.4.30",+ "version": "2026.5.21","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "orkas","version": "2026.4.30",+ "version": "2026.5.21","hasInstallScript": true,"license": "MIT","dependencies": {@@ -19,7 +21,6 @@"fastembed": "^2.1.0","jimp": "^1.6.1","mammoth": "^1.12.0",- "onnxruntime-node": "^1.24.3","pdfjs-dist": "^5.6.205","sqlite-vec": "^0.1.9","tsx": "^4.21.0",@@ -6444,29 +6445,6 @@"node": ">=6"}},- "node_modules/onnxruntime-common": {- "version": "1.24.3",- "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.24.3.tgz",- "integrity": "sha512-GeuPZO6U/LBJXvwdaqHbuUmoXiEdeCjWi/EG7Y1HNnDwJYuk6WUbNXpF6luSUY8yASul3cmUlLGrCCL1ZgVXqA==",- "license": "MIT"- },- "node_modules/onnxruntime-node": {- "version": "1.24.3",- "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.24.3.tgz",- "integrity": "sha512-JH7+czbc8ALA819vlTgcV+Q214/+VjGeBHDjX81+ZCD0PCVCIFGFNtT0V4sXG/1JXypKPgScQcB3ij/hk3YnTg==",- "hasInstallScript": true,- "license": "MIT",- "os": [- "win32",- "darwin",- "linux"- ],- "dependencies": {- "adm-zip": "^0.5.16",- "global-agent": "^3.0.0",- "onnxruntime-common": "1.24.3"- }- },"node_modules/openai": {"version": "6.26.0","license": "Apache-2.0",diff --git a/package.json b/package.jsonindex d1cb43ec..942e4424 100644--- a/package.json+++ b/package.json@@ -1,6 +1,7 @@{"name": "orkas","version": "2026.4.30",+ "version": "2026.5.21","private": true,"license": "MIT","description": "Orkas desktop — Electron + Node one-piece app",@@ -19,6 +20,7 @@"rebuild:sqlite:electron": "node scripts/swap-sqlite-abi.mjs electron","rebuild:sqlite:node": "node scripts/swap-sqlite-abi.mjs node","postinstall": "node scripts/swap-sqlite-abi.mjs electron && node scripts/fetch-embedding-model.mjs",+ "prepare": "node scripts/install-git-hooks.mjs","prepack": "node scripts/swap-sqlite-abi.mjs electron","predist": "node scripts/swap-sqlite-abi.mjs electron","pack": "electron-builder --dir",@@ -48,7 +50,6 @@"fastembed": "^2.1.0","jimp": "^1.6.1","mammoth": "^1.12.0",- "onnxruntime-node": "^1.24.3","pdfjs-dist": "^5.6.205","sqlite-vec": "^0.1.9","tsx": "^4.21.0",@@ -102,7 +103,6 @@"node_modules/bindings/**/*","node_modules/file-uri-to-path/**/*","node_modules/sqlite-vec*/**/*",- "node_modules/onnxruntime-node/**/*","node_modules/fastembed/**/*"],"extraResources": [@@ -136,6 +136,9 @@],"icon": "src/resources/icons/icon.icns"},+ "dmg": {+ "writeUpdateInfo": false+ },"win": {"target": "nsis","icon": "src/resources/icons/icon.ico"diff --git a/scripts/codesign-adhoc.cjs b/scripts/codesign-adhoc.cjsindex fcc4657b..170993ec 100644--- a/scripts/codesign-adhoc.cjs+++ b/scripts/codesign-adhoc.cjs@@ -11,16 +11,76 @@'use strict';const { execSync } = require('node:child_process');+const fs = require('node:fs');const path = require('node:path');+const ARCH_NAMES = {+ 0: 'ia32',+ 1: 'x64',+ 2: 'armv7l',+ 3: 'arm64',+ 4: 'universal',+};++function removeIfExists(target) {+ if (fs.existsSync(target)) fs.rmSync(target, { recursive: true, force: true });+}++function listDirs(dir) {+ if (!fs.existsSync(dir)) return [];+ return fs.readdirSync(dir, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => entry.name);+}++function pruneOnnxRuntimePackage(pkgDir, targetArch) {+ const binDir = path.join(pkgDir, 'bin');+ if (!fs.existsSync(binDir)) return;++ const keepArch = targetArch === 'arm64' || targetArch === 'x64' ? targetArch : null;+ for (const napiDirName of listDirs(binDir)) {+ const napiDir = path.join(binDir, napiDirName);+ for (const platformDirName of listDirs(napiDir)) {+ if (platformDirName !== 'darwin') {+ removeIfExists(path.join(napiDir, platformDirName));+ }+ }++ if (!keepArch) continue;+ const darwinDir = path.join(napiDir, 'darwin');+ for (const archDirName of listDirs(darwinDir)) {+ if (archDirName !== keepArch) {+ removeIfExists(path.join(darwinDir, archDirName));+ }+ }+ }+}++function prunePackedNativePayload(appPath, targetArch) {+ const nodeModules = path.join(appPath, 'Contents', 'Resources', 'app.asar.unpacked', 'node_modules');+ const packages = [+ path.join(nodeModules, 'onnxruntime-node'),+ path.join(nodeModules, 'fastembed', 'node_modules', 'onnxruntime-node'),+ ];++ for (const pkgDir of packages) {+ pruneOnnxRuntimePackage(pkgDir, targetArch);+ }+}+module.exports = async function afterPack(context) {if (context.electronPlatformName !== 'darwin') return;+ const appName = context.packager.appInfo.productFilename;+ const appPath = path.join(context.appOutDir, `${appName}.app`);+ const targetArch = ARCH_NAMES[context.arch] || process.arch;++ prunePackedNativePayload(appPath, targetArch);+if (process.env.CSC_LINK || process.env.CSC_NAME) {console.log('[codesign-adhoc] formal signing env detected; skipping ad-hoc signing');return;}- const appName = context.packager.appInfo.productFilename;- const appPath = path.join(context.appOutDir, `${appName}.app`);+console.log(`[codesign-adhoc] signing ${appPath}`);execSync(`codesign --force --deep --sign - "${appPath}"`, { stdio: 'inherit' });// 校验签名(失败时直接 throw 中断 build,避免发出未签的包)diff --git a/scripts/install-git-hooks.mjs b/scripts/install-git-hooks.mjsnew file mode 100644index 00000000..89d72035--- /dev/null+++ b/scripts/install-git-hooks.mjs@@ -0,0 +1,52 @@+#!/usr/bin/env node+/**+ * Auto-install the repo-local git hooks directory.+ *+ * Wired into PC/package.json `prepare`, which `npm install` runs whenever+ * a contributor sets up the repo. Effect:+ *+ * git config core.hooksPath <repo-root>/.githooks+ *+ * so the commit-msg hook (the one that enforces `Prompt audit:` on+ * prompt-facing commits) is on by default — no per-machine ceremony.+ *+ * Best-effort: silently no-ops when+ * - cwd isn't inside a git checkout (e.g. tarball install)+ * - the .githooks/ directory isn't present+ * - `git` isn't on PATH+ * so a botched local setup never blocks `npm install`.+ */++import { execSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';++function tryGitTopLevel() {+ try {+ return execSync('git rev-parse --show-toplevel', { stdio: ['ignore', 'pipe', 'ignore'] })+ .toString()+ .trim();+ } catch {+ return null;+ }+}++const repoRoot = tryGitTopLevel();+if (!repoRoot) {+ // Not a git checkout — npm install from a published tarball, CI install+ // with .git stripped, etc. Silently no-op.+ process.exit(0);+}++const hooksDir = path.join(repoRoot, '.githooks');+if (!fs.existsSync(hooksDir)) {+ // No hooks vendored in this checkout — nothing to wire up.+ process.exit(0);+}++try {+ execSync(`git config core.hooksPath "${hooksDir}"`, { stdio: 'ignore' });+ console.log(`[install-git-hooks] core.hooksPath -> ${hooksDir}`);+} catch (err) {+ console.warn(`[install-git-hooks] skipped: ${(err && err.message) || err}`);+}diff --git a/src/core-agent/src/agent/runner.ts b/src/core-agent/src/agent/runner.tsindex 60b1eba7..7a728c47 100644--- a/src/core-agent/src/agent/runner.ts+++ b/src/core-agent/src/agent/runner.ts@@ -10,7 +10,6 @@ import {import { createLogger } from "../shared/logger.js";import type { CoreAgentConfig } from "../config/schema.js";import type { EvolutionConfig } from "../evolution/types.js";-import { detectUserCorrection } from "../evolution/metacognition.js";import type { LLMProvider, CompletionResult } from "../providers/base.js";import { ProviderRegistry } from "../providers/registry.js";import type { AgentTool, ToolContext } from "../tools/base.js";@@ -18,8 +17,6 @@ import { toToolDefinition } from "../tools/base.js";import { getBuiltinTools } from "../tools/builtin.js";import { SkillStore } from "../evolution/skill-store.js";import { createSkillManageTool } from "../evolution/skill-tools.js";-import { shouldReflect, buildAdaptiveReviewPrompt } from "../evolution/metacognition.js";-import type { MetacognitionConfig, RunMetrics } from "../evolution/types.js";import { Session } from "./session.js";import type { AgentRunParams, AgentRunResult, AgentRunMeta, AgentRunEvent } from "./types.js";@@ -511,163 +508,6 @@ export class AgentRunner {return this.skillStore;}- /**- * Evaluate whether a completed run warrants metacognitive reflection.- * Converts AgentRunResult.meta into RunMetrics, calls shouldReflect(),- * and if triggered, returns the adaptive review prompt. Returns null- * if no reflection is needed.- *- * @param result The completed run result- * @param competence Current COMPETENCE.md content (optional)- * @param strategies Current LEARNING_STRATEGIES.md content (optional)- */- evaluateReflection(- result: AgentRunResult,- competence?: string,- strategies?: string,- /** The user message that triggered this run. When provided, `buildRunMetrics`- * runs `detectUserCorrection` on it to populate `userCorrections`. Wired- * through from the caller per plan §6.1 so the same heuristic feeds both- * this metric and the bus-side `correction` signal (no double-judgment). */- inboundMessage?: string,- ): { prompt: string; primaryFocus: string; score: number } | null {- const metaConfig = this.config.evolution.metacognition as MetacognitionConfig;- if (!metaConfig.enabled) {- log.debug('evaluateReflection: metacognition disabled in config');- return null;- }-- const metrics = this.buildRunMetrics(result, inboundMessage);- log.debug(`evaluateReflection: metrics toolCalls=${metrics.toolCalls} errors=${metrics.errorCount} errorKind=${metrics.errorKind} transient=${metrics.transientErrorCount} corrections=${metrics.userCorrections} skills=[${metrics.skillsLoaded.join(',')}]`);-- const reflection = shouldReflect(metrics, metaConfig, competence);- if (!reflection.shouldReflect) {- log.info(`evaluateReflection: no reflection needed (score=${reflection.score.toFixed(2)} threshold=${metaConfig.reflectThreshold} signals=${reflection.signals.length})`);- return null;- }-- // Build a conversation digest so the reflection LLM has context- // about what actually happened (it runs in an ephemeral session).- const digest = this.buildConversationDigest(result, metrics, reflection.signals);-- const prompt = buildAdaptiveReviewPrompt(- reflection.primaryFocus,- competence || '',- strategies || '',- undefined, // skillHealthReport — future- digest,- );- return {- prompt,- primaryFocus: reflection.primaryFocus,- score: reflection.score,- };- }-- /**- * Build a concise digest of the conversation for the reflection LLM.- * Since the reflection runs in an ephemeral session, it needs this- * context to understand what happened and make meaningful updates.- */- private buildConversationDigest(- result: AgentRunResult,- metrics: RunMetrics,- signals: Array<{ name: string; reason: string }>,- ): string {- const lines: string[] = [];-- // What tools were used- if (metrics.toolNames.length > 0) {- lines.push(`Tools used: ${metrics.toolNames.join(', ')}`);- }-- // Which skills were loaded- if (metrics.skillsLoaded.length > 0) {- lines.push(`Skills loaded: ${metrics.skillsLoaded.join(', ')}`);- }-- // Error info with classification- if (result.meta.error) {- lines.push(`Error: [${result.meta.error.kind}] ${result.meta.error.message}`);- if (metrics.recovered) lines.push('Outcome: recovered from the error and completed the task');- }- if (metrics.errorKind !== 'none') {- const label = metrics.errorKind === 'transient' ? 'transient (network / timeout / rate limit)'- : metrics.errorKind === 'mixed' ? 'mixed (transient + permanent)'- : 'permanent (non-transient)';- lines.push(`Error kind: ${label} (${metrics.transientErrorCount} transient occurrence(s))`);- }-- // Trigger signals- lines.push(`Trigger signals: ${signals.map(s => `${s.name}(${s.reason})`).join('; ')}`);-- // The agent's final response (truncated) — this is the most important- // context for understanding what actually happened- if (result.text) {- const maxLen = 1500;- const text = result.text.length > maxLen- ? result.text.slice(0, maxLen) + '\n…(truncated)'- : result.text;- lines.push('', '--- Final assistant reply ---', text);- }-- // Session message history (user messages only, for additional context)- const messages = this.session.getMessages();- const userMessages = messages- .filter(m => m.role === 'user')- .map(m => {- const textParts = m.content- .filter((c: any) => c.type === 'text')- .map((c: any) => c.text)- .join('');- return textParts;- })- .filter(t => t.length > 0);-- if (userMessages.length > 0) {- lines.push('', '--- User messages ---');- // Include last few user messages (most relevant)- const recent = userMessages.slice(-3);- for (const msg of recent) {- const truncated = msg.length > 300 ? msg.slice(0, 300) + '…' : msg;- lines.push(`- ${truncated}`);- }- }-- return lines.join('\n');- }-- /** Convert AgentRunResult.meta into RunMetrics for the trigger evaluator.- * When `inboundMessage` is provided, runs `detectUserCorrection` to set- * `userCorrections` (otherwise 0). Reuses the same heuristic the bus-side- * expert_signals extractor uses — same input, same boolean. */- private buildRunMetrics(result: AgentRunResult, inboundMessage?: string): RunMetrics {- const meta = result.meta;- const transient = meta.transientToolErrors ?? 0;- const permanent = meta.permanentToolErrors ?? 0;- const hadErrors = meta.error !== undefined || transient + permanent > 0;- const totalToolErrors = transient + permanent;- let errorKind: import('../evolution/types.js').ErrorKind = 'none';- if (totalToolErrors > 0) {- if (transient > 0 && permanent === 0) errorKind = 'transient';- else if (permanent > 0 && transient === 0) errorKind = 'permanent';- else errorKind = 'mixed';- } else if (meta.error) {- errorKind = 'permanent';- }- return {- toolCalls: meta.toolLoops,- toolNames: meta.toolNames ?? [],- skillsLoaded: meta.skillsLoaded ?? [],- hadErrors,- recovered: hadErrors && result.text.length > 0,- errorCount: totalToolErrors + (meta.error ? 1 : 0),- userCorrections: inboundMessage && detectUserCorrection(inboundMessage) ? 1 : 0,- errorKind,- transientErrorCount: transient,- };- }-private async buildSystemPromptWithEvolution(basePrompt: string): Promise<string> {if (!this.skillStore || !this.config.evolution.enabled) {return basePrompt;diff --git a/src/core-agent/src/evolution/index.ts b/src/core-agent/src/evolution/index.tsindex 113a4f14..c96e655c 100644--- a/src/core-agent/src/evolution/index.ts+++ b/src/core-agent/src/evolution/index.ts@@ -15,5 +15,5 @@ export {detectUserCorrection,emptyRunMetrics,shouldReflect,- buildAdaptiveReviewPrompt,+ buildReviewPrompt,} from "./metacognition.js";diff --git a/src/core-agent/src/evolution/metacognition.ts b/src/core-agent/src/evolution/metacognition.tsindex 78c702cd..34709b0e 100644--- a/src/core-agent/src/evolution/metacognition.ts+++ b/src/core-agent/src/evolution/metacognition.ts@@ -201,103 +201,81 @@ function extractSection(text: string, headingKeywords: string[]): string | nullreturn captured.length > 0 ? captured.join('\n').trim() : null;}-// ── Adaptive review prompt generation ───────────────────────────────────+// ── Review prompt generation ────────────────────────────────────────────/**- * Build a review prompt tailored to the trigger reason, the agent's- * self-assessment, and available learning strategies.+ * Build the reflection LLM prompt for one agent over a recent activity+ * transcript.*- * @param primaryFocus Trigger reason (error_recovery, user_correction, etc.)- * @param competence Current COMPETENCE.md content- * @param strategies Current LEARNING_STRATEGIES.md content- * @param skillHealthReport Optional skill health report- * @param conversationDigest Summary of what happened in the conversation+ * Single open-ended prompt (no `primaryFocus` branching) per+ * `docs/plans/reflection-redesign.md` §2.3 — the LLM reads the transcript+ * and decides what's worth saving. Eliminating the 7-case switch removes+ * a window-aggregation ambiguity (multi-focus runs would need contradictory+ * directives) and keeps the system prompt cache-stable across calls.+ *+ * @param competence Current COMPETENCE.md content (capped 3000 chars by the meta tool)+ * @param strategies Current LEARNING_STRATEGIES.md content (capped 4000 chars)+ * @param transcript Activity transcript from `reflection-transcript.buildTranscript`*/-export function buildAdaptiveReviewPrompt(- primaryFocus: string,+export function buildReviewPrompt(competence: string,strategies: string,- skillHealthReport?: string,- conversationDigest?: string,+ transcript: string,): string {- const base = 'Based on the conversation digest below, consider improving your skills and self-awareness.\n\n'+ const base = 'Based on the activity transcript below, review and update your self-understanding.\n\n'+ '**Important: transient errors (network timeouts, dropped connections, rate limits) are environmental issues, not skill or capability deficits. '+ 'Do not mark them as weaknesses in COMPETENCE.md, do not modify or delete the related skills, '+ 'and do not advise avoiding the tool in LEARNING_STRATEGIES.md.**\n\n';- let focus: string;- switch (primaryFocus) {- case 'error_recovery':- focus = 'You recovered from an error during this task. '- + 'Extract the resolution into a reusable skill, focusing on the non-obvious steps that made recovery succeed.';- break;- case 'user_correction':- focus = 'The user corrected your approach. '- + 'Identify what you got wrong, then create or update a skill that captures the correct way. '- + 'Also update COMPETENCE.md to record this weakness.';- break;- case 'skill_ineffective':- focus = 'A skill you loaded did not help on this task. '- + 'Diagnose why: outdated? too generic? mismatched? '- + 'Patch or delete the ineffective skill.';- break;- case 'known_weakness':- focus = 'This task hit one of your known weaknesses. '- + 'Strengthen this area. If you succeeded, update COMPETENCE.md to reflect the progress.';- break;- case 'weakness_succeeded':- focus = 'A capability you previously flagged as a weakness performed normally on this task. '- + 'Update COMPETENCE.md: remove or downgrade that weakness entry. '- + 'Do not modify or delete the related skills — they are working as expected.';- break;- case 'periodic_review':- focus = 'Some time has passed since the last reflection — do a periodic review. '- + 'Look at COMPETENCE.md and LEARNING_STRATEGIES.md: '- + 'merge similar entries, drop content that no longer applies or is duplicated, '- + 'and distill recently-recurring stable patterns into new skills. '- + 'If there is nothing new worth saving, just say "nothing to save" — do not reflect for the sake of reflecting.';- break;- case 'complexity':- default:- focus = 'This is a complex task. '- + 'Consider whether any approach or pattern is worth saving as a skill.';- break;- }-- const parts = [+ const focus = 'Look at COMPETENCE.md and LEARNING_STRATEGIES.md: '+ + 'merge similar entries, drop content that no longer applies or is duplicated, '+ + 'and distill recently-recurring stable patterns into new skills. '+ + 'Identify user preferences and domain constraints surfaced in this window — '+ + 'red lines the user revealed, edits made to your draft, repeated corrections, '+ + 'workflow preferences. '+ + 'If there is nothing new worth saving, just say "nothing to save" — '+ + 'do not reflect for the sake of reflecting.';++ // Imperative writing guidance — prose injection of COMPETENCE/STRATEGIES+ // into the runtime system prompt is a weak nudge unless entries are written+ // as actionable rules anchored to trigger conditions. Without this section+ // reflection tends to produce vague descriptions ("agent should be careful+ // about X") that the agent reliably ignores. See docs/plans/reflection-redesign.md §9.+ const writingStyle = 'When you update COMPETENCE.md / LEARNING_STRATEGIES.md or '+ + 'author a skill, write actionable imperatives — not descriptions.\n'+ + ' ✗ "Agent should be careful about overly verbose output."\n'+ + ' ✓ "NEVER exceed 5 bullet points in family-office context replies."\n'+ + ' ✗ "User seems to prefer concise output."\n'+ + ' ✓ "WHEN replying to family-office context, ALWAYS lead with the '+ + 'bottom-line answer before rationale."\n'+ + 'Use NEVER / ALWAYS / WHEN-THEN structures with concrete trigger conditions.\n'+ + 'For a new skill\'s `description` field specifically: one imperative line '+ + 'stating WHEN to use the skill, not what it is about (the description is '+ + 'the only thing the next turn\'s agent sees before deciding to load the body).\n'+ + ' ✗ "Q4 earnings analysis skill."\n'+ + ' ✓ "WHEN handling Q4 earnings for utilities, use trailing-4-quarters not annualized."';++ return [base,`**Focus**: ${focus}`,- ];-- if (conversationDigest) {- parts.push(- '',- '**Conversation digest**:',- conversationDigest,- );- }-- parts.push(+ '',+ `**Writing style**: ${writingStyle}`,+ '',+ '**Activity transcript**:',+ transcript || '(No new activity in the window.)','','**Current self-assessment (COMPETENCE.md)**:',competence || '(No self-assessment yet — consider creating one.)','','**Available learning strategies (LEARNING_STRATEGIES.md)**:',strategies || '(No strategy log yet — use your own judgment.)',- );-- if (skillHealthReport) {- parts.push('', '**Skill health report**:', skillHealthReport);- }-- parts.push('','After reflecting, you can:',- '1. Create / patch / delete skills via the skill_manage tool',+ '1. Create / patch / delete skills via the skill_manage tool '+ + '(no user confirmation needed during reflection — the tool\'s default '+ + '"confirm with user" guidance is for live turns, not for this call).','2. Update COMPETENCE.md via the metacognition tool','3. Update LEARNING_STRATEGIES.md via the metacognition tool','4. If nothing is worth saving, just say "nothing to save"',- );-- return parts.join('\n');+ ].join('\n');}diff --git a/src/core-agent/src/index.ts b/src/core-agent/src/index.tsindex bc7b8d74..8f97f46c 100644--- a/src/core-agent/src/index.ts+++ b/src/core-agent/src/index.ts@@ -66,7 +66,7 @@ export {// Evolution (self-improvement)export { SkillStore, createSkillManageTool } from "./evolution/index.js";export type { Skill, SkillSummary, SkillFrontmatter } from "./evolution/index.js";-export { detectUserCorrection, emptyRunMetrics, shouldReflect, buildAdaptiveReviewPrompt } from "./evolution/index.js";+export { detectUserCorrection, emptyRunMetrics, shouldReflect, buildReviewPrompt } from "./evolution/index.js";export type { MetacognitionConfig, RunMetrics, TriggerSignal, MetacognitiveReflection } from "./evolution/index.js";// CLIdiff --git a/src/core-agent/test/evolution.test.ts b/src/core-agent/test/evolution.test.tsindex 1fadafd4..bcacd3b6 100644--- a/src/core-agent/test/evolution.test.ts+++ b/src/core-agent/test/evolution.test.ts@@ -543,74 +543,10 @@ describe("Evolution: AgentRunner integration", () => {expect(runner.getSkillStore()).toBeNull();});- it("evaluateReflection returns null when metacognition is disabled", async () => {- const store = new SkillStore(skillsDir, makeConfig(skillsDir));- await store.init();-- const registry = new ProviderRegistry();- const config = createConfig({- agent: { defaultProvider: "mock", defaultModel: "mock-model" },- evolution: { enabled: true, skillsDir, metacognition: { enabled: false } },- });-- const runner = new AgentRunner({ config, providers: registry, tools: [], skillStore: store });- const result = makeRunResult({ toolLoops: 10 });- expect(runner.evaluateReflection(result)).toBeNull();- });-- it("evaluateReflection returns prompt when metacognition triggers", async () => {- const store = new SkillStore(skillsDir, makeConfig(skillsDir));- await store.init();-- const registry = new ProviderRegistry();- const config = createConfig({- agent: { defaultProvider: "mock", defaultModel: "mock-model" },- evolution: {- enabled: true,- skillsDir,- metacognition: { enabled: true, reflectThreshold: 0.7 },- },- });-- const runner = new AgentRunner({ config, providers: registry, tools: [], skillStore: store });- // Error recovery (weight 0.8) should trigger- const result = makeRunResult({- toolLoops: 3,- error: { kind: "provider_error", message: "temporary" },- toolNames: ["bash"],- skillsLoaded: [],- });- // result.text is non-empty → recovered = true- const evaluation = runner.evaluateReflection(result);- expect(evaluation).not.toBeNull();- expect(evaluation!.primaryFocus).toBe("error_recovery");- // Adaptive review prompt = English head (buildAdaptiveReviewPrompt) +- // English digest body (buildConversationDigest's "Outcome: recovered- // from the error and completed the task") + the user-supplied- // result.text appended verbatim.- expect(evaluation!.prompt).toContain("conversation digest");- expect(evaluation!.prompt).toContain("recovered from the error");- expect(evaluation!.prompt).toContain("Task completed");- });-- it("evaluateReflection returns null for simple runs", async () => {- const store = new SkillStore(skillsDir, makeConfig(skillsDir));- await store.init();-- const registry = new ProviderRegistry();- const config = createConfig({- agent: { defaultProvider: "mock", defaultModel: "mock-model" },- evolution: {- enabled: true,- skillsDir,- metacognition: { enabled: true, reflectThreshold: 0.7 },- },- });-- const runner = new AgentRunner({ config, providers: registry, tools: [], skillStore: store });- const result = makeRunResult({ toolLoops: 2 });- expect(runner.evaluateReflection(result)).toBeNull();- });+ // Per-turn `evaluateReflection` path removed in the reflection redesign+ // (`docs/plans/reflection-redesign.md` §2.4). Reflection now runs only+ // from the orchestrator (`features/reflection-orchestrator.ts`); the+ // runner no longer owns reflection triggering.it("agent can create a skill via tool call", async () => {const mockProvider = createMockProvider([diff --git a/src/core-agent/test/metacognition.test.ts b/src/core-agent/test/metacognition.test.tsindex 97d524c3..44f2485a 100644--- a/src/core-agent/test/metacognition.test.ts+++ b/src/core-agent/test/metacognition.test.ts@@ -3,7 +3,7 @@ import {detectUserCorrection,emptyRunMetrics,shouldReflect,- buildAdaptiveReviewPrompt,+ buildReviewPrompt,} from '../src/evolution/metacognition.js';import type { RunMetrics, MetacognitionConfig } from '../src/evolution/types.js';@@ -287,91 +287,83 @@ describe('shouldReflect', () => {});});-// ── buildAdaptiveReviewPrompt ───────────────────────────────────────────+// ── buildReviewPrompt ───────────────────────────────────────────────────-describe('buildAdaptiveReviewPrompt', () => {- it('builds error_recovery focused prompt', () => {- const prompt = buildAdaptiveReviewPrompt('error_recovery', '', '');- expect(prompt).toContain('recovered from an error');- expect(prompt).toContain('skill_manage');- expect(prompt).toContain('metacognition');+describe('buildReviewPrompt', () => {+ it('renders the transcript section with content when provided', () => {+ const transcript = '## Activity since 2026-05-19 14:00\n\n### c001\n[14:23 user]\nq';+ const prompt = buildReviewPrompt('', '', transcript);+ expect(prompt).toContain('Activity transcript');+ expect(prompt).toContain('14:23 user');});- it('builds user_correction focused prompt', () => {- const prompt = buildAdaptiveReviewPrompt('user_correction', '', '');- expect(prompt).toContain('corrected your approach');- expect(prompt).toContain('COMPETENCE');- });-- it('builds skill_ineffective focused prompt', () => {- const prompt = buildAdaptiveReviewPrompt('skill_ineffective', '', '');- expect(prompt).toContain('did not help');- expect(prompt).toContain('Patch or delete');- });-- it('builds known_weakness focused prompt', () => {- const prompt = buildAdaptiveReviewPrompt('known_weakness', '', '');- expect(prompt).toContain('known weaknesses');- expect(prompt).toContain('Strengthen');- });-- it('builds complexity default prompt', () => {- const prompt = buildAdaptiveReviewPrompt('complexity', '', '');- expect(prompt).toContain('complex task');+ it('shows placeholder when transcript is empty', () => {+ const prompt = buildReviewPrompt('', '', '');+ expect(prompt).toContain('No new activity in the window');});it('includes competence content', () => {- const prompt = buildAdaptiveReviewPrompt('complexity', 'I am strong at Python', '');+ const prompt = buildReviewPrompt('I am strong at Python', '', '');expect(prompt).toContain('I am strong at Python');expect(prompt).not.toContain('No self-assessment yet');});it('shows placeholder when no competence', () => {- const prompt = buildAdaptiveReviewPrompt('complexity', '', '');+ const prompt = buildReviewPrompt('', '', '');expect(prompt).toContain('No self-assessment yet');});it('includes strategies content', () => {- const prompt = buildAdaptiveReviewPrompt('complexity', '', 'Error extraction pattern');+ const prompt = buildReviewPrompt('', 'Error extraction pattern', '');expect(prompt).toContain('Error extraction pattern');expect(prompt).not.toContain('No strategy log yet');});- it('includes skill health report when provided', () => {- const report = '- docker-debug: effectiveness 0.83, healthy';- const prompt = buildAdaptiveReviewPrompt('complexity', '', '', report);- expect(prompt).toContain('Skill health report');- expect(prompt).toContain('docker-debug');+ it('always includes transient-error guidance (preserved invariant)', () => {+ const prompt = buildReviewPrompt('', '', '');+ expect(prompt).toContain('transient errors');+ expect(prompt).toContain('Do not mark them as weaknesses in COMPETENCE.md');});- it('omits skill health section when not provided', () => {- const prompt = buildAdaptiveReviewPrompt('complexity', '', '');- expect(prompt).not.toContain('Skill health report');+ it('always offers the four post-reflection actions', () => {+ const prompt = buildReviewPrompt('', '', '');+ expect(prompt).toContain('skill_manage tool');+ expect(prompt).toContain('metacognition tool');+ expect(prompt).toMatch(/nothing to save/i);});- it('includes conversation digest when provided', () => {- const digest = 'Tools used: bash, read_file\nSkills loaded: docker-debug\n--- final reply ---\nFixed Docker container that failed to start';- const prompt = buildAdaptiveReviewPrompt('error_recovery', '', '', undefined, digest);- expect(prompt).toContain('docker-debug');- expect(prompt).toContain('Docker container');- expect(prompt).toContain('final reply');+ it('directs LLM to look for user preferences + domain constraints', () => {+ const prompt = buildReviewPrompt('', '', '');+ // Plan §2.3: prompt should nudge LLM to extract red lines / edits / etc.+ expect(prompt).toMatch(/user preferences|domain constraints|red lines/i);});- it('omits conversation digest content when not provided', () => {- const prompt = buildAdaptiveReviewPrompt('complexity', '', '');- expect(prompt).not.toContain('final reply');+ it('directs LLM to write imperatives, not descriptions', () => {+ // Plan §9.x: prose injection of COMPETENCE/STRATEGIES is too soft unless+ // entries are written as actionable rules with trigger conditions.+ const prompt = buildReviewPrompt('', '', '');+ expect(prompt).toContain('Writing style');+ // The NEVER / ALWAYS / WHEN-THEN formula is the load-bearing instruction.+ expect(prompt).toMatch(/NEVER\s*\/\s*ALWAYS\s*\/\s*WHEN-THEN/);+ // Concrete bad/good pair is the second load-bearing piece.+ expect(prompt).toMatch(/✗.*✓/s);});- it('builds weakness_succeeded focused prompt', () => {- const prompt = buildAdaptiveReviewPrompt('weakness_succeeded', '', '');- expect(prompt).toContain('performed normally');- expect(prompt).toContain('remove or downgrade');- expect(prompt).toContain('Do not modify or delete the related skills');+ it('overrides skill_manage tool\'s "confirm with user" default for reflection', () => {+ // skill_manage tool description says "Confirm with user before creating+ // or deleting" — written for live turns. Without an explicit override+ // here, reflection LLM gets inhibited and never creates skills. See+ // reflection-redesign plan: skill-creation soft pitfall 1.+ const prompt = buildReviewPrompt('', '', '');+ expect(prompt).toMatch(/no user confirmation needed|does NOT need user confirmation/i);});- it('includes transient error guidance in all prompts', () => {- const prompt = buildAdaptiveReviewPrompt('complexity', '', '');- expect(prompt).toContain('transient errors');- expect(prompt).toContain('Do not mark them as weaknesses in COMPETENCE.md');+ it('extends Writing style guidance to the skill description field', () => {+ // The description field is the ONLY thing the next-turn agent sees+ // before deciding to load a skill — vague descriptions make the skill+ // effectively dead. Soft pitfall 2 in reflection-redesign plan.+ const prompt = buildReviewPrompt('', '', '');+ expect(prompt).toMatch(/description.*field|`description`/i);+ expect(prompt).toMatch(/WHEN to use/i);});});diff --git a/src/main/features/agents.ts b/src/main/features/agents.tsindex a60ee08a..094fe524 100644--- a/src/main/features/agents.ts+++ b/src/main/features/agents.ts@@ -1,9 +1,9 @@/**- * Agents — listing, custom CRUD, builtin sync, inline edit chat.+ * Agents — listing, custom CRUD, marketplace installs, inline edit chat.** Mirrors the skills module shape. Two sources:- * builtin — data/shared/agents/builtin/<id>.json (synced from PC/builtin/agents/)- * custom — data/shared/agents/custom/<id>.json (user-created, editable)+ * marketplace — <uid>/local/marketplace/agents/<id>/agent.json+ * custom — <uid>/cloud/agents/<id>/agent.json** Schema (one JSON per agent):* { agent_id, name, description, workflow, created_at, updated_at }@@ -60,7 +60,8 @@ import {normalizeMarketplaceCategoryCode,} from './marketplace_biz';-export type AgentSource = 'builtin' | 'custom';+export type AgentSource = 'marketplace' | 'custom';+type AgentSourceInput = AgentSource | 'builtin';export type AgentInputType = 'text' | 'textarea' | 'select' | 'multiselect' | 'number' | 'boolean' | 'file' | 'directory';@@ -179,7 +180,7 @@ export interface Agent {/** Marketplace author uid. Kept optional for install/reconcile compatibility; global UI* surfaces must not render it. */create_uid?: string;- /** Marketplace install version for `source==='builtin'`. Read from `_install.json` so the+ /** Marketplace install version for `source==='marketplace'`. Read from `_install.json` so the* agents-tab card can render a `v1.0.0` chip alongside the category. Custom agents leave* this undefined (version is a publish concept, not authored locally). */version?: string;@@ -244,21 +245,25 @@ export interface AgentChatMeta { session_id?: string; [k: string]: unknown }// 1. Builtin agent sync (startup)// ─────────────────────────────────────────────────────────────────────────-// `syncBuiltinAgents` / `hashTree` / `_isMarketplaceInstalled` removed — there is no longer a-// shipped-builtin tree to sync from (`PC/src/builtin/` is gone) or a sentinel to protect (the-// install flow now writes to `<uid>/local/marketplace/agents/` directly, distinct from the-// scrubbed builtin path that no longer exists). Source='builtin' still names the UI group-// ("Platform"); on disk it resolves to `userMarketplaceAgentsDir(uid)`.+// `syncBuiltinAgents` / `hashTree` / `_isMarketplaceInstalled` removed — marketplace installs+// now write to `<uid>/local/marketplace/agents/` directly.// ─────────────────────────────────────────────────────────────────────────// 2. Read / list// ─────────────────────────────────────────────────────────────────────────-/** Resolve where a given source's agents live on disk. Source='builtin' is a legacy name- * preserved across the codebase; it now points at the per-user marketplace install dir. */-function agentBaseDir(source: AgentSource): string {+function normalizeAgentSource(source: AgentSourceInput): AgentSource {+ return source === 'builtin' ? 'marketplace' : source;+}++function isMarketplaceSource(source: AgentSourceInput): boolean {+ return normalizeAgentSource(source) === 'marketplace';+}++/** Resolve where a given source's agents live on disk. */+function agentBaseDir(source: AgentSourceInput): string {const uid = getActiveUserId();- return source === 'builtin' ? userMarketplaceAgentsDir(uid) : userAgentsDir(uid);+ return isMarketplaceSource(source) ? userMarketplaceAgentsDir(uid) : userAgentsDir(uid);}/** Helpers replacing the removed `builtinAgentDir` / `builtinAgentDefinitionFile`.@@ -340,7 +345,7 @@ function assertAgentNameCharsetValid(name: string): void {}}-/** Reject names already in use by another agent (custom OR builtin).+/** Reject names already in use by another agent (custom OR marketplace).* Matches `_agentNameKey` (case-insensitive, all whitespace stripped) so* "Code Helper" and "codehelper" collide. `excludeAgentId` lets the* update path keep its own name. Caller owns the check at every write@@ -479,7 +484,7 @@ export function validateAgentInputs(raw: unknown): AgentInput[] {return out;}-export function normalizeAgent(raw: AgentRaw | null | undefined, source: AgentSource): Agent | null {+export function normalizeAgent(raw: AgentRaw | null | undefined, source: AgentSourceInput): Agent | null {if (!raw || typeof raw !== 'object' || !raw.agent_id) return null;// Migrate legacy single-`description` into the matching language slot.// Same Chinese-character heuristic as the skill loader; explicit > legacy.@@ -494,7 +499,7 @@ export function normalizeAgent(raw: AgentRaw | null | undefined, source: AgentSodescription_en: explicitEn || (legacyDesc && !legacyHasChinese ? legacyDesc : ''),workflow: typeof raw.workflow === 'string' ? raw.workflow : '',category: typeof raw.category === 'string' ? raw.category : '',- source,+ source: normalizeAgentSource(source),created_at: raw.created_at || '',updated_at: raw.updated_at || '',// Defaults to enabled; overlaid by listAgents / getAgent from the@@ -784,7 +789,7 @@ export async function listAgents(): Promise<Agent[]> {} else {specs = [];const seen = new Set<string>();- const sources: Array<[AgentSource, string]> = [['custom', CUSTOM_AGENTS_DIR()], ['builtin', userMarketplaceAgentsDir(getActiveUserId())]];+ const sources: Array<[AgentSource, string]> = [['custom', CUSTOM_AGENTS_DIR()], ['marketplace', userMarketplaceAgentsDir(getActiveUserId())]];for (const [source, dir] of sources) {if (!fs.existsSync(dir)) continue;const entries = (await fsp.readdir(dir, { withFileTypes: true }))@@ -798,8 +803,8 @@ export async function listAgents(): Promise<Agent[]> {const norm = normalizeAgent(data, source);if (!norm) continue;if (seen.has(norm.agent_id)) {- if (source === 'builtin') {- log.warn(`id conflict: custom and builtin both define "${norm.agent_id}" — custom wins, rename one`);+ if (isMarketplaceSource(source)) {+ log.warn(`id conflict: custom and marketplace both define "${norm.agent_id}" — custom wins, rename one`);}continue;}@@ -807,7 +812,7 @@ export async function listAgents(): Promise<Agent[]> {// Marketplace-installed agents carry an `_install.json` sidecar with `version`.// Author uid may also be present there for install/reconcile compatibility, but the// global UI intentionally does not surface it.- if (source === 'builtin') {+ if (isMarketplaceSource(source)) {try {const metaFile = path.join(dir, e.name, '_install.json');if (fs.existsSync(metaFile)) {@@ -837,8 +842,8 @@ export async function listAgents(): Promise<Agent[]> {*/export async function getAgent(agentId: string | null | undefined): Promise<Agent | null> {if (!agentId) return null;- for (const source of ['custom', 'builtin'] as AgentSource[]) {- const f = source === 'builtin'+ for (const source of ['custom', 'marketplace'] as AgentSource[]) {+ const f = isMarketplaceSource(source)? _platformAgentSpecFile(agentId): agentDefinitionFile(getActiveUserId(), agentId);if (!fs.existsSync(f)) continue;@@ -1357,6 +1362,7 @@ export async function _applyAgentUpdatesAndInvalidate(catch (err) { log.warn(`rename roster sweep failed id=${agentId}: ${(err as Error).message}`); }}return normalizeAgent(data, 'custom');+ return normalizeAgent(data, 'marketplace');}/**@@ -1704,6 +1710,8 @@ export function buildAgentEditSystemPrompt(agent: {interactive: agent.interactive === true ? 'true' : 'false',});return `${body}\n\n---\n\n${buildLanguageDirective()}`;+ const tail = buildLanguageDirective();+ return `${body}\n\n---\n\n${tail}`;}export interface AgentEditResult {diff --git a/src/main/features/chat_attachments.ts b/src/main/features/chat_attachments.tsindex 0038ad49..8eeb767c 100644--- a/src/main/features/chat_attachments.ts+++ b/src/main/features/chat_attachments.ts@@ -35,6 +35,7 @@import * as fs from 'node:fs';import * as path from 'node:path';+import * as crypto from 'node:crypto';import { chatAttachmentDir, userChatAttachmentsDir, userChatsDir } from '../paths';import { createLogger } from '../logger';@@ -146,6 +147,85 @@ function uniqueTarget(dir: string, name: string): string {return path.join(dir, `${stem}-${stamp}${ext}`);}+const attachmentWriteLocks = new Map<string, Promise<void>>();++async function withAttachmentWriteLock<T>(+ userId: string,+ cid: string,+ fn: () => Promise<T> | T,+): Promise<T> {+ const key = JSON.stringify([userId, cid]);+ const prev = attachmentWriteLocks.get(key) || Promise.resolve();+ let release!: () => void;+ const current = new Promise<void>((resolve) => { release = resolve; });+ attachmentWriteLocks.set(key, current);+ try {+ await prev;+ return await fn();+ } finally {+ release();+ if (attachmentWriteLocks.get(key) === current) {+ attachmentWriteLocks.delete(key);+ }+ }+}++function attachmentInfoForPath(absPath: string, name = path.basename(absPath)): AttachmentInfo | null {+ const ext = path.extname(name).toLowerCase();+ if (!ALLOWED_EXTENSIONS.has(ext)) return null;+ let st: fs.Stats;+ try { st = fs.statSync(absPath); }+ catch { return null; }+ if (!st.isFile()) return null;+ return {+ name,+ bytes: st.size,+ kind: kindOf(ext),+ mtime: Math.floor(st.mtimeMs / 1000),+ };+}++function hashBuffer(buf: Buffer): string {+ return crypto.createHash('sha256').update(buf).digest('hex');+}++function hashFile(absPath: string): Promise<string> {+ return new Promise((resolve, reject) => {+ const h = crypto.createHash('sha256');+ const s = fs.createReadStream(absPath);+ s.on('data', (chunk) => h.update(chunk));+ s.on('error', reject);+ s.on('end', () => resolve(h.digest('hex')));+ });+}++async function findDuplicateByHash(+ dir: string,+ bytes: number,+ sha256: string,+): Promise<AttachmentInfo | null> {+ let items: fs.Dirent[];+ try { items = fs.readdirSync(dir, { withFileTypes: true }); }+ catch { return null; }+ items.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));+ for (const e of items) {+ if (!e.isFile() || e.name.startsWith('.')) continue;+ const ext = path.extname(e.name).toLowerCase();+ if (!ALLOWED_EXTENSIONS.has(ext)) continue;+ const abs = path.join(dir, e.name);+ let st: fs.Stats;+ try { st = fs.statSync(abs); }+ catch { continue; }+ if (st.size !== bytes) continue;+ try {+ if (await hashFile(abs) === sha256) {+ return attachmentInfoForPath(abs, e.name);+ }+ } catch { /* skip unreadable */ }+ }+ return null;+}+// ── Public API ───────────────────────────────────────────────────────────export async function uploadAttachment(@@ -153,7 +233,7 @@ export async function uploadAttachment(cid: string,name: string,raw: Buffer | Uint8Array | null | undefined,-): Promise<Result<{ info: AttachmentInfo }>> {+): Promise<Result<{ info: AttachmentInfo; reused?: boolean }>> {let safeName: string;let safeConvId: string;try {@@ -175,36 +255,115 @@ export async function uploadAttachment(}const dir = ensureDir(userId, safeConvId);- const target = uniqueTarget(dir, safeName);- const finalName = path.basename(target);- try { fs.writeFileSync(target, buf); }- catch (err) {- // Roll back the mkdir from `ensureDir` if the directory ended up empty- // (i.e., this was the first attachment for the cid and the write failed- // before producing anything). Best-effort: a non-empty dir means a- // previous successful upload owns it and must not be touched.- try {- if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);- } catch { /* best-effort */ }- return { ok: false, error: (err as Error).message };+ const incomingHash = hashBuffer(buf);+ return withAttachmentWriteLock(userId, safeConvId, async () => {+ const duplicate = await findDuplicateByHash(dir, buf.length, incomingHash);+ if (duplicate) {+ log.info(`upload dedupe user=${userId} cid=${safeConvId} reuse=${duplicate.name} bytes=${duplicate.bytes}`);+ return { ok: true, info: duplicate, reused: true };+ }++ const target = uniqueTarget(dir, safeName);+ const finalName = path.basename(target);+ try { fs.writeFileSync(target, buf); }+ catch (err) {+ // Roll back the mkdir from `ensureDir` if the directory ended up empty+ // (i.e., this was the first attachment for the cid and the write failed+ // before producing anything). Best-effort: a non-empty dir means a+ // previous successful upload owns it and must not be touched.+ try {+ if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);+ } catch { /* best-effort */ }+ return { ok: false, error: (err as Error).message };+ }++ // No upload-time preprocessing: extract / grayscale happen lazily in+ // features/file_indexer when the model's tools first touch this file.+ // Video is display-only and never preprocessed.++ const st = fs.statSync(target);+ const kind = kindOf(ext);+ log.info(`upload user=${userId} cid=${safeConvId} name=${finalName} kind=${kind} bytes=${st.size}`);+ return {+ ok: true,+ info: {+ name: finalName,+ bytes: st.size,+ kind,+ mtime: Math.floor(st.mtimeMs / 1000),+ },+ };+ });+}++export async function importAttachmentFromPath(+ userId: string,+ cid: string,+ sourcePath: string,+ name?: string,+): Promise<Result<{ info: AttachmentInfo; reused?: boolean }>> {+ let safeName: string;+ let safeConvId: string;+ try {+ safeName = safeAttachmentName(name || path.basename(sourcePath || ''));+ safeConvId = safeCid(cid);+ } catch (err) { return { ok: false, error: (err as Error).message }; }++ const absSource = path.resolve(String(sourcePath || ''));+ let sourceStat: fs.Stats;+ try { sourceStat = fs.statSync(absSource); }+ catch { return { ok: false, error: 'file not found' }; }+ if (!sourceStat.isFile()) return { ok: false, error: 'file not found' };++ const ext = path.extname(safeName).toLowerCase();+ const cap = maxBytesFor(ext);+ if (sourceStat.size > cap) {+ return { ok: false, error: t('errors.file_too_large_mb', { mb: Math.round(cap / 1024 / 1024) }) };+ }+ if (TEXT_EXTS.has(ext)) {+ let buf: Buffer;+ try { buf = fs.readFileSync(absSource); }+ catch (err) { return { ok: false, error: (err as Error).message }; }+ const s = buf.toString('utf8');+ if (Buffer.from(s, 'utf8').length !== buf.length) {+ return { ok: false, error: t('errors.not_utf8') };+ }}- // No upload-time preprocessing: extract / grayscale happen lazily in- // features/file_indexer when the model's tools first touch this file.- // Video is display-only and never preprocessed.+ const dir = ensureDir(userId, safeConvId);+ let incomingHash: string;+ try { incomingHash = await hashFile(absSource); }+ catch (err) { return { ok: false, error: (err as Error).message }; }+ return withAttachmentWriteLock(userId, safeConvId, async () => {+ const duplicate = await findDuplicateByHash(dir, sourceStat.size, incomingHash);+ if (duplicate) {+ log.info(`import dedupe user=${userId} cid=${safeConvId} reuse=${duplicate.name} bytes=${duplicate.bytes}`);+ return { ok: true, info: duplicate, reused: true };+ }- const st = fs.statSync(target);- const kind = kindOf(ext);- log.info(`upload user=${userId} cid=${safeConvId} name=${finalName} kind=${kind} bytes=${st.size}`);- return {- ok: true,- info: {- name: finalName,- bytes: st.size,- kind,- mtime: Math.floor(st.mtimeMs / 1000),- },- };+ const target = uniqueTarget(dir, safeName);+ const finalName = path.basename(target);+ try { fs.copyFileSync(absSource, target); }+ catch (err) {+ try {+ if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);+ } catch { /* best-effort */ }+ return { ok: false, error: (err as Error).message };+ }++ const st = fs.statSync(target);+ const kind = kindOf(ext);+ log.info(`import user=${userId} cid=${safeConvId} name=${finalName} kind=${kind} bytes=${st.size}`);+ return {+ ok: true,+ info: {+ name: finalName,+ bytes: st.size,+ kind,+ mtime: Math.floor(st.mtimeMs / 1000),+ },+ };+ });}export function listAttachments(userId: string, cid: string): AttachmentInfo[] {diff --git a/src/main/features/chats.ts b/src/main/features/chats.tsindex 0ce6a522..26e0f1ea 100644--- a/src/main/features/chats.ts+++ b/src/main/features/chats.ts@@ -28,6 +28,9 @@ import {} from '../storage';import { createLogger } from '../logger';import { t } from '../i18n';+import {+ ZH_FILLER_RE, EN_FILLER_RE, CLAUSE_RE, TITLE_MAX,+} from '../util/auto-title';const log = createLogger('chats');import * as search from './search';@@ -115,7 +118,14 @@ export async function listConversations(userId: string): Promise<Conversation[]>let since: string | null = null;try {const s = await readState(userId, c.conversation_id);- const bus = await import('./group_chat/bus');+ // CJS require (not dynamic import) so bus.ts resolves through the same+ // module cache as the static-import chain. Node's dynamic `import()` is+ // always ESM, which would load bus.ts as a SECOND module instance with+ // its own _cids Map — splitting the bus state into two and silently+ // losing every event that's emitted on the wrong half (see bus.ts comment+ // at planExecutor.bindBusHooks for why ESM-vs-CJS duplication corrupts+ // plan_executor's hooks).+ const bus = require('./group_chat/bus') as typeof import('./group_chat/bus');const busBusy = !bus.isQuiescent(userId, c.conversation_id);processing = s.status === 'running' || busBusy;since = processing ? s.last_active_at : null;@@ -277,8 +287,11 @@ export async function deleteConversation(userId: string, cid: string): Promise<bawait saveConversations(userId, kept);// Purge group dir (members.json / state.json / plan.md / visibility/) + bus state.+ // CJS require (same reason as listConversations above) — dynamic `import()`+ // would load bus.ts as a second ESM module and dropConv would clear the+ // wrong _cids.try {- const bus = await import('./group_chat/bus');+ const bus = require('./group_chat/bus') as typeof import('./group_chat/bus');bus.dropConv(userId, cid);await purgeGroupDir(userId, cid);}@@ -394,10 +407,7 @@ export async function deleteConversationsByAgent(agentId: string): Promise<numbe// doesn't match a shorter prefix when a longer one is also valid. Single-// character fillers (e.g. bare `请`) are intentionally NOT listed — too// likely to clip real content like `请教...`.-const ZH_FILLER_RE = /^(帮我看一下|可不可以|帮我看下|帮我看看|麻烦你|帮我看|我想要|想问问|能不能|可以不|可以吗|请帮我|看一下|麻烦|帮我|我想|想问|请问|看下|看看)\s*/;-const EN_FILLER_RE = /^(could you|would you|can you|help me|i'?d like to|i want to|please)\s+/i;-const CLAUSE_RE = /[,。?!;;,.?!]/;-const TITLE_MAX = 30;+// Heuristic auto-title regex/constants — see top-of-file import.export function autoTitle(content: string): string {const raw = (content || '').trim().replace(/\s+/g, ' ');diff --git a/src/main/features/connectors/catalog-google.ts b/src/main/features/connectors/catalog-google.tsindex e919cfce..cc964ad7 100644--- a/src/main/features/connectors/catalog-google.ts+++ b/src/main/features/connectors/catalog-google.ts@@ -1,9 +1,8 @@/**- * Google Workspace catalog entries — extracted from `catalog.ts` so they can be stripped- * from the OrkasOpen build (Google requires Workspace Developer Preview Program enrollment- * + production CASA verification, which the OSS distribution can't satisfy). PC builds- * include this file via a try/require in `catalog.ts`; OrkasOpen ships without it (see- * `OpenSource/SyncCode/strip-rules.json` `forbidden_files`).+ * Google Workspace catalog entries — extracted from `catalog.ts` so the Google bundle and+ * per-service connectors stay isolated while still syncing to OrkasOpen. Both PC and OrkasOpen+ * include this file via a try/require in `catalog.ts`; the catch path only keeps older open-source+ * checkouts without this file from crashing.** Includes:* - `google-workspace` (one independent all-in-one connector backed bydiff --git a/src/main/features/connectors/catalog.ts b/src/main/features/connectors/catalog.tsindex d59c335a..eddc0735 100644--- a/src/main/features/connectors/catalog.ts+++ b/src/main/features/connectors/catalog.ts@@ -74,18 +74,15 @@ export const CONNECTOR_CATALOG: CatalogEntry[] = [},},// Google Workspace entries (`google-workspace` bundle + 5 service members) live in- // `catalog-google.ts` and are loaded via `_loadGoogleEntries` below — that file is- // **stripped from the OrkasOpen build** because Google's production OAuth verification +- // CASA assessment can't be satisfied for an OSS distribution (see- // `OpenSource/SyncCode/strip-rules.json` `forbidden_files`). PC ships them; OrkasOpen- // silently omits them (require throws → empty array).+ // `catalog-google.ts` and are loaded via `_loadGoogleEntries` below. PC and OrkasOpen both+ // ship them; the try/require keeps older OrkasOpen checkouts that lack the file from crashing...._loadGoogleEntries(),];function _loadGoogleEntries(): CatalogEntry[] {try {- // `require` (not `import`) so the path isn't statically resolved at bundle time. In the- // OrkasOpen build the file is absent and the require throws — we swallow + return [].+ // `require` (not `import`) so the path isn't statically resolved at bundle time. Older+ // OrkasOpen builds may lack this file; swallow and return [] for that compatibility case.// eslint-disable-next-line @typescript-eslint/no-require-imports, global-requireconst mod = require('./catalog-google') as { GOOGLE_ENTRIES?: CatalogEntry[] };return Array.isArray(mod.GOOGLE_ENTRIES) ? mod.GOOGLE_ENTRIES : [];diff --git a/src/main/features/connectors/tools-adapter.ts b/src/main/features/connectors/tools-adapter.tsindex d5738f97..b3e1bce8 100644--- a/src/main/features/connectors/tools-adapter.ts+++ b/src/main/features/connectors/tools-adapter.ts@@ -112,34 +112,38 @@ const GOOGLE_SERVICE_BY_CONNECTOR_ID: Record<string, GoogleWorkspaceService> = {gtasks: 'gtasks',};-const GOOGLE_WORKSPACE_TOOL_PREFIX_BY_SERVICE: Record<GoogleWorkspaceService, string> = {- gmail: '[Gmail]',- gcal: '[Calendar]',- gdocs: '[Docs]',- gsheets: '[Sheets]',- gtasks: '[Tasks]',-};-function _dedupeGoogleWorkspaceTools(visible: Array<{ instance: ConnectorInstance; tools: ToolSchema[] }>,): Array<{ instance: ConnectorInstance; tools: ToolSchema[] }> {const workspace = visible.find((v) => v.instance.id === GOOGLE_WORKSPACE_ID);if (!workspace) return visible;- const shadowedPrefixes = new Set<string>();- for (const { instance } of visible) {- const service = GOOGLE_SERVICE_BY_CONNECTOR_ID[instance.id];- if (!service) continue;- shadowedPrefixes.add(GOOGLE_WORKSPACE_TOOL_PREFIX_BY_SERVICE[service]);+ // Collect tool names from every visible single-Google-service connector.+ // `bin/google-workspace-mcp-server.cjs` wraps the same five service+ // adapters the standalone connectors use, preserving each adapter's+ // original tool `name` and only adding a `[Gmail]` / `[Calendar]` / …+ // prefix to the `description`. So `name` is the strict equality+ // invariant — a service tool advertised under standalone `gmail`+ // shares its name byte-for-byte with the workspace's wrapped copy.+ // Matching by name is robust to a future UI polish that drops the+ // description prefix (which would silently break the prior+ // description-prefix dedup and re-expose both Gmail routes to the+ // model — the 20–50 tool-selection-accuracy cliff anti-pattern that+ // PC/CLAUDE.md §6.5 warns against).+ const shadowedNames = new Set<string>();+ for (const { instance, tools } of visible) {+ if (instance.id === GOOGLE_WORKSPACE_ID) continue;+ if (!GOOGLE_SERVICE_BY_CONNECTOR_ID[instance.id]) continue;+ for (const t of tools) shadowedNames.add(t.name);}- if (!shadowedPrefixes.size) return visible;+ if (!shadowedNames.size) return visible;return visible.map((v) => {if (v.instance.id !== GOOGLE_WORKSPACE_ID) return v;return {instance: v.instance,- tools: v.tools.filter((t) => !_hasShadowedWorkspacePrefix(t, shadowedPrefixes)),+ tools: v.tools.filter((t) => !shadowedNames.has(t.name)),};})// When all five single-service connectors are visible, the Workspace connector has no unique@@ -147,10 +151,5 @@ function _dedupeGoogleWorkspaceTools(.filter((v) => v.instance.id !== GOOGLE_WORKSPACE_ID || v.tools.length > 0);}-function _hasShadowedWorkspacePrefix(tool: ToolSchema, shadowedPrefixes: Set<string>): boolean {- const desc = typeof tool.description === 'string' ? tool.description.trimStart() : '';- for (const prefix of shadowedPrefixes) {- if (desc.startsWith(prefix)) return true;- }- return false;-}+/** Test-only export — see `test/main/features/connectors/dedupe-google-workspace.test.ts`. */+export const _dedupeGoogleWorkspaceToolsForTest = _dedupeGoogleWorkspaceTools;diff --git a/src/main/features/conversation_files.ts b/src/main/features/conversation_files.tsnew file mode 100644index 00000000..a8dd8cd2--- /dev/null+++ b/src/main/features/conversation_files.ts@@ -0,0 +1,101 @@+/**+ * Conversation workspace file listing for the info side panel.+ *+ * The chat history only records files that passed through chip-producing+ * tools (`write_file`, `edit_file`, PDF/image generators). Real runs often+ * create batches through `bash` or CLI agents, so the panel needs a cheap+ * disk snapshot of the conversation workspace as the source of truth.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++export interface ConversationWorkspaceFile {+ path: string;+ relPath: string;+ name: string;+ bytes: number;+ mtime: number;+}++export interface ConversationWorkspaceFileList {+ root: string;+ items: ConversationWorkspaceFile[];+ count: number;+ truncated: boolean;+ rootExists: boolean;+}++const DEFAULT_MAX_FILES = 5000;+const DEFAULT_MAX_DEPTH = 12;++function toPosixRel(rel: string): string {+ return rel.split(path.sep).filter(Boolean).join('/');+}++export function listWorkspaceFiles(+ root: string,+ opts: { maxFiles?: number; maxDepth?: number } = {},+): ConversationWorkspaceFileList {+ const rootAbs = path.resolve(root || '');+ const maxFiles = Math.max(1, Math.floor(opts.maxFiles ?? DEFAULT_MAX_FILES));+ const maxDepth = Math.max(0, Math.floor(opts.maxDepth ?? DEFAULT_MAX_DEPTH));+ const items: ConversationWorkspaceFile[] = [];+ let truncated = false;++ let rootStat: fs.Stats;+ try { rootStat = fs.statSync(rootAbs); }+ catch {+ return { root: rootAbs, items, count: 0, truncated: false, rootExists: false };+ }+ if (!rootStat.isDirectory()) {+ return { root: rootAbs, items, count: 0, truncated: false, rootExists: false };+ }++ const walk = (dir: string, depth: number): void => {+ if (items.length >= maxFiles) {+ truncated = true;+ return;+ }+ if (depth > maxDepth) {+ truncated = true;+ return;+ }++ let entries: fs.Dirent[];+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }+ catch { return; }+ entries.sort((a, b) => a.name.localeCompare(b.name));++ for (const e of entries) {+ if (e.name.startsWith('.')) continue;+ const abs = path.join(dir, e.name);+ if (e.isSymbolicLink()) continue;+ if (e.isDirectory()) {+ walk(abs, depth + 1);+ if (items.length >= maxFiles) {+ truncated = true;+ return;+ }+ } else if (e.isFile()) {+ let st: fs.Stats;+ try { st = fs.statSync(abs); }+ catch { continue; }+ items.push({+ path: abs,+ relPath: toPosixRel(path.relative(rootAbs, abs)),+ name: e.name,+ bytes: st.size,+ mtime: Math.floor(st.mtimeMs),+ });+ if (items.length >= maxFiles) {+ truncated = true;+ return;+ }+ }+ }+ };++ walk(rootAbs, 0);+ return { root: rootAbs, items, count: items.length, truncated, rootExists: true };+}diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.tsindex 79bcb962..bf19a164 100644--- a/src/main/features/group_chat/bus.ts+++ b/src/main/features/group_chat/bus.ts@@ -47,9 +47,10 @@ import {import * as planExecutor from './plan_executor';import {userChatsDir, userSkillsDir, userAgentsDir,- userMarketplaceSkillsDir, userMarketplaceAgentsDir,+ userMarketplaceSkillsDir, userMarketplaceAgentsDir, projectFilesDir,} from '../../paths';import * as agentsFeat from '../agents';+import { isDevEnv } from '../devtools';import { isAgentEnabled } from '../component_enabled';import { buildLanguageDirective, descriptionLang, t } from '../../i18n';import * as marketplaceFeat from '../marketplace';@@ -923,6 +924,10 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promislog.warn(`resolve project scope cid=${cid} pid=${turnProjectId}: ${(err as Error).message}`);}}+ const turnProjectFilesRoot = turnProjectId ? projectFilesDir(uid, turnProjectId) : '';+ const turnProjectFilesSystemBlock = turnProjectId+ ? await buildProjectFilesSystemBlock(uid, cid, turnProjectId)+ : '';// First-turn replay: if the persistent session jsonl doesn't exist yet,// prepend a `<group-chat-history>` block built from the visibility slice@@ -941,13 +946,14 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promislog.warn(`replay-prefix build failed cid=${cid} actor=${actor.id}: ${(err as Error).message}`);}- // Attach a `<attachments>` manifest block listing user-uploaded files- // (text / pdf / docx / image with absolute paths + kinds). Commander uses- // it to route work; agent uses it to extract values for `inputs_schema`- // (especially `type=file` fields). Image bytes ride alongside via- // ChatOptions.images so the vision model sees them on the same user turn- // — the manifest entry carries `attached="inline"` so the LLM doesn't- // waste a read_file round-trip re-fetching what it already has.+ // Attach a `<attachments>` manifest block listing files uploaded on this+ // user turn (text / pdf / docx / image with absolute paths + kinds).+ // Project files are shared conversation context, so they live in the+ // system prompt's runtime injection block instead of being prepended to+ // the user message. Image bytes ride alongside via ChatOptions.images so+ // the vision model sees them on the same user turn — the manifest entry+ // carries `attached="inline"` so the LLM doesn't waste a read_file+ // round-trip re-fetching what it already has.let turnImages: Array<{ data: string; mediaType: 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' }> = [];if (item.attachments && item.attachments.length) {try {@@ -969,7 +975,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis// Hoisted here so the branch below can read it without re-fetching.let cliAgent: import('../agents').Agent | null = null;if (isCommander) {- systemPrompt = await buildCommanderSystemPrompt(uid, cid, turnProjectScope?.agents ?? null);+ systemPrompt = await buildCommanderSystemPrompt(uid, cid, turnProjectScope?.agents ?? null, turnProjectFilesSystemBlock);extraTools = await buildCommanderExtraTools(state, w, item.attachments);// skillList stays undefined for commander — every skill is globally// visible (skills are NOT project-scoped this round; see CLAUDE.md §6).@@ -1004,7 +1010,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): PromiscliAgent = agent;systemPrompt = ''; // unused on CLI path} else {- systemPrompt = await buildAgentInGroupSystemPrompt(uid, agent, workingDir);+ systemPrompt = await buildAgentInGroupSystemPrompt(uid, agent, workingDir, turnProjectFilesSystemBlock);// Pass agent.skill_list verbatim — it carries System A + System B// ids the agent owns. Skills are NOT project-scoped this round// (see CLAUDE.md §6); the runner's `projectAllowedSkillIds` hook is@@ -1194,7 +1200,11 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): PromisonSkillInvoked: (id, sys, trig) => skillBuffer.recordInvoked(id, sys, trig),cacheRetention: 'short',abortSignal: w.abortController.signal,- readOnlyExtraRoots: [...skillRoots, ...agentRoots],+ readOnlyExtraRoots: [+ ...(turnProjectFilesRoot ? [turnProjectFilesRoot] : []),+ ...skillRoots,+ ...agentRoots,+ ],...(turnImages.length ? { images: turnImages } : {}),...(extraTools.length ? { extraTools } : {}),...(skillList !== undefined ? { skillList } : {}),@@ -1306,12 +1316,19 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promisconst target = await agentsFeat.getAgent(editId);if (!target) {workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Agent edit failed: agent not found (id=${editId}).</span>`;- } else if (target.source !== 'custom') {- workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Built-in agents can't be edited from the main chat; fork one in the right-hand detail panel and edit there.</span>`;+ } else if (target.source !== 'custom' && !false) {+ workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Marketplace agents can't be edited from the main chat; fork one in the right-hand detail panel and edit there.</span>`;} else if (agentsFeat.isCliAgent(target)) {workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ External agents can only be edited from the right-hand detail panel.</span>`;} else {- const updated = await agentsFeat.updateCustomAgent(editId, fields);+ // `updateAgentSpec` dispatches: custom → updateCustomAgent,+ // marketplace + dev → agents_dev.updateBuiltinAgentSpec+ // (which writes the local marketplace install dir). The+ // dev-env source guard above is what makes the marketplace+ // branch reachable; the direct `updateCustomAgent` call this+ // replaces would short-circuit to null because the custom+ // agent.json doesn't exist for marketplace ids.+ const updated = await agentsFeat.updateAgentSpec(editId, fields);if (updated) {createdAgents.push({ agent_id: updated.agent_id, name: updated.name, kind: 'updated' });} else {@@ -1694,7 +1711,10 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis// ── System prompts ───────────────────────────────────────────────────────async function buildCommanderSystemPrompt(- uid: string, cid: string, allowedAgentIds?: readonly string[] | null,+ uid: string,+ cid: string,+ allowedAgentIds?: readonly string[] | null,+ projectFilesBlock = '',): Promise<string> {const { prompts } = await import('../../prompts/loader');const path_ = await import('node:path');@@ -1726,11 +1746,24 @@ async function buildCommanderSystemPrompt(os: process.platform === 'darwin' ? 'macOS' : process.platform === 'win32' ? 'Windows' : process.platform,working_dir: workingDir,local_exec_state: permState,+ project_files_block: projectFilesBlock,});const shared = prompts.load('chat_shared_rules', {});return appendLanguageDirective(concatSharedRules(main, shared));}+async function buildProjectFilesSystemBlock(uid: string, cid: string, projectId: string): Promise<string> {+ try {+ const projectFileFeature = await import('../project_files');+ const manifest = await projectFileFeature.buildProjectFilesManifest(uid, projectId);+ if (!manifest) return '';+ return `### Project files\n\n${manifest}`;+ } catch (err) {+ log.warn(`project files system block failed cid=${cid} pid=${projectId}: ${(err as Error).message}`);+ return '';+ }+}+/** Merge shared_rules into the per-role prompt. The shared block carries* PDF / search / file-output rules that BOTH commander and agent need;* duplicating them in two .md files would drift. We append them right@@ -1756,9 +1789,9 @@ function appendLanguageDirective(prompt: string): string {// Format:// `\`read_file(<ROOT>/<id>/agent.json)\` — ROOT by Source:\n` +// `- custom: <abs path>\n` +-// `- builtin: <abs path>\n` ++// `- marketplace: <abs path>\n` +// `Use these ROOT values verbatim. \`id:\` is tool-call input only — prose mentions agents as @<name>.\n\n` +-// per-entry lines `- @<name> (Source: custom|builtin, id: <agent_id>) — desc` + optional `\n inputs_schema: <slim json>`+// per-entry lines `- @<name> (Source: custom|marketplace, id: <agent_id>) — desc` + optional `\n inputs_schema: <slim json>`//// Why expose id and ROOT inline (changed 2026-05): the prior layout hid// agent_id (to discourage hex-id leak in user prose) and put paths in a@@ -1789,11 +1822,11 @@ async function buildAgentsIndexBlock(uid: string, allowedIds?: readonly string[]const { pickDescription } = await import('#core-agent');const lang = descriptionLang(getCurrentLang());const customRoot = path.resolve(userAgentsDir(uid));- const builtinRoot = path.resolve(userMarketplaceAgentsDir(uid));+ const marketplaceRoot = path.resolve(userMarketplaceAgentsDir(uid));const header = ['`read_file(<ROOT>/<id>/agent.json)` — ROOT by Source:',`- custom: ${customRoot}`,- `- builtin: ${builtinRoot}`,+ `- marketplace: ${marketplaceRoot}`,'Use these ROOT values verbatim. `id:` is tool-call input only — prose mentions agents as @<name>.','',].join('\n');@@ -1831,6 +1864,7 @@ async function buildAgentInGroupSystemPrompt(_uid: string,agent: { name?: string; description?: string; workflow?: string; agent_id: string; inputs?: unknown; output_format?: string },workingDir: string,+ projectFilesBlock = '',): Promise<string> {const { prompts } = await import('../../prompts/loader');// Render the agent's declared inputs schema so the LLM knows when to@@ -1856,6 +1890,7 @@ async function buildAgentInGroupSystemPrompt(inputs_schema: inputsSchemaJson || '(none)',working_dir: workingDir,output_format_hint: buildOutputFormatHint(agent.output_format),+ project_files_block: projectFilesBlock,});const shared = prompts.load('chat_shared_rules', {});return appendLanguageDirective(concatSharedRules(main, shared));@@ -2467,6 +2502,7 @@ export async function abort(uid: string, cid: string): Promise<void> {const state = _cids.get(cidKey(uid, cid));let cleared = 0;let aborted = 0;+ let abortedModelSessions = 0;if (state) {for (const [, w] of state.workers) {cleared += w.queue.length;@@ -2476,6 +2512,21 @@ export async function abort(uid: string, cid: string): Promise<void> {try { w.abortController?.abort(); } catch { /* ignore */ }}}+ // Belt-and-suspenders abort for model turns. In production traces we saw+ // user stop requests reach this function while the bus worker map no longer+ // exposed the live AbortController (`abortedWorkers=0`), even though the+ // core-agent session kept running. The model client owns a per-session+ // abort registry, so abort all active sessions for this conversation too:+ // `gconv-<cid>` and every `gmember-<cid>-<agent>`.+ try {+ const model = await import('../../model/client');+ const abortByCid = (model as {+ abortActiveSessionsForConversation?: (cid: string) => number;+ }).abortActiveSessionsForConversation;+ if (typeof abortByCid === 'function') abortedModelSessions = abortByCid(cid);+ } catch (err) {+ log.warn(`abort model-session fallback failed cid=${cid}: ${(err as Error).message}`);+ }await setStatus(uid, cid, 'aborted');if (state) {emit(state, { type: 'aborted', cid });@@ -2500,7 +2551,7 @@ export async function abort(uid: string, cid: string): Promise<void> {await new Promise<void>((resolve) => setTimeout(resolve, 25));}}- log.info(`abort user=${uid} cid=${cid} clearedQueue=${cleared} abortedWorkers=${aborted}`);+ log.info(`abort user=${uid} cid=${cid} clearedQueue=${cleared} abortedWorkers=${aborted} abortedModelSessions=${abortedModelSessions}`);}// ── Cleanup ──────────────────────────────────────────────────────────────@@ -2536,6 +2587,23 @@ export function _cidStateForTest(uid: string, cid: string): CidState | null {// having to import bus internals (which would be a circular import). Bus is// the only authority that mutates worker queues; executor speaks through// these hooks.+//+// Catastrophic-if-broken invariant: bus.ts MUST be loaded exactly once per+// process. If a second copy gets loaded (e.g. CJS + ESM dual load when+// `bootstrap.cjs` requires src/main as CJS but somewhere does `await+// import('./group_chat/bus')` — Node always resolves dynamic `import()` to+// ESM regardless of caller context, producing a SEPARATE module instance+// with its own `_cids`), the second load's bindBusHooks call wins because+// plan_executor's `_hooks` is a module-level singleton. Then `groupChat.send`+// (in module A) routes through `planExecutor.reconcile → _hooks.enqueue`+// which now points at module B's enqueue. Module B has empty `_cids`, so+// it creates a fresh state for the cid — agent workers run in B's state,+// events emit to B's listeners (empty), and the IPC subscriber (registered+// on module A) sees zero. Symptom: "loading 一直显示,中断后才看到 process+// info"; chats sidebar sometimes-shows phantom `processing=true`. Bug fixed+// at the load-path side: see chats.ts `require('./group_chat/bus')` (CJS+// require, hits the same module cache as our static `from './bus'` import+// chain) — never `await import` this file.planExecutor.bindBusHooks({async enqueue(params) {@@ -2916,6 +2984,19 @@ async function _buildCliPrompt(const attachmentsBlock = allAtts.length? `## Attachments\n${allAtts.map(a => `- ${a}`).join('\n')}`: '';+ let projectFilesBlock = '';+ try {+ const { getConversation } = await import('../chats');+ const conv = await getConversation(uid, cid);+ const pid = (conv as any)?.project_id;+ if (typeof pid === 'string' && pid) {+ const projectFileFeature = await import('../project_files');+ projectFilesBlock = await projectFileFeature.buildProjectFilesCliBlock(uid, pid);+ }+ } catch (err) {+ log.warn(`cli project files block failed cid=${cid}: ${(err as Error).message}`);+ }+ const filesBlock = [attachmentsBlock, projectFilesBlock].filter(Boolean).join('\n\n');// ── Task body — submission unwrap if the dispatch was a form-submit.// When the user confirmed the input form, the dispatched payload is@@ -2954,7 +3035,7 @@ async function _buildCliPrompt(agent_name: agent.name || agent.agent_id,agent_description: (agent.description_en || agent.description_zh || '').trim(),output_protocol_block: outputProtocolBlock,- attachments_block: attachmentsBlock,+ attachments_block: filesBlock,conversation_block: conversationBlock,task_body: taskBody,});diff --git a/src/main/features/group_chat/conv_title.ts b/src/main/features/group_chat/conv_title.tsindex 08fedcfa..a0eaa6f4 100644--- a/src/main/features/group_chat/conv_title.ts+++ b/src/main/features/group_chat/conv_title.ts@@ -1,20 +1,40 @@// Placeholder conversation-title helpers shared by group-chat modules.-// Keep this file dependency-free so `chats.ts` can import group_chat facade-// without entering the conv_workspace -> chats cycle.+// Keep this file's import surface narrow (only `i18n` — itself a leaf that+// reads locale json) so `chats.ts` can import group_chat facade without+// entering the conv_workspace -> chats cycle.-// Match the literal default titles `chats.createConversation` writes when-// no title is supplied (currently `t('chat.default_title')` resolved at-// creation time per UI language) AND any historical / capitalization-// variant. Match by string equality, not-// lang lookup, because state can carry whatever the conv was named at-// creation regardless of the current UI language.-export const PLACEHOLDER_TITLES: ReadonlySet<string> = new Set([- '新对话',- 'New conversation',+import { SUPPORTED_LANGS, t } from '../../i18n';++// Capitalization variants from an older creation path. Live conversations+// may still carry these literal titles from their creation time, so they+// stay in the set as historical aliases.+const HISTORICAL_PLACEHOLDERS: readonly string[] = ['New Conversation',- 'New chat','New Chat',-]);+];++function buildPlaceholderTitles(): Set<string> {+ const out = new Set<string>(HISTORICAL_PLACEHOLDERS);+ for (const lang of SUPPORTED_LANGS) {+ try {+ const value = t('chat.default_title', undefined, lang);+ // `t()` returns the raw key on miss — skip that to avoid polluting+ // the placeholder set with the literal "chat.default_title" string.+ if (value && value !== 'chat.default_title') out.add(value);+ } catch { /* locale load failure — keep set partial rather than crash */ }+ }+ return out;+}++// Match the literal default title `chats.createConversation` writes when+// no title is supplied (`t('chat.default_title')` resolved at creation+// time per UI language) AND any historical / capitalization variant.+// Built once at module load by enumerating every supported UI language —+// adding a new locale auto-populates the set; nothing to remember to sync.+// Match by string equality, not lang lookup, because state can carry+// whatever the conv was named at creation regardless of the current UI+// language.+export const PLACEHOLDER_TITLES: ReadonlySet<string> = buildPlaceholderTitles();/** True when `title` is a placeholder default written at conversation* creation, i.e. the user hasn't named the chat yet. Locale-agnostic: itdiff --git a/src/main/features/group_chat/plan.ts b/src/main/features/group_chat/plan.tsindex 68608ff7..44be5c0d 100644--- a/src/main/features/group_chat/plan.ts+++ b/src/main/features/group_chat/plan.ts@@ -76,6 +76,17 @@ export interface PlanStep {* Reset to 0 on user-initiated retry / step success. */transient_attempts?: number;+ /** For `assignee === 'user'` steps only: the random `form_id` the+ * executor stamped at dispatch time. Used by+ * `plan_executor.ts::acceptsUserStepCompletion` to verify that the+ * user's `<agent-input-submission>` text references the form we+ * actually dispatched — O(1) lookup instead of reconstructing the+ * mapping by scanning the conversation jsonl. Cleared on retryStep+ * so a re-armed step gets a fresh form_id on the next dispatch.+ * Absent on legacy plans authored before this field existed; in that+ * case the gate falls back to "accept any user reply". */+ pending_form_id?: string;+/** Legacy free-form notes (kept for tools that still use it). */notes?: string;}@@ -150,6 +161,8 @@ function normalizeStep(raw: any, i: number): PlanStep {...(typeof raw?.failure_reason === 'string' ? { failure_reason: raw.failure_reason } : {}),...(Number.isFinite(Number(raw?.transient_attempts)) && Number(raw.transient_attempts) > 0? { transient_attempts: Number(raw.transient_attempts) } : {}),+ ...(typeof raw?.pending_form_id === 'string' && raw.pending_form_id+ ? { pending_form_id: String(raw.pending_form_id) } : {}),...(typeof raw?.notes === 'string' && raw.notes.trim() ? { notes: String(raw.notes) } : {}),};}@@ -234,7 +247,7 @@ export async function setPlan(export async function updateStep(uid: string, cid: string, stepIndex: number, status: StepStatus,- patch?: { notes?: string; output_summary?: string; output_files?: string[]; output_msg_id?: string; failure_reason?: string; transient_attempts?: number },+ patch?: { notes?: string; output_summary?: string; output_files?: string[]; output_msg_id?: string; failure_reason?: string; transient_attempts?: number; pending_form_id?: string },): Promise<PlanFile | null> {const cur = await readPlan(uid, cid);if (!cur) return null;@@ -256,6 +269,10 @@ export async function updateStep(if (patch.transient_attempts > 0) cur.steps[idx].transient_attempts = patch.transient_attempts;else delete cur.steps[idx].transient_attempts;}+ if (patch?.pending_form_id !== undefined) {+ if (patch.pending_form_id) cur.steps[idx].pending_form_id = patch.pending_form_id;+ else delete cur.steps[idx].pending_form_id;+ }await writePlanRaw(uid, cid, cur);log.info(`plan-update user=${uid} cid=${cid} step=${stepIndex} status=${status}`);return cur;diff --git a/src/main/features/group_chat/plan_executor.ts b/src/main/features/group_chat/plan_executor.tsindex be7c65f1..e4fe8443 100644--- a/src/main/features/group_chat/plan_executor.ts+++ b/src/main/features/group_chat/plan_executor.ts@@ -23,12 +23,9 @@import { Mutex } from 'async-mutex';import * as crypto from 'node:crypto';-import * as path from 'node:path';import { createLogger } from '../../logger';import { t } from '../../i18n';-import { userChatsDir } from '../../paths';-import { readJsonl } from '../../storage';import { isTransientError } from '../../util/transient-errors';import { COMMANDER_ID, USER_ID, readMembers } from './state';import {@@ -590,13 +587,23 @@ export async function retryStep(if (!step) return { ok: false, error: 'step not found' };if (step.status !== 'failed') {// The UI can issue a duplicate retry from stale DOM while the first- // retry has already re-armed the step. Treat those post-retry states as- // success so users do not see a false failure after recovery started.+ // retry has already re-armed the step (failed -> pending -> dispatch+ // -> in_progress / blocked-on-deps). Treat those mid-recovery states+ // as success so users do not see a false failure after recovery+ // started.+ //+ // `done` is intentionally NOT in this set: by the time a step+ // reaches `done`, the rail has already re-rendered with a hidden+ // retry button (`_isStepActionable` in plan-rail.js returns+ // `failed`-only), so there is no DOM path that produces a retry+ // click on a done step. Accepting it here would also fire a retry+ // expert-signal with the completed turn's output_msg_id, attributing+ // user dissatisfaction to a successful execution — see PC/CLAUDE.md+ // §10 expert-signals turn_id convention.if (step.status === 'pending'|| step.status === 'in_progress'|| step.status === 'blocked'- || step.status === 'done') {log.info(`plan-step retry-noop cid=${cid} step=${stepIndex} current=${step.status}`);return { ok: true };@@ -607,6 +614,7 @@ export async function retryStep(failure_reason: '',output_msg_id: '',transient_attempts: 0,+ pending_form_id: '',});// Unblock cascade-skipped downstream: when step N failed under// `abort_plan` policy, applyTermination marked all not-yet-terminal@@ -722,32 +730,23 @@ async function maybeMarkFinished(uid: string, cid: string, plan: PlanFile, ctx:}async function acceptsUserStepCompletion(- uid: string,+ _uid: string,cid: string,step: PlanStep,ctx: ReconcileCtx,): Promise<boolean> {- const file = path.join(userChatsDir(uid), `${cid}.jsonl`);- const messages = await readJsonl<GroupMessage>(file, 100_000);- const userForms = messages.filter((m) => m.form?.agent_id === USER_ID);- const stepForms = userForms.filter((m) => m.form?.plan_step_index === step.index);- const candidates = stepForms.length ? stepForms : userForms;- const relevant = candidates.length ? candidates[candidates.length - 1] : undefined;- // Legacy conversations created before user-owned forms existed still need- // plain-text replies to complete user steps.- if (!relevant?.form) return true;+ // Legacy conversations + plans authored before the stamp existed have no+ // `pending_form_id`. Accept any user reply for those (the original+ // behaviour before user-owned forms were introduced).+ const expectedFormId = step.pending_form_id;+ if (!expectedFormId) return true;const text = ctx.finishedMessage?.text || '';const submission = decodeSubmission(text);- const expectedFormId = relevant.form.form_id;if (!submission || submission.agent_id !== USER_ID || submission.form_id !== expectedFormId) {log.info(`plan-user-step ignored non-matching user message cid=${cid} step=${step.index} expected_form=${expectedFormId}`);return false;}- if (relevant.form.submitted !== true) {- log.info(`plan-user-step ignored unmarked submission cid=${cid} step=${step.index} form=${expectedFormId}`);- return false;- }return true;}@@ -901,6 +900,14 @@ async function dispatchStep(// Step asks user for input. Commander voice; render goes to user with// a user-owned form so the reply can route back to the plan machinery// without waking commander as an extra side conversation.+ //+ // Stamp `pending_form_id` on the step BEFORE enqueueing so the user's+ // reply can be matched in O(1) inside the reconcile mutex (see+ // `acceptsUserStepCompletion`) — without this, that gate would have to+ // scan the whole <cid>.jsonl to recover the mapping, with the linear+ // scan happening inside `_planLock`.+ const form = buildUserStepForm(step);+ await updateStep(uid, cid, step.index, 'in_progress', { pending_form_id: form.form_id });await _hooks.enqueue({uid, cid,fromActorId: COMMANDER_ID,@@ -908,7 +915,7 @@ async function dispatchStep(forceTo: [USER_ID],triggered_step: step.index,...(inheritedAttachments && inheritedAttachments.length ? { attachments: inheritedAttachments } : {}),- form: buildUserStepForm(step),+ form,});return;}diff --git a/src/main/features/metacognition.ts b/src/main/features/metacognition.tsindex 579f9d82..aab24c0c 100644--- a/src/main/features/metacognition.ts+++ b/src/main/features/metacognition.ts@@ -38,7 +38,7 @@ export const STRATEGIES_CHAR_LIMIT = 4000; // ~1300 tokens — strategies is a// 1. env `ORKAS_METACOGNITION='0'` — dev/CI kill switch, hard off.// 2. user preference `preferences.json::metacognition_enabled` — UI setting;// undefined (never written) → treated as on, preserving historical default.-// runner.ts and reflection-trigger.ts both read from here; don't sprinkle the+// runner.ts and reflection-orchestrator.ts both read from here; don't sprinkle the// env check around again.export function isFeatureEnabled(): boolean {if (process.env.ORKAS_METACOGNITION === '0') return false;diff --git a/src/main/features/project_files.ts b/src/main/features/project_files.tsnew file mode 100644index 00000000..8c5b2002--- /dev/null+++ b/src/main/features/project_files.ts@@ -0,0 +1,305 @@+/**+ * Project-scoped files.+ *+ * Storage: `<uid>/cloud/projects/<pid>/files/<name>`.+ * These files belong to the project, not a single conversation, so every+ * conversation inside the project receives a lightweight file-list prompt and+ * file tools get read-only access to this directory.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++import { projectFilesDir } from '../paths';+import { createLogger } from '../logger';+import { t } from '../i18n';+import { invalidateFileCache } from './file_indexer';+import { projectExists } from './projects';++const log = createLogger('project_files');++const TEXT_EXTS: ReadonlySet<string> = new Set([+ '.md', '.markdown', '.txt', '.csv', '.tsv',+ '.json', '.yaml', '.yml', '.log',+]);+const IMAGE_EXTS: ReadonlySet<string> = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif']);+const VIDEO_EXTS: ReadonlySet<string> = new Set(['.mp4', '.webm', '.mov', '.m4v', '.ogv']);+const PDF_EXT = '.pdf';+const DOCX_EXT = '.docx';+const ALLOWED_EXTENSIONS: ReadonlySet<string> = new Set([+ ...TEXT_EXTS, PDF_EXT, DOCX_EXT, ...IMAGE_EXTS, ...VIDEO_EXTS,+]);++const MAX_BYTES_TEXT = 5 * 1024 * 1024;+const MAX_BYTES_DOCX = 20 * 1024 * 1024;+const MAX_BYTES_IMAGE = 20 * 1024 * 1024;+const MAX_BYTES_PDF = 100 * 1024 * 1024;+const MAX_BYTES_VIDEO = 200 * 1024 * 1024;+const MAX_FILENAME_LEN = 200;++export type ProjectFileKind = 'text' | 'pdf' | 'docx' | 'image' | 'video';++export interface ProjectFileInfo {+ name: string;+ path: string;+ bytes: number;+ kind: ProjectFileKind;+ mtime: number;+}++export type Result<T = {}> = ({ ok: true } & T) | { ok: false; error: string };++function safeProjectId(projectId: unknown): string {+ if (typeof projectId !== 'string' || !projectId) throw new Error('projectId required');+ if (projectId.includes('/') || projectId.includes('\\') || projectId.includes('\x00') || projectId === '.' || projectId === '..') {+ throw new Error('invalid projectId');+ }+ return projectId;+}++function safeFileName(name: unknown): string {+ if (typeof name !== 'string') throw new Error('filename required');+ const s = name.trim();+ if (!s || s === '.' || s === '..') throw new Error('invalid filename');+ if (s.includes('/') || s.includes('\\') || s.includes('\x00')) {+ throw new Error('filename must not contain path separators');+ }+ if (s.startsWith('.')) throw new Error("filename must not start with '.'");+ if (s.length > MAX_FILENAME_LEN) throw new Error('filename too long');+ const ext = path.extname(s).toLowerCase();+ if (!ALLOWED_EXTENSIONS.has(ext)) {+ throw new Error(t('errors.unsupported_file_ext', { ext: ext || t('errors.unsupported_file_no_ext') }));+ }+ return s;+}++function kindOfName(name: string): ProjectFileKind {+ const ext = path.extname(name).toLowerCase();+ if (ext === PDF_EXT) return 'pdf';+ if (ext === DOCX_EXT) return 'docx';+ if (IMAGE_EXTS.has(ext)) return 'image';+ if (VIDEO_EXTS.has(ext)) return 'video';+ return 'text';+}++function maxBytesFor(name: string): number {+ const ext = path.extname(name).toLowerCase();+ if (ext === PDF_EXT) return MAX_BYTES_PDF;+ if (ext === DOCX_EXT) return MAX_BYTES_DOCX;+ if (IMAGE_EXTS.has(ext)) return MAX_BYTES_IMAGE;+ if (VIDEO_EXTS.has(ext)) return MAX_BYTES_VIDEO;+ return MAX_BYTES_TEXT;+}++function uniqueTarget(dir: string, name: string): string {+ const original = path.join(dir, name);+ if (!fs.existsSync(original)) return original;+ const ext = path.extname(name);+ const stem = name.slice(0, name.length - ext.length);+ const now = new Date();+ const pad = (v: number) => String(v).padStart(2, '0');+ const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;+ for (let i = 0; i < 1000; i += 1) {+ const suffix = i === 0 ? stamp : `${stamp}-${i}`;+ const target = path.join(dir, `${stem}-${suffix}${ext}`);+ if (!fs.existsSync(target)) return target;+ }+ return path.join(dir, `${stem}-${stamp}-${Date.now()}${ext}`);+}++async function ensureProjectFilesDir(userId: string, projectId: string): Promise<string> {+ const pid = safeProjectId(projectId);+ if (!await projectExists(userId, pid)) throw new Error('not_found');+ const dir = projectFilesDir(userId, pid);+ fs.mkdirSync(dir, { recursive: true });+ return dir;+}++function _notifyDirty(projectId: string): void {+ try {+ // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require+ const sync = require('./sync') as { markDirty?: (domain: string, relPath: string) => void };+ sync.markDirty?.('projects', `cloud/projects/${projectId}/files`);+ } catch { /* features/sync stripped */ }+}++function infoFor(absPath: string): ProjectFileInfo | null {+ let st: fs.Stats;+ try { st = fs.statSync(absPath); }+ catch { return null; }+ if (!st.isFile()) return null;+ const name = path.basename(absPath);+ return {+ name,+ path: absPath,+ bytes: st.size,+ kind: kindOfName(name),+ mtime: Math.floor(st.mtimeMs / 1000),+ };+}++export async function listProjectFiles(userId: string, projectId: string): Promise<ProjectFileInfo[]> {+ let dir: string;+ try {+ const pid = safeProjectId(projectId);+ if (!await projectExists(userId, pid)) return [];+ dir = projectFilesDir(userId, pid);+ } catch { return []; }++ let items: fs.Dirent[];+ try { items = fs.readdirSync(dir, { withFileTypes: true }); }+ catch { return []; }++ const out: ProjectFileInfo[] = [];+ items.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));+ for (const e of items) {+ if (!e.isFile() || e.name.startsWith('.')) continue;+ const ext = path.extname(e.name).toLowerCase();+ if (!ALLOWED_EXTENSIONS.has(ext)) continue;+ const info = infoFor(path.join(dir, e.name));+ if (info) out.push(info);+ }+ return out;+}++export async function uploadProjectFile(+ userId: string,+ projectId: string,+ name: string,+ raw: Buffer | Uint8Array | null | undefined,+): Promise<Result<{ info: ProjectFileInfo }>> {+ let safeName: string;+ let pid: string;+ let dir: string;+ try {+ safeName = safeFileName(name);+ pid = safeProjectId(projectId);+ dir = await ensureProjectFilesDir(userId, pid);+ } catch (err) { return { ok: false, error: (err as Error).message }; }++ const buf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw || []);+ const cap = maxBytesFor(safeName);+ if (buf.length > cap) {+ return { ok: false, error: t('errors.file_too_large_mb', { mb: Math.round(cap / 1024 / 1024) }) };+ }+ if (TEXT_EXTS.has(path.extname(safeName).toLowerCase())) {+ const s = buf.toString('utf8');+ if (Buffer.from(s, 'utf8').length !== buf.length) {+ return { ok: false, error: t('errors.not_utf8') };+ }+ }++ const target = uniqueTarget(dir, safeName);+ try { fs.writeFileSync(target, buf); }+ catch (err) { return { ok: false, error: (err as Error).message }; }++ const info = infoFor(target);+ if (!info) return { ok: false, error: 'write failed' };+ _notifyDirty(pid);+ log.info(`upload user=${userId} pid=${pid} name=${info.name} kind=${info.kind} bytes=${info.bytes}`);+ return { ok: true, info };+}++export async function deleteProjectFile(userId: string, projectId: string, name: string): Promise<Result> {+ let safeName: string;+ let pid: string;+ try {+ safeName = safeFileName(name);+ pid = safeProjectId(projectId);+ if (!await projectExists(userId, pid)) return { ok: false, error: 'not_found' };+ } catch (err) { return { ok: false, error: (err as Error).message }; }++ const dir = projectFilesDir(userId, pid);+ const abs = path.resolve(dir, safeName);+ if (path.relative(path.resolve(dir), abs).startsWith('..')) return { ok: false, error: 'forbidden' };+ if (!fs.existsSync(abs)) return { ok: false, error: 'not_found' };+ try { fs.unlinkSync(abs); }+ catch (err) { return { ok: false, error: (err as Error).message }; }+ try { invalidateFileCache(userId, abs); }+ catch (err) { log.warn(`invalidate cache ${abs}: ${(err as Error).message}`); }+ try {+ if (fs.existsSync(dir) && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);+ } catch { /* best-effort */ }+ _notifyDirty(pid);+ return { ok: true };+}++export async function resolveProjectFileAbsPath(+ userId: string,+ projectId: string,+ name: string,+): Promise<Result<{ absPath: string; kind: ProjectFileKind }>> {+ let safeName: string;+ let pid: string;+ try {+ safeName = safeFileName(name);+ pid = safeProjectId(projectId);+ if (!await projectExists(userId, pid)) return { ok: false, error: 'not_found' };+ } catch (err) { return { ok: false, error: (err as Error).message }; }++ const root = path.resolve(projectFilesDir(userId, pid));+ const abs = path.resolve(root, safeName);+ const rel = path.relative(root, abs);+ if (rel.startsWith('..') || path.isAbsolute(rel)) return { ok: false, error: 'forbidden' };+ let st: fs.Stats;+ try { st = fs.statSync(abs); }+ catch { return { ok: false, error: 'not_found' }; }+ if (!st.isFile()) return { ok: false, error: 'not_found' };+ return { ok: true, absPath: abs, kind: kindOfName(safeName) };+}++export async function getProjectFilesRoot(userId: string, projectId: string): Promise<string | null> {+ try {+ const pid = safeProjectId(projectId);+ if (!await projectExists(userId, pid)) return null;+ return projectFilesDir(userId, pid);+ } catch { return null; }+}++export async function isProjectFilePath(userId: string, projectId: string, absPath: string): Promise<boolean> {+ const root = await getProjectFilesRoot(userId, projectId);+ if (!root) return false;+ const rel = path.relative(path.resolve(root), path.resolve(absPath));+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));+}++function escapeAttr(s: string): string {+ return s.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');+}++async function listProjectFilePathsForPrompt(userId: string, projectId: string): Promise<string[]> {+ let dir: string;+ try {+ const pid = safeProjectId(projectId);+ if (!await projectExists(userId, pid)) return [];+ dir = projectFilesDir(userId, pid);+ } catch { return []; }++ let items: fs.Dirent[];+ try { items = fs.readdirSync(dir, { withFileTypes: true }); }+ catch { return []; }++ return items+ .filter(e => e.isFile() && !e.name.startsWith('.') && ALLOWED_EXTENSIONS.has(path.extname(e.name).toLowerCase()))+ .sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()))+ .map(e => path.join(dir, e.name));+}++export async function buildProjectFilesManifest(userId: string, projectId: string): Promise<string> {+ const files = await listProjectFilePathsForPrompt(userId, projectId);+ if (!files.length) return '';+ const entries = files.map((p) => `<file path="${escapeAttr(p)}"/>`);+ return [+ '<project-files>',+ 'These files are available to every conversation in this project. Use read_file with the listed path when the task needs content; use stat_file first only when metadata or extraction is needed.',+ ...entries,+ '</project-files>',+ ].join('\n');+}++export async function buildProjectFilesCliBlock(userId: string, projectId: string): Promise<string> {+ const files = await listProjectFilePathsForPrompt(userId, projectId);+ if (!files.length) return '';+ const lines = files.map(p => `- ${p}`);+ return `## Project files\n${lines.join('\n')}`;+}diff --git a/src/main/features/reflection-digest.ts b/src/main/features/reflection-digest.tsdeleted file mode 100644index c244a9ae..00000000--- a/src/main/features/reflection-digest.ts+++ /dev/null@@ -1,201 +0,0 @@-/**- * Build a compact activity digest for the metacognition reflection.- *- * Walks recent core-agent session jsonls bound to a target agent and- * aggregates tool usage + errors into a markdown summary that gets- * spliced into the reflection prompt as `conversationDigest`. Without- * this, startup reflection is blind to what actually happened in the- * cooldown window — see `reflection-trigger.ts` for the call site.- *- * Scope:- * - `<uid>-gconv-*.jsonl` (commander session) AND- * - `<uid>-gmember-<cid>-<aid>.jsonl` (agent worker session) for the- * target agent — added per plan §1.3 P0 because agent worker tool- * calls / errors are the largest reflection blind spot when only- * the commander session is read.- *- * Output target: ~800 chars, ~250 tokens.- */--import * as fs from 'node:fs';-import { userSessionFile } from '../paths';-import { createLogger } from '../logger';-import { listConversations, type Conversation } from './chats';-import { buildGmemberSessionId } from './group_chat/state';--const log = createLogger('reflection-digest');--const ERROR_SAMPLE_MAX = 3;-const ERROR_SAMPLE_LEN = 160;-const TOOL_TOP_N = 8;-const SKILLS_TOP_N = 8;--// ── Aggregator (pure) ───────────────────────────────────────────────────--export interface SessionMetrics {- sessionsAnalyzed: number;- toolCalls: Record<string, number>;- errorCount: number;- errorSamples: string[];- skillsLoaded: Record<string, number>;- earliestTs: number | null;- latestTs: number | null;-}--export function emptyMetrics(): SessionMetrics {- return {- sessionsAnalyzed: 0,- toolCalls: {},- errorCount: 0,- errorSamples: [],- skillsLoaded: {},- earliestTs: null,- latestTs: null,- };-}--/**- * Aggregate one session's messages into the running totals. Messages are- * the parsed jsonl lines — same shape as core-agent emits (role + content- * blocks: text / tool_use / tool_result).- */-export function aggregateSession(messages: any[], into: SessionMetrics): void {- if (!messages.length) return;- into.sessionsAnalyzed += 1;-- for (const m of messages) {- if (!m || typeof m !== 'object') continue;- if (typeof m.ts === 'number') {- into.earliestTs = into.earliestTs === null ? m.ts : Math.min(into.earliestTs, m.ts);- into.latestTs = into.latestTs === null ? m.ts : Math.max(into.latestTs, m.ts);- }- const blocks = Array.isArray(m.content) ? m.content : [];- for (const block of blocks) {- if (!block || typeof block !== 'object') continue;- if (block.type === 'tool_use' && typeof block.name === 'string') {- into.toolCalls[block.name] = (into.toolCalls[block.name] || 0) + 1;- if (block.name === 'skill_manage' && block.input?.action === 'read' && typeof block.input?.id === 'string') {- into.skillsLoaded[block.input.id] = (into.skillsLoaded[block.input.id] || 0) + 1;- }- } else if (block.type === 'tool_result' && block.isError === true) {- into.errorCount += 1;- if (into.errorSamples.length < ERROR_SAMPLE_MAX) {- const text = typeof block.content === 'string'- ? block.content- : JSON.stringify(block.content ?? '');- into.errorSamples.push(text.slice(0, ERROR_SAMPLE_LEN).replace(/\s+/g, ' ').trim());- }- }- }- }-}--// ── Formatter (pure) ────────────────────────────────────────────────────--export function formatDigest(metrics: SessionMetrics, sinceMs: number, nowMs: number): string {- if (metrics.sessionsAnalyzed === 0) {- return `No new conversation activity in the range ${isoDate(sinceMs)} to ${isoDate(nowMs)}.`;- }-- const parts: string[] = [];- const range = `${isoDate(metrics.earliestTs ?? sinceMs)} to ${isoDate(metrics.latestTs ?? nowMs)}`;- parts.push(`Based on ${metrics.sessionsAnalyzed} session(s) (${range}):`);-- const sortedTools = Object.entries(metrics.toolCalls).sort((a, b) => b[1] - a[1]).slice(0, TOOL_TOP_N);- if (sortedTools.length) {- parts.push('');- parts.push('**Tool calls**:');- for (const [name, n] of sortedTools) parts.push(`- ${name}: ${n}`);- }-- if (metrics.errorCount > 0) {- parts.push('');- parts.push(`**Total errors**: ${metrics.errorCount}`);- if (metrics.errorSamples.length) {- parts.push('**Error samples**:');- for (const s of metrics.errorSamples) parts.push(`- ${s}`);- }- }-- const sortedSkills = Object.entries(metrics.skillsLoaded).sort((a, b) => b[1] - a[1]).slice(0, SKILLS_TOP_N);- if (sortedSkills.length) {- parts.push('');- parts.push('**Skills loaded**:');- for (const [id, n] of sortedSkills) parts.push(`- ${id}${n > 1 ? ` (${n}x)` : ''}`);- }-- return parts.join('\n');-}--function isoDate(ms: number): string {- return new Date(ms).toISOString().slice(0, 10);-}--// ── I/O wrapper ─────────────────────────────────────────────────────────--/**- * Build the digest for a target agent ('_default' or a specific agent_id).- * Picks conversations whose `agent_id` matches and whose session jsonl- * was modified at or after `sinceMs`.- */-export async function buildAgentReflectionDigest(- uid: string,- agentId: string,- sinceMs: number,- nowMs: number = Date.now(),-): Promise<string> {- const metrics = emptyMetrics();- let convs: Conversation[] = [];- try {- convs = await listConversations(uid);- } catch (err) {- log.warn(`listConversations failed for uid ${uid}: ${(err as Error).message}`);- return formatDigest(metrics, sinceMs, nowMs);- }-- // _default → empty agent_id; specific agent → exact match- const targetMatches = (convAgentId: string): boolean =>- agentId === '_default' ? !convAgentId : convAgentId === agentId;-- for (const conv of convs) {- if (!targetMatches(conv.agent_id || '')) continue;- // Two sessions per matched conv: the commander gconv-* (already on- // conv.session_id), and — when the target agent is a specific one- // (not '_default') — the agent worker's gmember-* derived from- // (cid, agentId). _default = commander-only convs.- const sessionIds: string[] = [];- if (conv.session_id) sessionIds.push(conv.session_id);- if (agentId !== '_default') {- sessionIds.push(buildGmemberSessionId(conv.conversation_id, agentId));- }- for (const sessionId of sessionIds) {- _scanSessionFile(uid, sessionId, sinceMs, metrics);- }- }-- return formatDigest(metrics, sinceMs, nowMs);-}--/** Read one session jsonl (gated by mtime), parse lines, fold into metrics.- * Logs warn + skips on read errors so a single corrupt file doesn't break- * the digest. */-function _scanSessionFile(uid: string, sessionId: string, sinceMs: number, metrics: SessionMetrics): void {- let file: string;- try { file = userSessionFile(uid, sessionId); }- catch { return; }- let stat: fs.Stats;- try { stat = fs.statSync(file); }- catch { return; }- if (stat.mtimeMs < sinceMs) return;-- let raw: string;- try { raw = fs.readFileSync(file, 'utf8'); }- catch (err) { log.warn(`read ${file} failed: ${(err as Error).message}`); return; }- const messages: any[] = [];- for (const line of raw.split('\n')) {- if (!line.trim()) continue;- try { messages.push(JSON.parse(line)); }- catch { /* skip malformed line */ }- }- aggregateSession(messages, metrics);-}diff --git a/src/main/features/reflection-orchestrator.ts b/src/main/features/reflection-orchestrator.tsnew file mode 100644index 00000000..14afe92a--- /dev/null+++ b/src/main/features/reflection-orchestrator.ts@@ -0,0 +1,321 @@+/**+ * Reflection orchestrator — the single trigger for metacognitive reflection.+ *+ * Replaces the old startup-only `reflection-trigger.ts` and the per-turn+ * `runner.evaluateReflection` path. Per `docs/plans/reflection-redesign.md`:+ *+ * - One scheduler: fire on boot (after STARTUP_DELAY_MS) and every+ * `CYCLE_INTERVAL_MS` thereafter via a setTimeout chain.+ * - Per-agent gating: 4h min cooldown, dirty gate (signals.jsonl or+ * session jsonl newer than lastReflectedAt), 7-day max-gap fallback.+ * - Per-cycle cap: at most `MAX_AGENTS_PER_CYCLE`; eligible-but-deferred+ * agents wait for the next cycle (no agents lost).+ * - Sequential execution; failures isolate per-agent and don't advance+ * `lastReflectedAt`, so the next cycle retries.+ *+ * Background work; never awaited by the boot path. Tests inject `reflect`,+ * `now`, and timing knobs via `runOneCycle`.+ */++import * as fs from 'node:fs';+import { userReflectionStateFile, userLocalConfigDir, userSessionFile } from '../paths';+import { writeJsonSync } from '../storage';+import { createLogger } from '../logger';+import { listAgents } from './agents';+import { listConversations, type Conversation } from './chats';+import { buildGmemberSessionId } from './group_chat/state';+import * as metacognition from './metacognition';+import { buildTranscript } from './reflection-transcript';+import { querySignals } from './expert_signals';+import { buildRunner } from '../model/core-agent/runner';++const log = createLogger('reflection-orchestrator');++// ── Constants (per plan §2.1) ────────────────────────────────────────────++/** Delay after boot before firing the first cycle. */+export const STARTUP_DELAY_MS = 30_000;+/** Interval between cycles after the first. */+export const CYCLE_INTERVAL_MS = 12 * 3600 * 1000;+/** Minimum gap between reflections for the same agent (anti-thrash). */+export const MIN_COOLDOWN_MS = 4 * 3600 * 1000;+/** Maximum gap — force a sanity reflection even when no signals/activity. */+export const MAX_GAP_MS = 7 * 24 * 3600 * 1000;+/** Default initial lookback window for never-reflected agents. */+export const DEFAULT_LOOKBACK_MS = 48 * 3600 * 1000;+/** Per-cycle agent cap — defer overflow to next cycle. */+export const MAX_AGENTS_PER_CYCLE = 5;+/** Sentinel agent id covering all `normal` (no-agent-bound) conversations. */+export const DEFAULT_AGENT_ID = '_default';++// ── State IO (kept compatible with old reflection-state.json) ────────────++export interface ReflectionState {+ /** ISO timestamp per agent id (or `_default`). */+ lastReflectedAt: Record<string, string>;+}++export function readReflectionState(uid: string): ReflectionState {+ const file = userReflectionStateFile(uid);+ if (!fs.existsSync(file)) return { lastReflectedAt: {} };+ try {+ const raw = fs.readFileSync(file, 'utf8');+ const data = JSON.parse(raw);+ if (!data || typeof data !== 'object' || !data.lastReflectedAt || typeof data.lastReflectedAt !== 'object') {+ log.warn(`reflection-state.json malformed for uid ${uid}, treating as empty`);+ return { lastReflectedAt: {} };+ }+ const clean: Record<string, string> = {};+ for (const [k, v] of Object.entries(data.lastReflectedAt as Record<string, unknown>)) {+ if (typeof v === 'string') clean[k] = v;+ }+ return { lastReflectedAt: clean };+ } catch (err) {+ log.warn(`reflection-state.json parse failed for uid ${uid}: ${(err as Error).message}, treating as empty`);+ return { lastReflectedAt: {} };+ }+}++export function writeReflectionState(uid: string, state: ReflectionState): void {+ writeJsonSync(userReflectionStateFile(uid), state);+}++// ── Eligibility & dirty gate (pure / IO) ────────────────────────────────++interface AgentDecision {+ agentId: string;+ /** Lower bound for activity to include in the next reflection's transcript. */+ sinceMs: number;+ /** Why we picked this agent (logged when we actually run). */+ reason: 'dirty' | 'max_gap' | 'never_reflected';+}++/** Decide which agents are due for reflection in this cycle.+ * Pure-ish wrt to `state` (read once, ts compared in-memory); the dirty+ * check is delegated to `isDirty` so tests can stub it. */+export async function pickAgentsForCycle(+ uid: string,+ agentIds: string[],+ state: ReflectionState,+ now: number,+ isDirty: (uid: string, agentId: string, sinceMs: number) => Promise<boolean>,+): Promise<AgentDecision[]> {+ const out: AgentDecision[] = [];+ for (const id of agentIds) {+ const lastIso = state.lastReflectedAt[id];+ const lastMs = lastIso ? Date.parse(lastIso) : NaN;+ const hasLast = !Number.isNaN(lastMs);++ if (hasLast && now - lastMs < MIN_COOLDOWN_MS) continue; // cooldown++ if (hasLast && now - lastMs >= MAX_GAP_MS) {+ out.push({ agentId: id, sinceMs: lastMs, reason: 'max_gap' });+ continue;+ }++ const sinceMs = hasLast ? lastMs : now - DEFAULT_LOOKBACK_MS;+ if (await isDirty(uid, id, sinceMs)) {+ out.push({ agentId: id, sinceMs, reason: hasLast ? 'dirty' : 'never_reflected' });+ }+ }++ // Apply per-cycle cap: most-stale (earliest lastReflectedAt) first; ties broken+ // by ordering of agentIds (we already put _default first). Never-reflected+ // agents sort earliest (Date.parse(undefined) = NaN → treat as 0).+ out.sort((a, b) => {+ const aLast = Date.parse(state.lastReflectedAt[a.agentId] || '') || 0;+ const bLast = Date.parse(state.lastReflectedAt[b.agentId] || '') || 0;+ return aLast - bLast;+ });++ if (out.length > MAX_AGENTS_PER_CYCLE) {+ const deferred = out.length - MAX_AGENTS_PER_CYCLE;+ log.info(`cycle: ${out.length} eligible, capping at ${MAX_AGENTS_PER_CYCLE}, deferring ${deferred} to next cycle`);+ return out.slice(0, MAX_AGENTS_PER_CYCLE);+ }+ return out;+}++/** Dirty check: an agent is dirty if signals.jsonl has any entry attributed+ * to it since `sinceMs`, OR if any of its session jsonl files has a turn+ * newer than `sinceMs`. */+export async function isAgentDirty(uid: string, agentId: string, sinceMs: number): Promise<boolean> {+ const isDefault = agentId === DEFAULT_AGENT_ID;++ // (1) signals.jsonl probe+ try {+ const sigs = await querySignals({+ since: new Date(sinceMs).toISOString(),+ aid: isDefault ? null : agentId,+ limit: 1,+ });+ if (sigs.length > 0) return true;+ } catch (err) {+ log.warn(`isAgentDirty: querySignals failed agent=${agentId}: ${(err as Error).message}`);+ }++ // (2) session jsonl mtime probe (gconv for _default; gconv + gmember for specific)+ let convs: Conversation[] = [];+ try { convs = await listConversations(uid); }+ catch (err) {+ log.warn(`isAgentDirty: listConversations failed: ${(err as Error).message}`);+ return false;+ }+ for (const c of convs) {+ const a = c.agent_id || '';+ const matches = isDefault ? !a : a === agentId;+ if (!matches) continue;+ if (_sessionNewerThan(uid, c.session_id, sinceMs)) return true;+ if (!isDefault) {+ const gmemberSid = buildGmemberSessionId(c.conversation_id, agentId);+ if (_sessionNewerThan(uid, gmemberSid, sinceMs)) return true;+ }+ }+ return false;+}++function _sessionNewerThan(uid: string, sessionId: string, sinceMs: number): boolean {+ let file: string;+ try { file = userSessionFile(uid, sessionId); } catch { return false; }+ try {+ const stat = fs.statSync(file);+ return stat.mtimeMs >= sinceMs;+ } catch { return false; }+}++// ── Reflection invocation ────────────────────────────────────────────────++export type ReflectFn = (uid: string, agentId: string, sinceMs: number) => Promise<void>;++/** Build the reflection prompt for one agent and run it. Throws on failure+ * so the caller can decide whether to stamp `lastReflectedAt` (success)+ * or leave it (retry next cycle). */+async function realReflectForAgent(uid: string, agentId: string, sinceMs: number): Promise<void> {+ const runnerAgentId = agentId === DEFAULT_AGENT_ID ? '' : agentId;++ // Ephemeral session — runReflection uses an in-memory session (not the+ // jsonl) so this id is just a label for the LLM-archive devtools.+ const tail = Date.now().toString(36) + Math.random().toString(36).slice(2, 8);+ const sessionId = `reflect-${tail}`;++ const { runner } = await buildRunner({ sessionId, userId: uid, agentId: runnerAgentId });++ const transcriptResult = await buildTranscript(uid, agentId, sinceMs);+ if (!transcriptResult.text) {+ // Dirty gate said yes but transcript came back empty (race / sweep / etc.).+ // Skip without stamping — next cycle's dirty check decides again.+ log.info(`reflect ${agentId}: transcript empty (considered=${transcriptResult.stats.convsConsidered}), skipping`);+ throw new Error('transcript empty after dirty gate');+ }++ const ca = await import('#core-agent');+ const comp = metacognition.readContent(agentId, 'competence');+ const strat = metacognition.readContent(agentId, 'strategies');+ const prompt = ca.buildReviewPrompt(comp.content || '', strat.content || '', transcriptResult.text);++ // `runReflection` swallows provider/LLM/loop errors and returns ''; an+ // empty response is treated as a failed reflection (cooldown not stamped).+ const responseText = await runner.runReflection(prompt);+ if (!responseText || !responseText.trim()) {+ throw new Error('reflection returned empty (provider/LLM error or max loops; see core-agent log)');+ }++ log.info(`reflect ${agentId}: ok (transcript ${transcriptResult.stats.convsIncluded}/${transcriptResult.stats.convsConsidered} convs, ~${transcriptResult.stats.estimatedTokens} tokens)`);+}++// ── Cycle ───────────────────────────────────────────────────────────────++export interface RunCycleOpts {+ /** Override reflection invocation (test seam). */+ reflect?: ReflectFn;+ /** Override `Date.now()` (test seam). */+ now?: () => number;+ /** Override dirty check (test seam). */+ isDirty?: (uid: string, agentId: string, sinceMs: number) => Promise<boolean>;+}++/** Run one reflection cycle: enumerate agents, pick eligible (capped),+ * reflect sequentially. Returns the count actually reflected — useful for+ * tests and logging. */+export async function runOneCycle(uid: string, opts: RunCycleOpts = {}): Promise<number> {+ if (!uid) {+ log.debug('no active uid, skipping cycle');+ return 0;+ }+ if (!metacognition.isFeatureEnabled()) {+ log.debug('metacognition disabled, skipping cycle');+ return 0;+ }+ fs.mkdirSync(userLocalConfigDir(uid), { recursive: true });++ const now = (opts.now ?? Date.now)();+ const reflect = opts.reflect ?? realReflectForAgent;+ const dirtyFn = opts.isDirty ?? isAgentDirty;++ let agents: Awaited<ReturnType<typeof listAgents>> = [];+ try { agents = await listAgents(); }+ catch (err) { log.warn(`listAgents failed: ${(err as Error).message}`); }++ // `_default` first so the most common bucket gets attention even if a+ // long agent list later in the loop hits issues.+ const agentIds = [DEFAULT_AGENT_ID, ...agents.map((a) => a.agent_id)];+ const state = readReflectionState(uid);+ const eligible = await pickAgentsForCycle(uid, agentIds, state, now, dirtyFn);++ if (eligible.length === 0) {+ log.debug(`cycle: nothing eligible (${agentIds.length} agents scanned)`);+ return 0;+ }+ log.info(`cycle start: ${eligible.length}/${agentIds.length} agent(s) eligible`);++ let completed = 0;+ for (const { agentId, sinceMs, reason } of eligible) {+ try {+ await reflect(uid, agentId, sinceMs);+ // Stamp success — read fresh state in case another writer touched it.+ const next = readReflectionState(uid);+ next.lastReflectedAt[agentId] = new Date(now).toISOString();+ writeReflectionState(uid, next);+ completed += 1;+ log.info(`reflect ${agentId}: completed (${reason})`);+ } catch (err) {+ log.warn(`reflect ${agentId}: failed (${reason}): ${(err as Error).message}`);+ }+ }+ log.info(`cycle end: ${completed}/${eligible.length} agent(s) completed`);+ return completed;+}++// ── Loop control ─────────────────────────────────────────────────────────++export interface LoopHandle {+ /** Cancel the next scheduled cycle. Any in-flight cycle continues to+ * completion (no preemption). */+ stop(): void;+}++/** Start the reflection loop: run one cycle now, then every+ * `CYCLE_INTERVAL_MS` until stopped. The boot path calls this once after+ * STARTUP_DELAY_MS and stores the handle so `before-quit` can cancel. */+export function startReflectionLoop(uid: string, opts: RunCycleOpts = {}): LoopHandle {+ let timer: NodeJS.Timeout | null = null;+ let stopped = false;++ const cycle = async () => {+ if (stopped) return;+ try { await runOneCycle(uid, opts); }+ catch (err) { log.error(`cycle threw: ${(err as Error).message}`); }+ if (stopped) return;+ timer = setTimeout(cycle, CYCLE_INTERVAL_MS);+ };++ // Fire-and-forget; the caller has already delayed boot by STARTUP_DELAY_MS.+ cycle();++ return {+ stop() {+ stopped = true;+ if (timer) { clearTimeout(timer); timer = null; }+ },+ };+}diff --git a/src/main/features/reflection-transcript.ts b/src/main/features/reflection-transcript.tsnew file mode 100644index 00000000..659f62fb--- /dev/null+++ b/src/main/features/reflection-transcript.ts@@ -0,0 +1,344 @@+/**+ * Build a chronological activity transcript for reflection.+ *+ * Replaces `reflection-digest.ts` per `docs/plans/reflection-redesign.md`.+ * Reads the target agent's recent conversations, time-interleaves user+ * voice (from gconv) with agent replies (from gmember), injects four+ * system-event signal types (retry / skip / form_left_blank / silence),+ * and applies a double cap (≤5 conversations AND ≤16K tokens).+ *+ * Output is a plain string for the reflection LLM prompt — no aggregation,+ * no structured fields, just light annotation. Reflection LLM judges raw+ * patterns from the text. T0/T1 signals other than the 4 inlined kinds are+ * NOT consumed here (those serve future critic / weekly-review consumers).+ *+ * Pure side-effect-free; safe to call from anywhere with active uid.+ */++import * as fs from 'node:fs';+import { userSessionFile } from '../paths';+import { createLogger } from '../logger';+import { listConversations, type Conversation } from './chats';+import { buildGmemberSessionId } from './group_chat/state';+import { querySignals, type Signal, type SignalType } from './expert_signals';++const log = createLogger('reflection-transcript');++// ── Caps (per plan §2.2) ────────────────────────────────────────────────++export const MAX_CONVS = 5;+export const MAX_TOKENS = 16_000;+export const MAX_AGENT_REPLY_CHARS = 800;+const SYSTEM_EVENT_TYPES: SignalType[] = ['retry', 'skip', 'form_left_blank', 'silence'];++// ── Token estimation (CJK-aware) ────────────────────────────────────────++/** Estimate token count. CJK chars count as ~0.7 token each; other chars+ * as ~0.25 token (≈4 chars/token English heuristic). Empirically within+ * ~10% of model tokenizers for mixed Chinese / English text. */+export function estimateTokens(text: string): number {+ // CJK Unified Ideographs (U+4E00–U+9FFF) + Hiragana (U+3040–U+309F)+ // + Katakana (U+30A0–U+30FF) + Hangul Syllables (U+AC00–U+D7AF).+ const cjkChars = (text.match(/[一-鿿-ヿ가-]/g) || []).length;+ const otherChars = text.length - cjkChars;+ return Math.ceil(cjkChars * 0.7 + otherChars / 4);+}++// ── Internal types ──────────────────────────────────────────────────────++interface TranscriptEntry {+ ts: number;+ kind: 'user' | 'agent' | 'system';+ text: string;+}++interface ConvSection {+ conv: Conversation;+ entries: TranscriptEntry[];+}++// ── Message parsing ─────────────────────────────────────────────────────++/** Parse `<msg from="X" to="Y">...</msg>` wrapper used by group_chat. The+ * wrapper carries the actual sender identity — `from="user"` is the human,+ * `from="commander"` is commander dispatch, `from="<aid>"` is another agent.+ * If no wrapper is detected (e.g. legacy edit chats), treat as a user+ * message with the raw text. */+function parseMsgWrapper(raw: string): { from: string; inner: string } {+ const m = raw.match(/^<msg\s+from="([^"]+)"\s+to="[^"]*"[^>]*>([\s\S]*?)<\/msg>\s*$/);+ if (!m) return { from: 'user', inner: raw };+ return { from: m[1], inner: m[2].trim() };+}++/** Extract user-voice entries from a session jsonl. Filters to role=user+ * text blocks where the `<msg>` wrapper says `from="user"` — drops+ * commander dispatch / agent system messages. Skips tool_result blocks. */+function extractUserEntries(messages: any[]): TranscriptEntry[] {+ const out: TranscriptEntry[] = [];+ for (const m of messages) {+ if (!m || m.role !== 'user') continue;+ if (typeof m.ts !== 'number') continue;+ const blocks = Array.isArray(m.content) ? m.content : [];+ const texts: string[] = [];+ for (const b of blocks) {+ if (!b || b.type !== 'text' || typeof b.text !== 'string') continue;+ const { from, inner } = parseMsgWrapper(b.text);+ if (from !== 'user') continue;+ const trimmed = inner.trim();+ if (trimmed) texts.push(trimmed);+ }+ if (texts.length) out.push({ ts: m.ts, kind: 'user', text: texts.join('\n') });+ }+ return out;+}++/** Extract agent-reply entries from a session jsonl. Filters to role=assistant+ * text blocks only — drops thinking / tool_use / tool_result (those are+ * intermediate work, not the final user-facing output). Caps each entry+ * text at MAX_AGENT_REPLY_CHARS. */+function extractAgentEntries(messages: any[]): TranscriptEntry[] {+ const out: TranscriptEntry[] = [];+ for (const m of messages) {+ if (!m || m.role !== 'assistant') continue;+ if (typeof m.ts !== 'number') continue;+ const blocks = Array.isArray(m.content) ? m.content : [];+ const texts: string[] = [];+ for (const b of blocks) {+ if (!b || b.type !== 'text' || typeof b.text !== 'string') continue;+ const trimmed = b.text.trim();+ if (trimmed) texts.push(trimmed);+ }+ if (!texts.length) continue;+ let text = texts.join('\n');+ if (text.length > MAX_AGENT_REPLY_CHARS) {+ text = text.slice(0, MAX_AGENT_REPLY_CHARS) + '…(truncated)';+ }+ out.push({ ts: m.ts, kind: 'agent', text });+ }+ return out;+}++/** Render one signal as a synthetic system-event transcript entry. Returns+ * null when the signal type isn't one of the 4 inlined kinds (defensive —+ * caller already filters by type). */+function renderSignalEntry(sig: Signal): TranscriptEntry | null {+ const ts = Date.parse(sig.ts);+ if (Number.isNaN(ts)) return null;+ const meta = (sig.metadata || {}) as Record<string, unknown>;+ switch (sig.type) {+ case 'retry':+ return { ts, kind: 'system', text: `user clicked retry on step #${meta.step_index ?? '?'}` };+ case 'skip':+ return { ts, kind: 'system', text: `user clicked skip on step #${meta.step_index ?? '?'}` };+ case 'form_left_blank': {+ const reqLabel = meta.was_required ? 'required field' : 'field';+ return { ts, kind: 'system', text: `user left ${reqLabel} "${meta.input_id ?? '?'}" blank on form submit` };+ }+ case 'silence':+ return { ts, kind: 'system', text: `agent message received no user response (silence threshold reached)` };+ default:+ return null;+ }+}++// ── Session IO ──────────────────────────────────────────────────────────++function readSessionJsonl(uid: string, sessionId: string): any[] {+ let file: string;+ try { file = userSessionFile(uid, sessionId); } catch { return []; }+ let raw: string;+ try { raw = fs.readFileSync(file, 'utf8'); }+ catch { return []; }+ const out: any[] = [];+ for (const line of raw.split('\n')) {+ if (!line.trim()) continue;+ try { out.push(JSON.parse(line)); } catch { /* skip malformed line */ }+ }+ return out;+}++// ── Rendering ───────────────────────────────────────────────────────────++function pad2(n: number): string { return String(n).padStart(2, '0'); }++function formatTs(ts: number): string {+ const d = new Date(ts);+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;+}++function renderEntry(e: TranscriptEntry): string {+ const ts = formatTs(e.ts);+ if (e.kind === 'system') return `[${ts} system event] ${e.text}`;+ return `[${ts} ${e.kind}]\n${e.text}`;+}++function formatConvSection(section: ConvSection): string {+ const c = section.conv;+ const dateBase = c.created_at ? Date.parse(c.created_at) : section.entries[0]?.ts || Date.now();+ const datePart = new Date(dateBase).toISOString().slice(0, 10);+ const lines: string[] = [`### ${c.conversation_id} — ${c.title || '(untitled)'} (${datePart})`, ''];+ for (const e of section.entries) {+ lines.push(renderEntry(e));+ lines.push('');+ }+ return lines.join('\n').trimEnd();+}++// ── Top-level build ─────────────────────────────────────────────────────++export interface TranscriptResult {+ /** Markdown-ish transcript string. Empty when no activity matched. */+ text: string;+ /** Sanity-check counters for callers / observability. */+ stats: {+ convsConsidered: number;+ convsIncluded: number;+ convsTruncated: number;+ estimatedTokens: number;+ };+}++/**+ * Build the activity transcript for one agent over a lookback window.+ * Returns `text: ''` (with `stats.convsIncluded === 0`) when nothing matches.+ *+ * @param uid active user id+ * @param agentId `_default` (no-agent / commander-only conversations) or a specific agent_id+ * @param sinceMs lower bound for activity inclusion (typically lastReflectedAt epoch ms)+ */+export async function buildTranscript(+ uid: string,+ agentId: string,+ sinceMs: number,+): Promise<TranscriptResult> {+ const isDefault = agentId === '_default';++ let convs: Conversation[] = [];+ try { convs = await listConversations(uid); }+ catch (err) {+ log.warn(`listConversations failed uid=${uid}: ${(err as Error).message}`);+ return _empty();+ }++ const matched = convs.filter((c) => {+ const a = c.agent_id || '';+ return isDefault ? !a : a === agentId;+ });+ if (!matched.length) return _empty();++ // Single signal query covers the whole window; we partition by cid below.+ // For `_default` we pass `aid: null` (commander-scope signals like+ // agent_dispatched are filtered out by the SYSTEM_EVENT_TYPES whitelist+ // anyway, so a permissive aid filter for _default is fine).+ let windowSignals: Signal[] = [];+ try {+ windowSignals = await querySignals({+ since: new Date(sinceMs).toISOString(),+ types: SYSTEM_EVENT_TYPES,+ ...(isDefault ? {} : { aid: agentId }),+ });+ } catch (err) {+ log.warn(`querySignals failed: ${(err as Error).message}`);+ }++ const sections: ConvSection[] = [];+ for (const conv of matched) {+ const gconvMsgs = readSessionJsonl(uid, conv.session_id);+ if (!gconvMsgs.length) continue;++ // Activity gate: skip conv whose newest msg predates the window.+ const maxTs = gconvMsgs.reduce((acc, m) => Math.max(acc, typeof m.ts === 'number' ? m.ts : 0), 0);+ if (maxTs < sinceMs) continue;++ const userEntries = extractUserEntries(gconvMsgs).filter((e) => e.ts >= sinceMs);++ let agentEntries: TranscriptEntry[];+ if (isDefault) {+ // No agent worker — commander's reply IS the response shown to user.+ agentEntries = extractAgentEntries(gconvMsgs).filter((e) => e.ts >= sinceMs);+ } else {+ const gmemberSid = buildGmemberSessionId(conv.conversation_id, agentId);+ const gmemberMsgs = readSessionJsonl(uid, gmemberSid);+ agentEntries = extractAgentEntries(gmemberMsgs).filter((e) => e.ts >= sinceMs);+ }++ const sigEntries = windowSignals+ .filter((s) => s.cid === conv.conversation_id)+ .map(renderSignalEntry)+ .filter((e): e is TranscriptEntry => e !== null)+ .filter((e) => e.ts >= sinceMs);++ const entries = [...userEntries, ...agentEntries, ...sigEntries]+ .sort((a, b) => a.ts - b.ts);++ if (!entries.length) continue;+ sections.push({ conv, entries });+ }++ if (!sections.length) return _empty();++ // Sort by most-recent-activity desc and apply MAX_CONVS cap.+ sections.sort((a, b) => _lastTs(b) - _lastTs(a));+ const convsConsidered = sections.length;+ let convsTruncated = Math.max(0, sections.length - MAX_CONVS);+ let kept = sections.slice(0, MAX_CONVS);++ // Render in chronological order (oldest first) and drop oldest sections+ // until token budget is met. Always keep at least one section (the most+ // recent) so a single oversized conv still produces output rather than ''.+ kept.sort((a, b) => _lastTs(a) - _lastTs(b));++ const sinceLabel = _fmtSinceLabel(sinceMs);+ const header = `## Activity since ${sinceLabel}`;++ while (kept.length > 1) {+ const full = `${header}\n\n${kept.map(formatConvSection).join('\n\n')}`;+ if (estimateTokens(full) <= MAX_TOKENS) {+ return _result(full, convsConsidered, kept.length, convsTruncated);+ }+ kept.shift();+ convsTruncated += 1;+ }++ // Single section remaining — emit even if it exceeds budget (logged).+ const full = `${header}\n\n${formatConvSection(kept[0])}`;+ const tokens = estimateTokens(full);+ if (tokens > MAX_TOKENS) {+ log.warn(`transcript exceeds token cap: ${tokens} > ${MAX_TOKENS} (single conv ${kept[0].conv.conversation_id} kept)`);+ }+ return _result(full, convsConsidered, kept.length, convsTruncated);+}++// ── Helpers ─────────────────────────────────────────────────────────────++function _lastTs(s: ConvSection): number {+ return s.entries[s.entries.length - 1].ts;+}++function _fmtSinceLabel(ms: number): string {+ return new Date(ms).toISOString().slice(0, 16).replace('T', ' ');+}++function _empty(): TranscriptResult {+ return { text: '', stats: { convsConsidered: 0, convsIncluded: 0, convsTruncated: 0, estimatedTokens: 0 } };+}++function _result(text: string, considered: number, included: number, truncated: number): TranscriptResult {+ const estimatedTokens = estimateTokens(text);+ if (truncated > 0) {+ log.info(`transcript: ${included}/${considered} convs included, ${truncated} dropped (caps), ~${estimatedTokens} tokens`);+ }+ return { text, stats: { convsConsidered: considered, convsIncluded: included, convsTruncated: truncated, estimatedTokens } };+}++// ── Test seam ───────────────────────────────────────────────────────────++export const _internals = {+ parseMsgWrapper,+ extractUserEntries,+ extractAgentEntries,+ renderSignalEntry,+ formatConvSection,+ renderEntry,+ formatTs,+};diff --git a/src/main/features/reflection-trigger.ts b/src/main/features/reflection-trigger.tsdeleted file mode 100644index 2be6d833..00000000--- a/src/main/features/reflection-trigger.ts+++ /dev/null@@ -1,239 +0,0 @@-/**- * Startup-triggered metacognitive reflection.- *- * Replaces the old per-turn trigger in `model/core-agent/client.ts`. Runs- * once shortly after app boot, with a 48-hour per-agent cooldown so we- * don't reflect on the same agent twice in a session.- *- * Flow:- * 1. Enumerate `_default` (catches all `normal` conversations) + every- * custom and builtin agent for the active user.- * 2. Read `<uid>/local/config/reflection-state.json` for cooldown gates.- * 3. For each eligible agent (cooldown passed), build a runner bound to- * that agent and call `runner.runReflection(periodicReviewPrompt)`.- * 4. On success, stamp `lastReflectedAt[agentId]` and persist.- *- * Iteration is sequential — no point hammering the API in parallel for- * background work, and reflection per agent already takes single-digit- * seconds at most.- */--import * as fs from 'node:fs';-import { userReflectionStateFile, userLocalConfigDir } from '../paths';-import { writeJsonSync } from '../storage';-import { createLogger } from '../logger';-import { listAgents } from './agents';-import * as metacognition from './metacognition';-import { buildAgentReflectionDigest } from './reflection-digest';-import { buildRunner } from '../model/core-agent/runner';--const log = createLogger('reflection-trigger');--export const COOLDOWN_HOURS = 48;-export const STARTUP_DELAY_MS = 30_000;-/** Sentinel agent id covering all `normal` (no-agent) conversations. */-export const DEFAULT_AGENT_ID = '_default';-/** Default digest lookback window for first-ever reflection (no prior stamp). */-export const DEFAULT_LOOKBACK_HOURS = 7 * 24;--export interface ReflectionState {- /** ISO timestamp per agent id (or `_default`). */- lastReflectedAt: Record<string, string>;-}--const EMPTY_STATE: ReflectionState = { lastReflectedAt: {} };--// ── State IO ─────────────────────────────────────────────────────────────--export function readReflectionState(uid: string): ReflectionState {- const file = userReflectionStateFile(uid);- if (!fs.existsSync(file)) return { lastReflectedAt: {} };- try {- const raw = fs.readFileSync(file, 'utf8');- const data = JSON.parse(raw);- if (!data || typeof data !== 'object' || !data.lastReflectedAt || typeof data.lastReflectedAt !== 'object') {- log.warn(`reflection-state.json malformed for uid ${uid}, treating as empty`);- return { lastReflectedAt: {} };- }- // Filter out non-string values defensively.- const clean: Record<string, string> = {};- for (const [k, v] of Object.entries(data.lastReflectedAt as Record<string, unknown>)) {- if (typeof v === 'string') clean[k] = v;- }- return { lastReflectedAt: clean };- } catch (err) {- log.warn(`reflection-state.json parse failed for uid ${uid}: ${(err as Error).message}, treating as empty`);- return { lastReflectedAt: {} };- }-}--export function writeReflectionState(uid: string, state: ReflectionState): void {- const file = userReflectionStateFile(uid);- writeJsonSync(file, state);-}--// ── Eligibility (pure) ───────────────────────────────────────────────────--/**- * Filter `agentIds` down to those past their cooldown.- *- * - Agent never reflected → eligible.- * - Agent reflected within `cooldownHours` of `now` → skipped.- * - Stale/invalid timestamp → eligible (defensive).- */-export function pickEligibleAgents(- agentIds: string[],- state: ReflectionState,- now: number,- cooldownHours: number = COOLDOWN_HOURS,-): string[] {- const cooldownMs = cooldownHours * 3600 * 1000;- const eligible: string[] = [];- for (const id of agentIds) {- const lastIso = state.lastReflectedAt[id];- if (!lastIso) {- eligible.push(id);- continue;- }- const lastMs = Date.parse(lastIso);- if (Number.isNaN(lastMs)) {- eligible.push(id);- continue;- }- if (now - lastMs >= cooldownMs) {- eligible.push(id);- }- }- return eligible;-}--// ── Reflection invocation ────────────────────────────────────────────────--export type ReflectFn = (uid: string, agentId: string, sinceMs: number) => Promise<void>;--/**- * Build a runner bound to `agentId` and run a periodic-review reflection.- * `sinceMs` is the start of the activity window the digest aggregates over- * (typically the last reflection's timestamp; 7 days back for first-ever).- * Throws on auth/provider/LLM failure — orchestrator catches per-agent.- */-async function realReflectForAgent(uid: string, agentId: string, sinceMs: number): Promise<void> {- // `_default` corresponds to "no agent bound" in the chat layer.- const runnerAgentId = agentId === DEFAULT_AGENT_ID ? '' : agentId;-- // Disposable session id — the reflection runs in an in-memory Session- // (created by AgentRunner.runReflection), so the persistent jsonl- // created by buildRunner stays empty. Acceptable: same pattern as- // organizer/extract-img kinds (§5).- const tail = Date.now().toString(36) + Math.random().toString(36).slice(2, 8);- const sessionId = `reflect-${tail}`;-- const { runner } = await buildRunner({- sessionId,- userId: uid,- agentId: runnerAgentId,- });-- // Aggregate recent activity into a markdown digest so the LLM reflects- // on actual events instead of just rereading its own self-assessment.- const digest = await buildAgentReflectionDigest(uid, agentId, sinceMs);-- // Build a periodic-review prompt directly — bypasses evaluateReflection's- // signal-based gating (we're triggered by time, not by metrics).- const ca = await import('#core-agent');- const comp = metacognition.readContent(agentId, 'competence');- const strat = metacognition.readContent(agentId, 'strategies');- const prompt = ca.buildAdaptiveReviewPrompt(- 'periodic_review',- comp.content || '',- strat.content || '',- undefined,- digest,- );-- // `runReflection` swallows provider/LLM/loop-exhaustion errors and returns- // `''` instead of throwing (see core-agent runner.ts: line 687/745/749).- // Empty string = nothing actually succeeded, so it must not burn the- // 48h cooldown. Even when the LLM concludes "no change needed", it- // returns at least one sentence of explanation (non-empty), so a- // post-trim blank is treated as failure. The specific failure reason- // is in the core-agent logs (log.error / log.warn both fire); we- // throw a generic error here.- const responseText = await runner.runReflection(prompt);- if (!responseText || !responseText.trim()) {- throw new Error('reflection returned empty (provider/LLM error or max loops; see core-agent log)');- }-}--// ── Orchestrator ─────────────────────────────────────────────────────────--export interface RunStartupReflectionsOpts {- /** Override the per-agent reflection call (test seam). */- reflect?: ReflectFn;- /** Override `Date.now()` for tests. */- now?: () => number;- /** Override the cooldown window for tests. */- cooldownHours?: number;-}--/**- * Top-level entry. Called once after boot completes (with delay). Safe to- * call concurrently — each agent's reflection awaits in sequence so the- * function as a whole serializes naturally.- */-export async function runStartupReflections(uid: string, opts: RunStartupReflectionsOpts = {}): Promise<void> {- if (!uid) {- log.debug('no active uid, skipping startup reflection');- return;- }- if (!metacognition.isFeatureEnabled()) {- log.debug('metacognition disabled, skipping startup reflection');- return;- }- // Make sure local/config exists for first-boot users so writeReflectionState doesn't race.- fs.mkdirSync(userLocalConfigDir(uid), { recursive: true });-- const now = (opts.now ?? Date.now)();- const reflect = opts.reflect ?? realReflectForAgent;- const cooldownHours = opts.cooldownHours ?? COOLDOWN_HOURS;-- let agents: Awaited<ReturnType<typeof listAgents>> = [];- try {- agents = await listAgents();- } catch (err) {- log.warn(`listAgents failed: ${(err as Error).message}`);- }- // `_default` first so the most common bucket gets attention even if a- // long agent list later in the loop fails.- const agentIds = [DEFAULT_AGENT_ID, ...agents.map((a) => a.agent_id)];-- const state = readReflectionState(uid);- const eligible = pickEligibleAgents(agentIds, state, now, cooldownHours);-- if (eligible.length === 0) {- log.info(`startup reflection: nothing eligible (${agentIds.length} agents, all within ${cooldownHours}h cooldown)`);- return;- }- log.info(`startup reflection: ${eligible.length}/${agentIds.length} agent(s) eligible`);-- const defaultLookbackMs = DEFAULT_LOOKBACK_HOURS * 3600 * 1000;- for (const agentId of eligible) {- // Window for the activity digest: since last reflection, or default- // lookback for first-ever (so we don't drag in ancient sessions).- const lastIso = state.lastReflectedAt[agentId];- const lastMs = lastIso ? Date.parse(lastIso) : NaN;- const sinceMs = Number.isNaN(lastMs) ? now - defaultLookbackMs : lastMs;-- try {- await reflect(uid, agentId, sinceMs);- // Stamp success — read fresh state in case another writer touched it.- const next = readReflectionState(uid);- next.lastReflectedAt[agentId] = new Date(now).toISOString();- writeReflectionState(uid, next);- log.info(`reflection completed for agent ${agentId}`);- } catch (err) {- log.error(`reflection failed for agent ${agentId}: ${(err as Error).message}`);- // Don't update lastReflectedAt — retry on next startup.- }- }-}diff --git a/src/main/features/skills.ts b/src/main/features/skills.tsindex bf9cf1d4..95af30c3 100644--- a/src/main/features/skills.ts+++ b/src/main/features/skills.ts@@ -8,8 +8,8 @@* 4. Skill inline edit chat (per user × skill, prefix injection, file-block extraction)** Two skill sources:- * builtin — data/shared/skills/builtin/<id>/ (seeded from PC/builtin/skills/)- * custom — data/shared/skills/custom/<id>/ (user-created, editable)+ * marketplace — <uid>/local/marketplace/skills/<id>/+ * custom — <uid>/cloud/skills/<id>/** core-agent integration: after any custom-skill mutation we call* `invalidateSkills()` from `model/core-agent/skill-registry` so the next@@ -83,7 +83,8 @@ function _parseSkillFileAttrs(raw: string): { path?: string } {return out;}-export type SkillSource = 'builtin' | 'custom';+export type SkillSource = 'marketplace' | 'custom';+type SkillSourceInput = SkillSource | 'builtin';export interface SkillListing {id: string;@@ -101,7 +102,7 @@ export interface SkillListing {/** Marketplace author uid. Kept optional for install/reconcile compatibility; global UI* surfaces must not render it. */create_uid?: string;- /** Marketplace install version for `source==='builtin'`. Read from `_install.json` so the+ /** Marketplace install version for `source==='marketplace'`. Read from `_install.json` so the* skills-tab card can render a `v1.0.0` chip. Undefined for custom skills. */version?: string;}@@ -247,8 +248,16 @@ function _unescapeDoubleQuoted(s: string): string {});}-function skillBaseDir(source: SkillSource): string {- return source === 'custom' ? CUSTOM_SKILLS_DIR() : userMarketplaceSkillsDir(getActiveUserId());+function normalizeSkillSource(source: SkillSourceInput): SkillSource {+ return source === 'builtin' ? 'marketplace' : source;+}++function isMarketplaceSource(source: SkillSourceInput): boolean {+ return normalizeSkillSource(source) === 'marketplace';+}++function skillBaseDir(source: SkillSourceInput): string {+ return normalizeSkillSource(source) === 'custom' ? CUSTOM_SKILLS_DIR() : userMarketplaceSkillsDir(getActiveUserId());}// Module-level cache for `listSkills`.@@ -298,7 +307,7 @@ export async function getSkillForEdit(skillId: string): Promise<SkillForEdit | nif (!skillId) return null;const sources: Array<[SkillSource, string]> = [['custom', CUSTOM_SKILLS_DIR()],- ['builtin', userMarketplaceSkillsDir(getActiveUserId())],+ ['marketplace', userMarketplaceSkillsDir(getActiveUserId())],];for (const [source, base] of sources) {const d = path.join(base, skillId);@@ -336,7 +345,7 @@ export async function listSkills(): Promise<SkillListing[]> {const out: SkillListing[] = [];const seen = new Set<string>();// Custom first so it wins on id collision (matches openclaw symlink rule).- const sources: Array<[SkillSource, string]> = [['custom', CUSTOM_SKILLS_DIR()], ['builtin', userMarketplaceSkillsDir(getActiveUserId())]];+ const sources: Array<[SkillSource, string]> = [['custom', CUSTOM_SKILLS_DIR()], ['marketplace', userMarketplaceSkillsDir(getActiveUserId())]];for (const [source, baseDir] of sources) {if (!fs.existsSync(baseDir)) continue;const names = fs.readdirSync(baseDir, { withFileTypes: true })@@ -345,8 +354,8 @@ export async function listSkills(): Promise<SkillListing[]> {.sort();for (const name of names) {if (seen.has(name)) {- if (source === 'builtin') {- log.warn(`id conflict: custom and builtin both define "${name}" — custom wins, rename one`);+ if (isMarketplaceSource(source)) {+ log.warn(`id conflict: custom and marketplace both define "${name}" — custom wins, rename one`);}continue;}@@ -367,7 +376,7 @@ export async function listSkills(): Promise<SkillListing[]> {// Marketplace-installed skills carry `_install.json` with `version`. Author uid may also// be present for install/reconcile compatibility, but the global UI intentionally does// not surface it.- if (source === 'builtin') {+ if (isMarketplaceSource(source)) {try {const metaFile = path.join(baseDir, name, '_install.json');if (fs.existsSync(metaFile)) {@@ -376,7 +385,7 @@ export async function listSkills(): Promise<SkillListing[]> {}} catch { /* corrupt _install.json — leave fields undefined */ }}- out.push({ id: name, name: displayName, source, ...descPair, category, enabled: true, create_uid: undefined, version });+ out.push({ id: name, name: displayName, source: normalizeSkillSource(source), ...descPair, category, enabled: true, create_uid: undefined, version });}}_skillListCache = { stamp, data: out };@@ -399,7 +408,7 @@ export function setSkillEnabledForActiveUser(skillId: string, enabled: boolean):export type Result<T = Record<string, unknown>> = ({ ok: true } & T) | { ok: false; error: string };export async function readSkillFile(- source: SkillSource, skillId: string, filepath = 'SKILL.md',+ source: SkillSourceInput, skillId: string, filepath = 'SKILL.md',): Promise<Result<{ content: string; ext: string; path: string }>> {const base = skillBaseDir(source);const skillDir = path.resolve(base, skillId);@@ -420,7 +429,7 @@ export async function readSkillFile(}export async function listSkillTree(- source: SkillSource, skillId: string,+ source: SkillSourceInput, skillId: string,): Promise<Result<{ tree: SkillTreeNode[] }>> {const base = skillBaseDir(source);const skillDir = path.resolve(base, skillId);@@ -1441,10 +1450,13 @@ async function _applySkillContainerEdit(skillId: string, files: SkillFileBlock[]}return { ok: false, error: t('skills.errors.skill_not_found', { id: skillId }) };}- // Built-in skills are dev-mode-only via the detail-panel edit chat; the- // commander flow always rejects regardless of dev mode (mirrors the agent- // edit policy at `bus.ts` post-stream parsing).- if (skill.source !== 'custom') {+ // Marketplace skills are dev-mode-only from any write path (commander+ // here + inline edit chat at sendToSkillChat). Mirrors the agent edit+ // policy at `bus.ts` post-stream parsing. Downstream+ // `writeSkillFileForEditChecked` routes the dev branch through+ // `skills_dev.writeBuiltinSkillFile`, which writes the local marketplace+ // install dir.+ if (skill.source !== 'custom' && !false) {return { ok: false, error: t('errors.builtin_skill_not_editable') };}const written: string[] = [];@@ -1507,6 +1519,14 @@ export async function buildSkillEditSystemPrompt(skill: {dir?: string;}): Promise<string> {const files = await listCustomSkillFiles(skill.id || '');+ /** Picks the file-listing path: `marketplace` reads files from `dir`+ * directly (per-machine install root), `custom` resolves via id under+ * the user's custom skills dir. */+ source?: SkillSource;+}): Promise<string> {+ const files = isMarketplaceSource(skill.source || 'custom') && skill.dir+ ? await _listSkillFilesAt(skill.dir)+ : await listCustomSkillFiles(skill.id || '');// Resolve all three forms into a single legacy `$skill_description` for the// current template, plus the bilingual pair for forward-compat. Phase 2// splits the template; this keeps existing prompt rendering working.@@ -1524,6 +1544,8 @@ export async function buildSkillEditSystemPrompt(skill: {skill_files: skillFilesBlock(files),});return `${body}\n\n---\n\n${buildLanguageDirective()}`;+ const tail = buildLanguageDirective();+ return `${body}\n\n---\n\n${tail}`;}export interface SkillChatResult {@@ -1539,6 +1561,9 @@ export interface SkillChatResult {export async function sendToSkillChat(userId: string, skillId: string, content: string): Promise<SkillChatResult> {const skill = await getCustomSkill(skillId);if (!skill) return { ok: false, error: 'skill not found' };+ if (isMarketplaceSource(skill.source) && !false) {+ return { ok: false, error: t('errors.builtin_skill_not_editable') };+ }const meta = await loadSkillChatMeta(userId, skillId);const sessionId = meta.session_id || defaultSkillSessionId(skillId);@@ -1622,6 +1647,11 @@ export async function* streamSendToSkillChat(yield { type: 'done' };return;}+ if (isMarketplaceSource(skill.source) && !false) {+ yield { type: 'error', text: t('errors.builtin_skill_not_editable') };+ yield { type: 'done' };+ return;+ }const meta = await loadSkillChatMeta(userId, skillId);const sessionId = meta.session_id || defaultSkillSessionId(skillId);diff --git a/src/main/index.ts b/src/main/index.tsindex 5fc07908..d6eff295 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -130,7 +130,7 @@ import * as searchFeature from './features/search';import * as authFeature from './features/auth';import * as appConfig from './features/config';import { getRendererTables } from './i18n';-import * as reflectionTrigger from './features/reflection-trigger';+import * as reflectionOrchestrator from './features/reflection-orchestrator';import * as scheduledTasks from './features/scheduled_tasks';import * as chatAttachments from './features/chat_attachments';import * as chatArtifacts from './features/chat_artifacts';@@ -138,11 +138,11 @@ import * as chatArtifacts from './features/chat_artifacts';import * as connectorsFeature from './features/connectors';import * as windowState from './features/window_state';// (sync + relay both depend on account; connectors depends on the Server OAuth bridge).+// (both depend on the Orkas account/Server surface). Connectors, including Google, are synced.function createWindow(): BrowserWindow {const dev = !app.isPackaged;- const dev = false;const restored = windowState.restoreWindowState();const win = new BrowserWindow({width: 1280,@@ -256,6 +256,7 @@ function registerIpc(): void {builtin_skills_dir: 'X', custom_skills_dir: 'X',agents_index: '', plan_state: '',os: 'X', working_dir: 'X', local_exec_state: 'X',+ project_files_block: '',});const tplLen = tplNormal.length;const skills = await skillsFeature.listSkills();@@ -276,7 +277,7 @@ function registerIpc(): void {},skills: {total: skills.length,- builtin: skills.filter((s) => s.source === 'builtin').length,+ marketplace: skills.filter((s) => s.source === 'marketplace').length,custom: skills.filter((s) => s.source === 'custom').length,ids: skills.map((s) => `${s.source}:${s.id}`),},@@ -754,16 +755,15 @@ if (!gotLock) {}});- // Background: per-agent metacognitive reflection. Time-triggered (48h- // cooldown per agent), not per-turn. Delay so it doesn't race the UI's- // first paint or the user's first action.+ // Background: per-agent metacognitive reflection. Single 12h-chained+ // loop replaces the old 48h-cooldown startup-only trigger+ // (docs/plans/reflection-redesign.md). Delay the first cycle so it+ // doesn't race the UI's first paint or the user's first action; the+ // loop self-schedules thereafter.setTimeout(() => {const uid = users.getActiveUserId();- const reflectLog = createLogger('reflection-trigger');- reflectionTrigger.runStartupReflections(uid).catch((err) => {- reflectLog.error('startup reflection batch failed', { error: err?.message || String(err) });- });- }, reflectionTrigger.STARTUP_DELAY_MS);+ reflectionOrchestrator.startReflectionLoop(uid);+ }, reflectionOrchestrator.STARTUP_DELAY_MS);// Background: scheduled-agent-tasks tick (every 30s). Reads// <uid>/cloud/config/scheduled_tasks.json on each tick and dispatchesdiff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex e11ed467..5b36ec18 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -19,6 +19,7 @@ import { ipcMain, dialog, BrowserWindow, type WebContents } from 'electron';import * as users from '../features/users';import * as chats from '../features/chats';import * as projects from '../features/projects';+import * as projectFiles from '../features/project_files';import * as groupChat from '../features/group_chat';import type { GroupEvent } from '../features/group_chat/bus';import * as agents from '../features/agents';@@ -35,6 +36,7 @@ import * as kbVector from '../features/kb_vector';import * as kbIndexer from '../features/kb_indexer';import * as chatAttachments from '../features/chat_attachments';import * as chatArtifacts from '../features/chat_artifacts';+import * as conversationFiles from '../features/conversation_files';import * as savedApps from '../features/saved_apps';import * as search from '../features/search';import * as auth from '../features/auth';@@ -44,6 +46,8 @@ import * as permissions from '../features/permissions';import * as appConfig from '../features/config';import * as avatars from '../features/avatars';import { getRendererTables, isLang, t } from '../i18n';+import { isPathAllowed } from '../util/path-sandbox';+import * as devtools from '../features/devtools';import * as userWorkspace from '../features/user_workspace';import { invokeHandlers as localAgentsHandlers } from './local_agents';import { invokeHandlers as qualityHandlers } from './quality';@@ -53,7 +57,9 @@ import { createLogger, logFromRenderer } from '../logger';import * as path from 'node:path';import * as fs from 'node:fs';import { shell } from 'electron';-import { WS_ROOT, chatAttachmentDir } from '../paths';+import { WS_ROOT, chatAttachmentDir, projectFilesDir } from '../paths';+import { readState as readGroupChatState } from '../features/group_chat/state';+import { readPlan as readGroupChatPlan } from '../features/group_chat/plan';const log = createLogger('ipc');@@ -98,6 +104,72 @@ function _attachmentScopeForPayload(userId: string, payload: any): string | nullreturn path.resolve(chatAttachmentDir(userId, payload.cid));}+// Project-file scope for sandbox checks. Takes the already-resolved projectId+// (computed by `_resolveWorkspaceScope`, which is cid-authoritative) rather+// than reading payload.projectId directly — this enforces that a caller+// passing `{cid, projectId}` where conv-cid.project_id !== projectId cannot+// reach a foreign project's files (the cid wins, the claimed projectId+// silently drops). When no cid is in payload, `_resolveWorkspaceScope`+// already falls back to payload.projectId, so the commander-tab path+// (project chip click before any conversation exists) continues to work.+function _projectFileScopeForUser(userId: string, projectId: string | undefined): string | null {+ if (!projectId || !safeId(projectId)) return null;+ return path.resolve(projectFilesDir(userId, projectId));+}++/** Build the allowed-roots list for the file-class IPC sandbox: workspace ∪+ * current cid's attachment dir ∪ payload's project-file dir. The actual+ * containment check happens via `util/path-sandbox.isPathAllowed`, which+ * realpath-resolves both candidate and roots so a symlink planted inside+ * any allowed root cannot exfiltrate to a path outside.+ *+ * Centralised for `conversations.attachments.import` / `workspace.revealPath`+ * / `produced.readText` / `produced.writeText` so the scope union stays in+ * sync. Previously each handler did its own `path.resolve(target).startsWith(+ * scope + path.sep)` triplet — lexical only, which let a symlink target+ * outside the scope quietly slip through under a `<uid>` workspace path+ * that itself contained one (the realistic attack: LLM-assisted skill+ * drops a symlink into an attachment dir; user later writes to the+ * apparent path through `produced.writeText` and the bytes land at+ * attacker-chosen target). */+async function _ipcFileSandboxAllowedRoots(userId: string, payload: any): Promise<string[]> {+ const projectId = await _resolveWorkspaceScope(userId, payload);+ const roots: string[] = [userWorkspace.getWorkspacePath(userId, projectId)];+ const att = _attachmentScopeForPayload(userId, payload);+ if (att) roots.push(att);+ const pf = _projectFileScopeForUser(userId, projectId);+ if (pf) roots.push(pf);+ return roots;+}++/** Test-only export — see `test/main/ipc/{produced-readText,workspace-reveal}.test.ts`. */+export const _ipcFileSandboxAllowedRootsForTest = _ipcFileSandboxAllowedRoots;++async function _isConversationRecordedFile(userId: string, cid: string, absPath: string): Promise<boolean> {+ if (!safeId(cid)) return false;+ const target = path.resolve(absPath);+ const matches = (value: unknown): boolean =>+ typeof value === 'string' && !!value && path.resolve(value) === target;++ try {+ const messages = await chats.getMessages(userId, cid, 2000);+ for (const msg of messages as any[]) {+ const produced = Array.isArray(msg?.produced) ? msg.produced : [];+ if (produced.some(matches)) return true;+ }+ } catch { /* best-effort allow-list */ }++ try {+ const plan = await readGroupChatPlan(userId, cid);+ for (const step of plan?.steps || []) {+ const files = Array.isArray(step.output_files) ? step.output_files : [];+ if (files.some(matches)) return true;+ }+ } catch { /* best-effort allow-list */ }++ return false;+}+// ── Invoke handlers ──────────────────────────────────────────────────────// Contract: `(payload, { userId, sender }) => result` where result is// merged into a `{ ok: true, ...result }` response. Throw to signal error.@@ -134,6 +206,17 @@ const invokeHandlers: Record<string, InvokeHandler> = {};},+ 'conversations.files.list': async ({ cid }, ctx) => {+ if (!safeId(cid)) throw new Error('invalid cid');+ const projectId = await userWorkspace.resolveProjectIdForCid(ctx.userId, cid);+ const workspaceRoot = userWorkspace.getWorkspacePath(ctx.userId, projectId);+ const state = await readGroupChatState(ctx.userId, cid);+ const root = state.workspace_dir+ ? path.join(workspaceRoot, state.workspace_dir)+ : workspaceRoot;+ return conversationFiles.listWorkspaceFiles(root);+ },+'conversations.create': async ({ title = '', projectId = '' } = {}, ctx) => {// Validate the projectId belongs to this user before persisting it on// the conv record. Unknown / invalid projectIds are dropped silently@@ -203,6 +286,33 @@ const invokeHandlers: Record<string, InvokeHandler> = {return { project };},+ 'projects.files.list': async ({ projectId }, ctx) => {+ if (!safeId(projectId)) throw new Error('invalid projectId');+ if (!await projects.projectExists(ctx.userId, projectId)) throw new Error('not_found');+ return { files: await projectFiles.listProjectFiles(ctx.userId, projectId) };+ },++ 'projects.files.upload': async ({ projectId, name, data }, ctx) => {+ if (!safeId(projectId)) throw new Error('invalid projectId');+ if (typeof data !== 'string') throw new Error('missing data');+ const buf = Buffer.from(data, 'base64');+ return projectFiles.uploadProjectFile(ctx.userId, projectId, name || '', buf);+ },++ 'projects.files.delete': async ({ projectId, name }, ctx) => {+ if (!safeId(projectId)) throw new Error('invalid projectId');+ if (typeof name !== 'string' || !name) throw new Error('invalid name');+ return projectFiles.deleteProjectFile(ctx.userId, projectId, name);+ },++ 'projects.files.absPath': async ({ projectId, name }, ctx) => {+ if (!safeId(projectId)) throw new Error('invalid projectId');+ if (typeof name !== 'string' || !name) throw new Error('invalid name');+ const r = await projectFiles.resolveProjectFileAbsPath(ctx.userId, projectId, name);+ if (!r.ok) return { ok: false, error: (r as { error?: string }).error || 'failed' };+ return { ok: true, path: r.absPath, kind: r.kind };+ },+// ── Project bindings (the strict scope of agents/skills visible inside// a project conversation; see CLAUDE.md §6 outer-intersection rule) ──// `bindings.list` returns the bound ids JOINED with name/description so@@ -425,6 +535,22 @@ const invokeHandlers: Record<string, InvokeHandler> = {return chatAttachments.uploadAttachment(ctx.userId, cid, name || '', buf);},+ 'conversations.attachments.import': async (payload, ctx) => {+ const cid = payload?.cid;+ const sourcePath = payload?.path;+ if (!safeId(cid)) throw new Error('invalid cid');+ if (typeof sourcePath !== 'string' || !sourcePath) throw new Error('missing path');++ const norm = path.resolve(sourcePath);+ const allowedRoots = await _ipcFileSandboxAllowedRoots(ctx.userId, payload);+ const inSandbox = isPathAllowed(norm, allowedRoots);+ const inRecordedFile = !inSandbox && await _isConversationRecordedFile(ctx.userId, cid, norm);+ if (!inSandbox && !inRecordedFile) {+ throw new Error('path is outside the user workspace');+ }+ return chatAttachments.importAttachmentFromPath(ctx.userId, cid, norm);+ },+'conversations.attachments.delete': async ({ cid, name }, ctx) => {if (!safeId(cid)) throw new Error('invalid cid');return chatAttachments.deleteAttachment(ctx.userId, cid, name || '');@@ -569,7 +695,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {'skills.list': async () => ({ skills: await skills.listSkills() }),'skills.read': async ({ source, id, file = 'SKILL.md' }) => {- if (source !== 'builtin' && source !== 'custom') throw new Error('invalid source');+ if (source !== 'marketplace' && source !== 'builtin' && source !== 'custom') throw new Error('invalid source');if (!skills.isValidSkillId(id)) throw new Error('invalid skill id');return skills.readSkillFile(source, id, file);},@@ -583,7 +709,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {},'skills.tree': async ({ source, id }) => {- if (source !== 'builtin' && source !== 'custom') throw new Error('invalid source');+ if (source !== 'marketplace' && source !== 'builtin' && source !== 'custom') throw new Error('invalid source');if (!skills.isValidSkillId(id)) throw new Error('invalid skill id');return skills.listSkillTree(source, id);},@@ -1043,14 +1169,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {if (typeof target !== 'string' || !target) {throw new Error('missing path');}- const projectId = await _resolveWorkspaceScope(ctx.userId, payload);- const ws = userWorkspace.getWorkspacePath(ctx.userId, projectId);const norm = path.resolve(target);- const wsNorm = path.resolve(ws);- const attachmentScope = _attachmentScopeForPayload(ctx.userId, payload);- const inAttachment = !!attachmentScope &&- (norm === attachmentScope || norm.startsWith(attachmentScope + path.sep));- if (!inAttachment && !norm.startsWith(wsNorm + path.sep) && norm !== wsNorm) {+ if (!isPathAllowed(norm, await _ipcFileSandboxAllowedRoots(ctx.userId, payload))) {throw new Error('path is outside the user workspace');}if (!fs.existsSync(norm)) throw new Error('file not found');@@ -1088,15 +1208,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {if (typeof target !== 'string' || !target) {throw new Error('missing path');}- const projectId = await _resolveWorkspaceScope(ctx.userId, payload);- const ws = userWorkspace.getWorkspacePath(ctx.userId, projectId);const norm = path.resolve(target);- const wsNorm = path.resolve(ws);- const attachmentScope = _attachmentScopeForPayload(ctx.userId, payload);- const inAttachment = !!attachmentScope &&- (norm === attachmentScope || norm.startsWith(attachmentScope + path.sep));- const inWorkspace = norm === wsNorm || norm.startsWith(wsNorm + path.sep);- if (!inWorkspace && !inAttachment) {+ if (!isPathAllowed(norm, await _ipcFileSandboxAllowedRoots(ctx.userId, payload))) {throw new Error('path is outside the user workspace');}let st: fs.Stats;@@ -1134,22 +1247,30 @@ const invokeHandlers: Record<string, InvokeHandler> = {if (bytes > MAX_TEXT_BYTES) {return { ok: false, error: 'too_large', size: bytes, cap: MAX_TEXT_BYTES };}- const projectId = await _resolveWorkspaceScope(ctx.userId, payload);- const ws = userWorkspace.getWorkspacePath(ctx.userId, projectId);const norm = path.resolve(target);- const wsNorm = path.resolve(ws);- const attachmentScope = _attachmentScopeForPayload(ctx.userId, payload);- const inAttachment = !!attachmentScope &&- (norm === attachmentScope || norm.startsWith(attachmentScope + path.sep));- const inWorkspace = norm === wsNorm || norm.startsWith(wsNorm + path.sep);- if (!inWorkspace && !inAttachment) {+ if (!isPathAllowed(norm, await _ipcFileSandboxAllowedRoots(ctx.userId, payload))) {throw new Error('path is outside the user workspace');}+ // Used below to gate sync.markDirty: we want to bump the project-files+ // sync domain ONLY when the write actually landed inside the+ // project-files scope (so a workspace-only write doesn't tickle the+ // project-sync engine). Computed via isPathAllowed on the narrow scope+ // so the symlink-safe semantics match the outer gate.+ const projectId = await _resolveWorkspaceScope(ctx.userId, payload);+ const projectFileScope = _projectFileScopeForUser(ctx.userId, projectId);+ const inProjectFile = !!projectFileScope && isPathAllowed(norm, [projectFileScope]);try {fs.writeFileSync(norm, content, 'utf8');} catch (err) {return { ok: false, error: String((err as Error).message || 'write failed') };}+ if (inProjectFile && payload?.projectId) {+ try {+ // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require+ const sync = require('../features/sync') as { markDirty?: (domain: string, relPath: string) => void };+ sync.markDirty?.('projects', `cloud/projects/${payload.projectId}/files`);+ } catch { /* sync stripped */ }+ }return { ok: true, size: bytes };},@@ -1226,15 +1347,13 @@ const streamHandlers: Record<string, StreamHandler> = {}const atts = Array.isArray(attachments) ? attachments.filter((n: any) => typeof n === 'string') : [];// Legacy `conversations.stream` is now a thin wrapper around the- // group_chat bus. **Subscribe to the bus directly BEFORE calling- // `groupChat.send`** — `send` internally wakes the recipient worker+ // group_chat bus. Subscribe to the bus directly BEFORE calling+ // `groupChat.send` — `send` internally wakes the recipient worker// synchronously, and that worker's first state_changed / process events- // can fire on the same microtask cycle as `send` returns. If we waited- // and then opened the subscription via `streamEvents`, those first- // events would arrive at the bus listener list before our listener- // attached and be dropped. The previous "send + then for-await- // streamEvents" pattern was the source of "agent reply doesn't appear- // until I refresh".+ // can fire on the same microtask cycle as `send` returns. We also drain+ // the subscription while `send` is still in flight: plan-triggered runs+ // can spend real time dispatching/reconciling before `send` resolves,+ // but the bus is already carrying the agent's process/delta stream.//// We relay events until the bus is fully quiescent (no worker running// AND every actor's queue empty) — checked via the in-memory bus@@ -1243,34 +1362,69 @@ const streamHandlers: Record<string, StreamHandler> = {const buf: GroupEvent[] = [];let wake: (() => void) | null = null;let cancelled = signal.aborted;+ const notify = () => {+ const w = wake; wake = null; w?.();+ };const onAbort = () => {cancelled = true;- const w = wake; wake = null; w?.();+ notify();};if (!cancelled) signal.addEventListener('abort', onAbort, { once: true });const unsub = groupChat.subscribeBus(ctx.userId, cid, (ev) => {buf.push(ev);- const w = wake; wake = null; w?.();+ notify();});- try {- const sendRes = await groupChat.send({- userId: ctx.userId, cid, text,- ...(atts.length ? { attachments: atts } : {}),- });- if (!sendRes.ok) {- yield { type: 'error', text: sendRes.error || 'send failed' };- return;+ let relayCount = 0;+ let processCount = 0;+ let firstProcessLogged = false;+ let sendDone = false;+ let sendRes: Awaited<ReturnType<typeof groupChat.send>> | null = null;+ let sendErr: unknown = null;+ const sendPromise = (async () => {+ try {+ sendRes = await groupChat.send({+ userId: ctx.userId, cid, text,+ ...(atts.length ? { attachments: atts } : {}),+ });+ } catch (err) {+ sendErr = err;+ } finally {+ sendDone = true;+ notify();}+ })();+ void sendPromise;+ try {drainLoop: while (!cancelled) {while (buf.length) {const ev = buf.shift()!;+ relayCount += 1;+ if (ev.type === 'process') {+ processCount += 1;+ if (!firstProcessLogged) {+ firstProcessLogged = true;+ log.info(`sendStream first process cid=${cid} actor=${(ev as any).actor || ''} kind=${(ev as any).data?.type || ''}`);+ }+ }yield { type: 'event', event: { stream: 'group', data: ev } };}- if (groupChat.busIsQuiescent(ctx.userId, cid)) break drainLoop;+ if (sendDone) {+ if (sendErr) {+ const errText = sendErr instanceof Error ? sendErr.message : String(sendErr || 'send failed');+ yield { type: 'error', text: errText };+ return;+ }+ if (!sendRes?.ok) {+ yield { type: 'error', text: sendRes?.error || 'send failed' };+ return;+ }+ if (groupChat.busIsQuiescent(ctx.userId, cid)) break drainLoop;+ }if (cancelled) break;await new Promise<void>((resolve) => { wake = resolve; });}} finally {+ log.info(`sendStream closed cid=${cid} relayed=${relayCount} process=${processCount} sendDone=${sendDone} cancelled=${cancelled}`);try { unsub(); } catch { /* ignore */ }try { signal.removeEventListener?.('abort', onAbort); } catch { /* ignore */ }}@@ -1286,6 +1440,9 @@ const streamHandlers: Record<string, StreamHandler> = {let wake: (() => void) | null = null;let cancelled = signal.aborted;let sawWorkActivity = !groupChat.busIsQuiescent(ctx.userId, cid);+ let relayCount = 0;+ let processCount = 0;+ let firstProcessLogged = false;const onAbort = () => { cancelled = true; const w = wake; wake = null; w?.(); };if (!cancelled) signal.addEventListener('abort', onAbort, { once: true });const unsub = groupChat.subscribeBus(ctx.userId, cid, (ev) => {@@ -1309,6 +1466,14 @@ const streamHandlers: Record<string, StreamHandler> = {sawWorkActivity = true;}}+ relayCount += 1;+ if (ev.type === 'process') {+ processCount += 1;+ if (!firstProcessLogged) {+ firstProcessLogged = true;+ log.info(`groupEvents first process cid=${cid} actor=${(ev as any).actor || ''} kind=${(ev as any).data?.type || ''}`);+ }+ }yield ev;if (sawWorkActivity && groupChat.busIsQuiescent(ctx.userId, cid)) return;}@@ -1317,6 +1482,7 @@ const streamHandlers: Record<string, StreamHandler> = {await new Promise<void>((resolve) => { wake = resolve; });}} finally {+ log.info(`groupEvents closed cid=${cid} relayed=${relayCount} process=${processCount} cancelled=${cancelled}`);try { unsub(); } catch { /* ignore */ }try { signal.removeEventListener?.('abort', onAbort); } catch { /* ignore */ }}@@ -1478,6 +1644,7 @@ export function register(): void {const controller = new AbortController();const state: StreamState = { cancelled: false, controller };activeStreams.set(requestId, state);+ log.info(`streamStart channel=${channel} requestId=${requestId} cid=${payload?.cid || payload?.id || payload?.agent_id || ''}`);try {const ctx = await resolveContext(event.sender);for await (const ev of handler(payload || {}, ctx, controller.signal)) {@@ -1490,6 +1657,7 @@ export function register(): void {out({ type: 'error', text: (err as Error).message || String(err) });} finally {activeStreams.delete(requestId);+ log.info(`streamDone channel=${channel} requestId=${requestId} cancelled=${state.cancelled}`);out({ type: 'done' });}});diff --git a/src/main/locales/en.json b/src/main/locales/en.jsonindex 5bcdc7e8..736ac454 100644--- a/src/main/locales/en.json+++ b/src/main/locales/en.json@@ -9,6 +9,8 @@"errors.kb_duplicate_sha1": "A file with identical content already exists in the knowledge base: {existingPath}","errors.kb_name_too_long": "Filename too long: \"{name}\". Keep it within ~100 ASCII chars or ~50 CJK chars.","errors.builtin_agent_not_editable": "Built-in agents cannot be edited through chat",+ "errors.builtin_agent_not_editable": "Marketplace agents cannot be edited through chat",+ "errors.builtin_skill_not_editable": "Marketplace skills cannot be edited through chat","errors.agent_disabled": "The agent bound to this conversation is disabled — re-enable it or switch conversation.","errors.no_files_to_organize": "No files to organize","errors.skill_write_failed": "Write failed (invalid path or skill not found)",@@ -41,7 +43,7 @@"skills.errors.name_too_long": "Skill name is too long (max 64 characters)","skills.errors.name_invalid": "Skill name must start with a letter and may contain English letters, digits, underscores (_), and hyphens (-); single spaces between letters are allowed","skills.errors.skill_exists": "Skill \"{name}\" already exists. Please choose another name.",- "skills.errors.builtin_conflict": "Skill name \"{name}\" conflicts with a built-in skill. Please choose another name.",+ "skills.errors.builtin_conflict": "Skill name \"{name}\" conflicts with a marketplace skill. Please choose another name.","skills.errors.url_scheme": "URL must start with http(s)://","skills.errors.create_failed": "Failed to create skill","skills.errors.validation_blocked": "Skill content failed quality validation — creation aborted",diff --git a/src/main/locales/ja.json b/src/main/locales/ja.jsonindex 7b98e56b..5d8f4ddf 100644--- a/src/main/locales/ja.json+++ b/src/main/locales/ja.json@@ -8,8 +8,8 @@"errors.file_already_exists": "同じ名前のファイルがすでに存在します","errors.kb_duplicate_sha1": "同一内容のファイルがナレッジベースにすでに存在します: {existingPath}","errors.kb_name_too_long": "ファイル名が長すぎます: 「{name}」。約 100 ASCII 文字または約 50 CJK 文字以内にしてください。",- "errors.builtin_agent_not_editable": "組み込みエージェントはチャットから編集できません",- "errors.builtin_skill_not_editable": "組み込みスキルはチャットから編集できません",+ "errors.builtin_agent_not_editable": "マーケットプレイスのエージェントはチャットから編集できません",+ "errors.builtin_skill_not_editable": "マーケットプレイスのスキルはチャットから編集できません","errors.agent_disabled": "この会話に紐づくエージェントは無効です。再度有効にするか、会話を切り替えてください。","errors.no_files_to_organize": "整理するファイルがありません","errors.skill_write_failed": "書き込みに失敗しました(パスが無効、またはスキルが見つかりません)",@@ -42,7 +42,7 @@"skills.errors.name_too_long": "スキル名が長すぎます(最大 64 文字)","skills.errors.name_invalid": "スキル名は英字で始め、英字・数字・アンダースコア(_)・ハイフン(-)を使用できます。英字間の単一スペースも使用できます","skills.errors.skill_exists": "スキル「{name}」はすでに存在します。別の名前を選んでください。",- "skills.errors.builtin_conflict": "スキル名「{name}」は組み込みスキルと競合します。別の名前を選んでください。",+ "skills.errors.builtin_conflict": "スキル名「{name}」はマーケットプレイスのスキルと競合します。別の名前を選んでください。","skills.errors.url_scheme": "URL は http(s):// で始まる必要があります","skills.errors.create_failed": "スキルの作成に失敗しました","skills.errors.validation_blocked": "スキル内容が品質検証に失敗したため、作成を中止しました",diff --git a/src/main/locales/zh.json b/src/main/locales/zh.jsonindex f6d5ca28..84c9d71d 100644--- a/src/main/locales/zh.json+++ b/src/main/locales/zh.json@@ -9,6 +9,8 @@"errors.kb_duplicate_sha1": "相同内容的文件已存在于知识库:{existingPath}","errors.kb_name_too_long": "文件名太长:「{name}」。请缩短到中文 50 字 / 英文 100 字符以内。","errors.builtin_agent_not_editable": "内置智能体不可通过对话编辑",+ "errors.builtin_agent_not_editable": "平台智能体不可通过对话编辑",+ "errors.builtin_skill_not_editable": "平台技能不可通过对话编辑","errors.agent_disabled": "本对话绑定的智能体已被禁用,请重新启用或换一个对话","errors.no_files_to_organize": "无可整理的文件","errors.skill_write_failed": "写入失败(路径无效或技能不存在)",@@ -41,7 +43,7 @@"skills.errors.name_too_long": "技能名称过长(最多 64 个字符)","skills.errors.name_invalid": "技能名称需以字母开头,只能包含英文字母、数字、下划线(_)、连字符(-),字母之间可以用单个空格分隔","skills.errors.skill_exists": "技能「{name}」已存在,请换一个名称",- "skills.errors.builtin_conflict": "技能名「{name}」与内置技能冲突,请换一个名称",+ "skills.errors.builtin_conflict": "技能名「{name}」与平台技能冲突,请换一个名称","skills.errors.url_scheme": "URL 必须以 http(s):// 开头","skills.errors.create_failed": "创建技能失败","skills.errors.validation_blocked": "技能内容未通过质量校验,已取消创建",diff --git a/src/main/logger.ts b/src/main/logger.tsindex 5dfc5731..890efec4 100644--- a/src/main/logger.ts+++ b/src/main/logger.ts@@ -62,8 +62,10 @@ function datePrefixOf(name: string): string | null {// ── Sensitive-field redaction ────────────────────────────────────────────-// Keys that may carry secrets — redacted regardless of nesting depth.-// Matched case-insensitively against property names.+// Keys that may carry secrets or PII — redacted regardless of nesting depth.+// Matched case-insensitively against property names. `name` is intentionally+// NOT here (too broad: agent.name / connector.name / project.name / filename+// are all legit business values).const REDACT_KEYS = new Set(['key', 'apikey', 'api_key','access', 'refresh',@@ -73,6 +75,11 @@ const REDACT_KEYS = new Set(['password', 'passwd', 'pwd','authorization','cookie', 'setcookie', 'set-cookie',+ // PII (defense-in-depth — no current call site logs these unmasked, but+ // the rule shields against future regressions).+ 'phone', 'mobile',+ 'email',+ 'username',]);const MASK = '***REDACTED***';diff --git a/src/main/model/client.ts b/src/main/model/client.tsindex d2833473..a38a6adc 100644--- a/src/main/model/client.ts+++ b/src/main/model/client.ts@@ -17,6 +17,8 @@import type { AgentTool } from '#core-agent';import {+ abortActiveSession as _abortActiveSession,+ abortActiveSessionsForConversation as _abortActiveSessionsForConversation,chatWithModel as _chatWithModel,streamChatWithModel as _streamChatWithModel,} from './core-agent/client';@@ -153,3 +155,5 @@ export interface ChatOptions {export const chatWithModel = _chatWithModel;export const streamChatWithModel = _streamChatWithModel;+export const abortActiveSession = _abortActiveSession;+export const abortActiveSessionsForConversation = _abortActiveSessionsForConversation;diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.tsindex 83da51e0..6d6e49db 100644--- a/src/main/model/core-agent/client.ts+++ b/src/main/model/core-agent/client.ts@@ -68,6 +68,54 @@ function buildSkillSandboxEnv(): Record<string, string> {return _skillSandboxEnv;}+type ActiveSessionAbort = {+ abort: () => void;+};++const activeSessionAborts = new Map<string, Set<ActiveSessionAbort>>();++function addActiveSessionAbort(sessionId: string, entry: ActiveSessionAbort): void {+ let set = activeSessionAborts.get(sessionId);+ if (!set) {+ set = new Set();+ activeSessionAborts.set(sessionId, set);+ }+ set.add(entry);+}++function removeActiveSessionAbort(sessionId: string, entry: ActiveSessionAbort): void {+ const set = activeSessionAborts.get(sessionId);+ if (!set) return;+ set.delete(entry);+ if (set.size === 0) activeSessionAborts.delete(sessionId);+}++export function abortActiveSession(sessionId: string): number {+ const set = activeSessionAborts.get(sessionId);+ if (!set || set.size === 0) return 0;+ let count = 0;+ for (const entry of Array.from(set)) {+ try {+ entry.abort();+ count += 1;+ } catch { /* already aborted */ }+ }+ return count;+}++export function abortActiveSessionsForConversation(cid: string): number {+ if (!cid) return 0;+ let count = 0;+ const commanderSession = `gconv-${cid}`;+ const memberPrefix = `gmember-${cid}-`;+ for (const sessionId of Array.from(activeSessionAborts.keys())) {+ if (sessionId === commanderSession || sessionId.startsWith(memberPrefix)) {+ count += abortActiveSession(sessionId);+ }+ }+ return count;+}+/*** Stream chat using core-agent. Yields the same events as the openclaw* client so existing consumers don't care which backend is live.@@ -147,6 +195,17 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<Stlet idleTimer: NodeJS.Timeout | null = null;let idleHit = false;let externalAbort = false;+ let directSessionAbort = false;+ const activeAbortEntry: ActiveSessionAbort = {+ abort: () => {+ directSessionAbort = true;+ log.info(`direct session abort ${turnTag} — releasing locks immediately`);+ controller.abort();+ releaseSlotOnce('session-abort');+ releaseSessionOnce('session-abort');+ },+ };+ addActiveSessionAbort(sessionId, activeAbortEntry);const resetIdle = () => {if (idleTimer) clearTimeout(idleTimer);@@ -284,9 +343,12 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St// Metacognitive reflection is no longer triggered per-turn — it now// runs once at app startup with a per-agent cooldown. See// `features/reflection-trigger.ts`.+ // runs from the background orchestrator on a 12h cycle. See+ // `features/reflection-orchestrator.ts`. Keeping `agentRunResult`+ // captured above for the recorder/archive payload.void agentRunResult;- if (externalAbort) {+ if (externalAbort || directSessionAbort) {// mapCoreAgentEvents may have already yielded 'error: empty response'// for the short-circuit; tag the stream as aborted for the client.yield { type: 'error', text: 'aborted', aborted: true };@@ -295,10 +357,18 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<Styield { type: 'error', text: errText };}} catch (err) {- errText = (err as Error).message || String(err);- log.error('stream error:', err);- yield { type: 'error', text: errText };+ const wasAborted = externalAbort || directSessionAbort || (controller.signal.aborted && !idleHit);+ errText = wasAborted ? 'aborted' : ((err as Error).message || String(err));+ if (wasAborted) {+ abortedFlag = true;+ log.info(`stream aborted ${turnTag}`);+ yield { type: 'error', text: errText, aborted: true };+ } else {+ log.error('stream error:', err);+ yield { type: 'error', text: errText };+ }} finally {+ removeActiveSessionAbort(sessionId, activeAbortEntry);if (idleTimer) clearTimeout(idleTimer);if (abortSignal) abortSignal.removeEventListener?.('abort', onExternalAbort);// Heal orphan tool_use in the cached session before releasing thediff --git a/src/main/model/core-agent/file-tools.ts b/src/main/model/core-agent/file-tools.tsindex a9c79764..7da22b84 100644--- a/src/main/model/core-agent/file-tools.ts+++ b/src/main/model/core-agent/file-tools.ts@@ -14,13 +14,14 @@* conversation's attachment dir + active workspace.* Never triggers extract; `total_chars` is included* only when the cache already has it.- * - `grep_files` — cross-file text search in the same scope. text/md/- * code → direct; pdf/docx → extract (cached); image- * skipped.+ * - `grep_files` — cross-file text search in that same scanned scope.+ * text/md/code → direct; pdf/docx → extract (cached);+ * image skipped.*- * Scope is enforced via `util/path-sandbox.isPathAllowed`: every tool's- * first step is to verify the target falls under- * [ active workspace dir, chat_attachments/<cid>/ ].+ * Scope is enforced via `util/path-sandbox.isPathAllowed`: path-taking tools+ * first verify the target falls under+ * [ active workspace dir, chat_attachments/<cid>/, project files /+ * caller-provided extra roots ].* Paths outside that set return an explicit E_PATH_OUT_OF_SCOPE error.** These tools do NOT require localExec permission — they only read from@@ -77,8 +78,8 @@ export interface FileToolsOpts {* Read AND write are permitted under these roots — used by per-skill edit* chats to expose the skill dir for the `<<<skill-file>>>` tooling. */extraRoots?: readonly string[];- /** Read-only extra roots: file-tools (read_file / search_files / grep_files- * / stat_file) can see these, but write-side tools (edit_file / write_file+ /** Read-only extra roots: path-taking file tools (read_file / stat_file)+ * can see these, but write-side tools (edit_file / write_file* / bash / markdown_to_pdf / html_to_pdf / generate_image) cannot mutate* paths inside. Used by the group-chat commander to inspect agent.json /* built-in agents / skill specs without giving direct-write access — the@@ -131,7 +132,7 @@ function guardPath(opts: FileToolsOpts, abs: string): string | null {if (!isPathAllowed(abs, allowedRoots(opts))) {return errText('E_PATH_OUT_OF_SCOPE',- `path is outside the current conversation's visible scope (workspace + attachments): ${abs}`,+ `path is outside the current conversation's visible scope (workspace + attachments + project files): ${abs}`,);}return null;@@ -146,7 +147,7 @@ function createReadFileTool(opts: FileToolsOpts): AgentTool {'Read a slice of a file\'s text by absolute path.\n'+ '\n'+ 'Parameters:\n'- + ' path — required. Must be inside the current workspace or this conversation\'s attachment dir.\n'+ + ' path — required. Must be inside the current workspace, this conversation\'s attachment dir, or a listed project file.\n'+ ' charStart — 0-based inclusive start offset. Default 0.\n'+ ' charEnd — 0-based exclusive end offset. Default = total_chars (end of file).\n'+ '\n'@@ -169,7 +170,7 @@ function createReadFileTool(opts: FileToolsOpts): AgentTool {inputSchema: {type: 'object',properties: {- path: { type: 'string', description: 'Absolute path. Must be inside workspace or current attachment dir.' },+ path: { type: 'string', description: 'Absolute path. Must be inside workspace, current attachment dir, or project files.' },charStart: { type: 'number', description: '0-based start char (inclusive). Default 0.' },charEnd: { type: 'number', description: '0-based end char (exclusive). Default total_chars.' },},@@ -278,7 +279,7 @@ function createStatFileTool(opts: FileToolsOpts): AgentTool {+ '`total_chars` for the file — typically for a pdf/docx that has never been read.\n'+ '\n'+ 'Parameters:\n'- + ' path — required. Absolute path inside workspace or current attachment dir.\n'+ + ' path — required. Absolute path inside workspace, current attachment dir, or project files.\n'+ '\n'+ 'Response:\n'+ ' <file path="..." kind="text|pdf|docx" total_chars="N"/>\n'@@ -291,7 +292,7 @@ function createStatFileTool(opts: FileToolsOpts): AgentTool {inputSchema: {type: 'object',properties: {- path: { type: 'string', description: 'Absolute path. Must be inside workspace or current attachment dir.' },+ path: { type: 'string', description: 'Absolute path. Must be inside workspace, current attachment dir, or project files.' },},required: ['path'],},diff --git a/src/main/paths.ts b/src/main/paths.tsindex 81c81795..b879d2d9 100644--- a/src/main/paths.ts+++ b/src/main/paths.ts@@ -216,11 +216,12 @@ export const userProjectsDir = (uid: string) => path.join(userCloudRoot(uiexport const projectDir = (uid: string, pid: string) => path.join(userProjectsDir(uid), pid);export const projectMetaFile = (uid: string, pid: string) => path.join(projectDir(uid, pid), 'project.json');export const projectBindingsFile = (uid: string, pid: string) => path.join(projectDir(uid, pid), 'bindings.json');+export const projectFilesDir = (uid: string, pid: string) => path.join(projectDir(uid, pid), 'files');export const agentDir = (uid: string, agentId: string) => path.join(userAgentsDir(uid), agentId || '_default');export const agentDefinitionFile = (uid: string, agentId: string) => path.join(agentDir(uid, agentId), 'agent.json');// Agent metacognition (per-agent self-assessment + learning strategies).-// Writes go through features/metacognition.ts; reflection-trigger fires+// Writes go through features/metacognition.ts; reflection-orchestrator fires// automatically and the `metacognition` tool lets the agent maintain it// itself.export const agentMetaDir = (uid: string, agentId: string) => path.join(agentDir(uid, agentId), 'meta');diff --git a/src/main/prompts/chat_agent_in_group.md b/src/main/prompts/chat_agent_in_group.mdindex b5eec0eb..566235a6 100644--- a/src/main/prompts/chat_agent_in_group.md+++ b/src/main/prompts/chat_agent_in_group.md@@ -8,7 +8,7 @@ Follow the "workflow" below to complete the work the commander / user has dispat**Two hard constraints**:- **Stay concise**: replies center on facts and conclusions, **no filler** (drop wording like "OK, I'll help you..." or "Thank you so much for trusting me..."). The user is reading the result, not the attitude.-- **If a dependency is missing, stop and report immediately**: skill unavailable / credentials missing / tool call failed / required input missing — **stop right away**, state clearly "what's missing + how far you got"; **do not force through** and do not bolt on some side path as a fallback.+- **When a dependency is missing, stop and report**: credentials missing / required input missing / non-recoverable tool failure / referenced skill unavailable — **stop right away**, state clearly "what's missing + how far you got"; **do not force through** and do not bolt on a side path. **Exception**: installable external deps declared in a skill (pip / npm / CLI) follow the rule in Shared rules — install first, stop only on failure.---@@ -32,7 +32,7 @@ Follow the "workflow" below to complete the work the commander / user has dispat- You can **only see** what is written into the inbound message. Tool-call results from the dispatcher, conversations of other agents, and other history of the user — **you cannot see any of those**.- On your first wake-up, the system prepends a `<group-chat-history>` block containing the visible history; afterwards the LLM session accumulates naturally and there's no further prepending.-- If the dispatcher wants you to use particular material, it **must** put the content into the inbound message text (file paths, summaries from the previous step, references — all carried in the inbound message text).+- If the dispatcher wants you to use particular material, it **must** put the content into the inbound message text (file paths, summaries from the previous step, references — all carried in the inbound message text). Shared project files are the exception: when present, they are listed in the Runtime injection block below and may be read by path.- When information is missing, **don't guess**: send a form to ask the user to fill in the key info, or write a body saying "the available info is only enough to do X; recommend filling in Y / Z to continue" — and stop. **You don't need** to find the commander; the bus handles your paused state automatically.---@@ -143,4 +143,6 @@ $inputs_schema### Working directory$working_dir+$project_files_block+$output_format_hintdiff --git a/src/main/prompts/chat_commander.md b/src/main/prompts/chat_commander.mdindex c7fe8ca8..faf323fd 100644--- a/src/main/prompts/chat_commander.md+++ b/src/main/prompts/chat_commander.md@@ -253,11 +253,11 @@ When the system prompt has a `## Connectors` block, those services are reachable### Attachments and files-When a user message has an `<attachments>` prefix, each `<file name=... path=... kind=... [total_chars=...]/>` entry's `path` is the **authoritative absolute path**.+When a user message has an `<attachments>` prefix, or the runtime context includes a `<project-files>` block, each `<file path=.../>` entry's `path` is the **authoritative absolute path**. Project-file entries intentionally include only `path`; call `stat_file(path)` only when you need metadata or extraction.**Locating**:-- Files in the manifest → call `read_file(path=...)` **directly**; don't `search_files` first.-- Files NOT in the manifest → **first `search_files`** (scope = `$working_dir` + this conversation's attachment dir); not being in the manifest does not mean "invisible" — the file may be in the workspace.+- Files in `<attachments>` or `<project-files>` → call `read_file(path=...)` **directly**; don't `search_files` first.+- Files NOT in those blocks → **first `search_files`** (scope = `$working_dir` + this conversation's attachment dir); not being listed does not mean "invisible" — the file may be in the workspace.- If neither has it → ask the user where the file is, or to upload it.**`read_file` / `stat_file` semantics**:@@ -265,7 +265,7 @@ When a user message has an `<attachments>` prefix, each `<file name=... path=...- For pdf / docx not yet extracted, `read_file` returns `E_NEED_STAT`; call `stat_file(path)` first to trigger extraction. text has no such issue.- image does NOT take a range; the response is a real-time compressed grayscale JPEG fed to the vision model (**you see it; the user does NOT**). Manifest entries marked `attached="inline"` already ride this turn's vision input — answer from what you see, do NOT call `read_file` on them.-**`search_files` / `grep_files`**: scope = `$working_dir` ∪ the current conversation's attachment dir. `search_files` finds paths by filename / glob; `grep_files` searches text across files (auto-extracts pdf/docx on hit).+**`search_files` / `grep_files`**: scope = `$working_dir` ∪ the current conversation's attachment dir. Project files are already listed explicitly in `<project-files>`; use those paths directly. `search_files` finds paths by filename / glob; `grep_files` searches text across files (auto-extracts pdf/docx on hit).### Resource path constants@@ -289,6 +289,8 @@ $local_exec_state$plan_state+$project_files_block+### Agents list> Each entry shows `name / source / id / description` plus optional `inputs_schema: [...]` (structured input params — when dispatching via `dispatch_to`, write the field values into `message` in natural language). The block header lists the `read_file(<ROOT>/<id>/agent.json)` pattern + resolved ROOT values per Source.diff --git a/src/main/prompts/chat_shared_rules.md b/src/main/prompts/chat_shared_rules.mdindex d4d6baa5..a6503717 100644--- a/src/main/prompts/chat_shared_rules.md+++ b/src/main/prompts/chat_shared_rules.md@@ -9,6 +9,13 @@ Switch automatically by availability (paid API / model native / built-in `web_se- Regardless of source, **do not** stitch together a "trend summary" purely from search snippets.3. **Failures keep going**: skip to the next URL on a fetch failure; on empty search results or `isError`, **try at least two different strategies** (current UI language ↔ English / different keywords / `site:`) before giving up — a single empty result is not a reason to give up. When everything fails, state the actual cause (empty results / preview text), not vague "API error" wording.+## Skill external dependencies++When a skill's `SKILL.md` lists external runtime requirements (pip / npm packages, CLI binaries, credentials, ...), resolve at invocation time **before** stopping:++1. **Self-resolvable** (pip / npm / CLI installable via a package manager) → install once using the skill's stated command; on success continue, on failure stop and report what you tried (a `bash`-unauthorized error here means the user must enable "Settings → Local execution" and install themselves).+2. **User-required** (API keys, OAuth tokens, paid credentials, sudo) → stop and report what the user must do; never invent a credential or call the tool with a placeholder.+## PDF toolchain rulesTo generate a PDF you **must** use `markdown_to_pdf` (pure markdown) or `html_to_pdf` (tables / custom styles), both based on Electron `printToPDF` + system fonts. **Do not** call reportlab / pypdf / pdfkit / wkhtmltopdf / LaTeX from `bash` — CJK fonts will render as squares. **Even when the built-in PDF tools error, do not fall back** to those low-level libraries — report the error truthfully, do not silently swap paths to "patch over it".diff --git a/src/main/smoke.ts b/src/main/smoke.tsindex 70ca44ed..b6c66fec 100644--- a/src/main/smoke.ts+++ b/src/main/smoke.ts@@ -79,6 +79,7 @@ async function section(name: string, fn: () => void | Promise<void>): Promise<vobuiltin_skills_dir: '/b/s', custom_skills_dir: '/c/s',agents_index: '- foo', plan_state: '',os: 'macOS', working_dir: '/tmp', local_exec_state: 'x',+ project_files_block: '',});assert.ok(typeof rendered === 'string' && rendered.length > 0);});diff --git a/src/main/util/auto-title.ts b/src/main/util/auto-title.tsnew file mode 100644index 00000000..92510f9d--- /dev/null+++ b/src/main/util/auto-title.ts@@ -0,0 +1,22 @@+// Canonical regexes + thresholds for the heuristic conversation auto-title+// ladder. Defined here so `src/main/features/chats.ts` (backend persistence+// path) can import them directly. The renderer mirrors these in+// `src/renderer/modules/auto-title.js` because §8 forbids cross-layer+// imports from renderer to main; the parity is asserted in+// `test/renderer/auto-title-parity.test.ts`, so adding a filler word to one+// side without updating the other fails the test loudly.+//+// Filler regex notes:+// - Both ZH and EN lists are ordered LONGEST-FIRST so the alternation+// doesn't match a shorter prefix when a longer one is also valid+// ("请帮我看一下..." must strip "请帮我看一下", not "请帮我" then leave "看一下").+// - Single-character ZH fillers (bare "请") are intentionally NOT listed+// — too likely to clip real content like "请教...".+// - The clause regex catches the first ZH/EN sentence terminator so a+// long input gets clipped at the first clause boundary.+// - 30-char truncate matches sidebar visual budget.++export const ZH_FILLER_RE = /^(帮我看一下|可不可以|帮我看下|帮我看看|麻烦你|帮我看|我想要|想问问|能不能|可以不|可以吗|请帮我|看一下|麻烦|帮我|我想|想问|请问|看下|看看)\s*/;+export const EN_FILLER_RE = /^(could you|would you|can you|help me|i'?d like to|i want to|please)\s+/i;+export const CLAUSE_RE = /[,。?!;;,.?!]/;+export const TITLE_MAX = 30;diff --git a/src/main/util/log-sanitize.ts b/src/main/util/log-sanitize.tsnew file mode 100644index 00000000..c6ef53dd--- /dev/null+++ b/src/main/util/log-sanitize.ts@@ -0,0 +1,38 @@+/**+ * Best-effort positional redaction for log text being sent off-device.+ *+ * The logger's `redact()` hook covers NAMED object fields (token / api_key+ * / email / ...) but cannot see values stitched into a positional string —+ * `log.warn(\`token=${val}\`)` slips through. This util runs AFTER a log+ * file is assembled (e.g. before `feedback.ts` uploads it), applying narrow+ * regex masks for shapes that are unambiguously sensitive in plain text:+ *+ * - "Bearer <token>" → "Bearer ***"+ * - JWT (3 base64url segs) → "***JWT***"+ * - email [email protected] → "a***@b.c" (matches Server mask_email)+ * - CN mobile 13800138000 → "138****8000" (matches Server mask_phone)+ *+ * Why these four and not more: each additional pattern risks destroying+ * useful diagnostic data. The four above are+ * (a) unambiguous in plain text — a literal "Bearer X" / "eyJ.eyJ.X" /+ * "@example.com" / "13xxxxxxxxx" rarely has a non-secret meaning,+ * (b) consistent with the Server-side masking convention+ * (`Server/utils/util.py::mask_phone` / `mask_email`).+ *+ * Opaque hex/SHA tokens (32+ chars of [a-f0-9]) are deliberately NOT+ * masked — too many false positives (commit shas, file hashes, paths).+ */+export function sanitizeLogTextForUpload(text: string): string {+ if (!text) return text;+ return text+ // Bearer in Authorization header — covers raw "Authorization: Bearer X"+ // and JSON-stringified "\"authorization\":\"Bearer X\"". Case-insensitive+ // because RFC 6750 declares the scheme name case-insensitive.+ .replace(/Bearer\s+[A-Za-z0-9._\-~+/=]+/gi, 'Bearer ***')+ // JWT — three base64url segments, first two starting "eyJ" (base64 of "{").+ .replace(/\beyJ[A-Za-z0-9_\-]+\.eyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\b/g, '***JWT***')+ // Email — keep first local char + full domain for diagnostic value.+ .replace(/\b([A-Za-z0-9._%+-])[A-Za-z0-9._%+-]*(@[A-Za-z0-9.-]+\.[A-Za-z]{2,})\b/g, '$1***$2')+ // CN mobile (11 digits starting 1[3-9]) — keep first 3 + last 4.+ .replace(/\b(1[3-9]\d)\d{4}(\d{4})\b/g, '$1****$2');+}diff --git a/src/renderer/index.html b/src/renderer/index.htmlindex dca54216..6e5beec6 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -124,7 +124,7 @@</button><div id="conv-project-empty-banner" class="conv-project-empty-banner" style="display:none"><span class="muted" data-i18n="project.bindings.empty_in_chat">This project has no agents or skills bound. Open the project page to add some.</span>- <button type="button" class="btn btn-sm" id="conv-project-empty-banner-open" data-i18n="project.bindings.open_settings">Open project page</button>+ <button type="button" class="btn btn-sm" id="conv-project-empty-banner-open" data-i18n="project.bindings.open_settings">Open</button></div><div id="chat-history" class="chat-history"><div class="empty" data-i18n="chat.empty">No messages yet...</div>@@ -247,7 +247,7 @@<div class="skills-grid" id="skills-grid-custom"></div></div><div class="skills-group" id="skills-grid-builtin-group" style="display:none">- <div class="skills-group-label" data-i18n="skills.builtin_group">Built-in</div>+ <div class="skills-group-label" data-i18n="skills.builtin_group">Marketplace</div><div class="skills-grid" id="skills-grid-builtin"></div></div><div class="skills-empty" id="skills-empty" data-i18n="skills.empty">No skills yet</div>@@ -342,7 +342,7 @@<div class="agents-grid" id="agents-grid-custom"></div></div><div class="agents-group" id="agents-grid-builtin-group" style="display:none">- <div class="agents-group-label" data-i18n="agents.builtin_group">Built-in</div>+ <div class="agents-group-label" data-i18n="agents.builtin_group">Marketplace</div><div class="agents-grid" id="agents-grid-builtin"></div></div><div class="agents-empty" id="agents-empty" data-i18n="agents.empty">No agents yet</div>@@ -464,34 +464,81 @@<div class="project-detail-view"><div class="project-detail-content" id="project-detail-content"><div class="project-detail-header">- <h2 class="project-detail-title" id="project-detail-title"></h2>- <input type="text" class="project-detail-title-input" id="project-detail-title-input"- style="display:none" autocomplete="off" spellcheck="false" />+ <div class="project-detail-title-wrap">+ <h2 class="project-detail-title" id="project-detail-title"></h2>+ <input type="text" class="project-detail-title-input" id="project-detail-title-input"+ style="display:none" autocomplete="off" spellcheck="false" />+ </div><div class="project-detail-actions">- <button type="button" class="btn btn-sm" id="project-action-new-conv" data-i18n="project.action.new_conv">+ New chat</button><button type="button" class="btn btn-sm" id="project-action-rename" data-i18n="project.action.rename">Rename</button><button type="button" class="btn btn-sm btn-danger" id="project-action-delete" data-i18n="project.action.delete">Delete</button></div></div>- <section class="project-detail-card" id="project-detail-agents-section">- <div class="project-detail-card-head">- <span class="project-detail-card-title" data-i18n="project.bindings.agents_title">Agents</span>- <button type="button" class="btn btn-sm" id="project-add-agent-btn" data-i18n="project.bindings.add_agent">Add</button>- </div>- <div class="project-bindings-list" id="project-agents-list"></div>- </section>- <!-- Skills section intentionally hidden this round: skills are- globally available regardless of project membership. The- storage + IPC + runner plumbing for skill bindings stays in- place so this card can be re-introduced without a schema- change later. -->- <section class="project-detail-card" id="project-detail-skills-section" style="display:none">- <div class="project-detail-card-head">- <span class="project-detail-card-title" data-i18n="project.bindings.skills_title">Skills</span>- <button type="button" class="btn btn-sm" id="project-add-skill-btn" data-i18n="project.bindings.add_skill">Add</button>+ <div class="project-detail-grid">+ <div class="project-detail-main">+ <section class="project-composer-card">+ <div class="project-composer-input-area">+ <div class="chat-input-overlay">+ <div class="chat-attachments" id="project-chat-attachments" style="display:none"></div>+ </div>+ <textarea id="project-chat-input" data-i18n-placeholder="project.chat.placeholder" placeholder="Type @ to choose agents, skills, connectors." rows="2"></textarea>+ <div class="chat-bottom-bar project-composer-bottom">+ <button type="button" class="chat-attach-btn" id="project-chat-attach-btn" data-i18n-title="project.files.add" title="Add file">+</button>+ <button type="button" class="chat-attach-btn chat-mic-btn" id="project-chat-mic-btn" data-i18n-title="chat.mic_title" title="Voice input">+ <span data-ui-icon="mic" data-ui-icon-class="chat-mic-icon"></span>+ </button>+ <button type="button" class="chat-recipient-chip" id="project-chat-recipient-chip" data-i18n-title="chat.recipient_picker_title" title="Choose agent, skill, or connector">+ <span class="chat-recipient-prefix" data-i18n="chat.recipient_label">To: </span>+ <span class="chat-recipient-name" id="project-chat-recipient-name" data-i18n="chat.recipient_commander">Commander</span>+ </button>+ <div class="chat-skill-chip" id="project-chat-skill-chip" data-target="project" style="display:none">+ <span class="chip-label"></span>+ <span class="chip-close" data-i18n-title="chat.chip_remove_title" title="Remove">×</span>+ </div>+ <button type="button" class="chat-send-btn project-chat-send-btn" id="project-chat-send-btn" data-i18n-title="chat.send_title" title="Send">+ <span data-ui-icon="send" data-ui-icon-class="send-icon"></span>+ </button>+ </div>+ </div>+ </section></div>- <div class="project-bindings-list" id="project-skills-list"></div>- </section>++ <aside class="project-detail-side">+ <section class="project-detail-card" id="project-detail-agents-section">+ <div class="project-detail-card-head">+ <span class="project-detail-card-title" data-i18n="project.bindings.agents_title">Agents</span>+ <button type="button" class="btn btn-sm" id="project-add-agent-btn" data-i18n="project.bindings.add_agent">Add</button>+ </div>+ <div class="project-bindings-list" id="project-agents-list"></div>+ </section>++ <section class="project-detail-card" id="project-detail-files-section">+ <div class="project-detail-card-head">+ <span class="project-detail-card-title" data-i18n="project.files.title">Files</span>+ <button type="button" class="project-card-icon-btn" id="project-add-file-btn"+ data-i18n-title="project.files.add" title="Add file" aria-label="Add file">+</button>+ <input type="file" id="project-file-input" multiple+ accept=".md,.markdown,.txt,.csv,.tsv,.json,.yaml,.yml,.log,.pdf,.docx,.png,.jpg,.jpeg,.webp,.gif,.mp4,.webm,.mov,.m4v,.ogv,text/markdown,text/plain,text/csv,application/json,application/x-yaml,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/png,image/jpeg,image/webp,image/gif,video/mp4,video/webm,video/quicktime"+ style="display:none" />+ </div>+ <div class="project-files-status muted" id="project-files-status"></div>+ <div class="project-files-list" id="project-files-list"></div>+ </section>++ <!-- Skills section intentionally hidden this round: skills are+ globally available regardless of project membership. The+ storage + IPC + runner plumbing for skill bindings stays in+ place so this card can be re-introduced without a schema+ change later. -->+ <section class="project-detail-card" id="project-detail-skills-section" style="display:none">+ <div class="project-detail-card-head">+ <span class="project-detail-card-title" data-i18n="project.bindings.skills_title">Skills</span>+ <button type="button" class="btn btn-sm" id="project-add-skill-btn" data-i18n="project.bindings.add_skill">Add</button>+ </div>+ <div class="project-bindings-list" id="project-skills-list"></div>+ </section>+ </aside>+ </div></div></div></section>@@ -1247,6 +1294,7 @@<script src="./modules/icons.js"></script><script src="./modules/chat-file-viewer.js"></script><script src="./modules/md-view-edit.js"></script>+ <script src="./modules/text-view-edit.js"></script><script src="./modules/context-menu.js"></script><script src="./modules/chat-md-drawer.js"></script><script src="./modules/strip-structural-blocks.js"></script>@@ -1270,6 +1318,7 @@<script src="./modules/agents.js"></script><script src="./modules/saved-apps.js"></script><script src="./modules/agent-schedule.js"></script>+ <script src="./modules/auto-title.js"></script><script src="./modules/utils.js"></script><script src="./modules/validation-report-view.js"></script><script src="./modules/marketplace.js"></script>diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.jsonindex 24ca6c11..f62173e8 100644--- a/src/renderer/locales/en.json+++ b/src/renderer/locales/en.json@@ -149,6 +149,7 @@"chat.new_conv_title": "New conversation","chat.conv_pin_title": "Pin","chat.conv_unpin_title": "Unpin",+ "chat.pin_failed": "Failed to update pin state. Try again or refresh the conversation list.","chat.conv_del_title": "Delete","chat.conv_del_confirm": "Delete this conversation?","chat.loading": "Loading...",@@ -195,7 +196,8 @@"conversation_info.load_failed": "Could not load conversation info: {reason}","conversation_info.empty_tasks": "No tasks yet","conversation_info.empty_steps": "No steps",- "conversation_info.empty_files": "No generated files yet",+ "conversation_info.empty_files": "No files yet",+ "conversation_info.files_truncated": "Showing first {count} files","conversation_info.empty_attachments": "No attachments","conversation_info.task_plan_fallback": "Execution plan","conversation_info.step_files": "Files",@@ -317,14 +319,12 @@"chat.created_skill_chip": "Open skill: {name}","chat.create_agent_failed": "Failed to create agent: {reason}","chat.create_agent_streaming_placeholder": "Assembling agent config…",- "chat.create_skill_streaming_placeholder": "Assembling skill files…",- "chat.skill_file_streaming_placeholder": "Writing {path}…",- "chat.skill_file_streaming_placeholder_unknown": "Writing file…",+ "chat.create_skill_streaming_placeholder": "Organizing skill config…","skills.title": "Skills","skills.add": "+ Add","skills.more_btn": "More","skills.custom_group": "Custom",- "skills.builtin_group": "Platform",+ "skills.builtin_group": "Marketplace","skills.empty": "No skills yet","skills.use": "Use","skills.edit": "Edit",@@ -344,8 +344,8 @@"skills.use_label": "Skill: {skill}","skills.use_prefix": "Use {skill} skill: {content}","skills.rename_title": "Click to rename",- "skills.source_custom": "Custom",- "skills.source_builtin": "Built-in",+ "skills.source_custom": "custom",+ "skills.source_marketplace": "marketplace","skills.name_invalid": "Name must start with a letter; allowed: letters, digits, underscore, hyphen, single internal spaces","skills.desc_unset": "(no description)","skills.no_match": "No matching skills",@@ -374,15 +374,12 @@"skills.delete_failed_with": "Delete failed: {reason}","skills.delete_confirm": "Uninstall the skill \"{name}\" and all its files?","skills.delete_failed_with": "Uninstall failed: {reason}",- "skills.promote_to_builtin": "Make built-in (dev)",- "skills.promote_confirm": "Promote the custom skill \"{name}\" to built-in? This writes to both src/builtin and data/builtin and removes the custom copy.",- "skills.promote_failed_with": "Promote to built-in failed: {reason}","agents.title": "Agents","agents.create_btn": "+ Create","agents.more_btn": "More","agents.empty": "No agents yet","agents.custom_group": "Custom",- "agents.builtin_group": "Platform",+ "agents.builtin_group": "Marketplace","agents.back": "Back to agents","agents.update_failed": "Update failed","agents.use": "Use",@@ -398,8 +395,8 @@"agents.clear_chat_title": "Clear the edit chat for this agent","agents.chat_input_placeholder": "Describe what to adjust...","agents.unnamed": "Untitled",- "agents.source_builtin": "Built-in",- "agents.source_custom": "Custom",+ "agents.source_custom": "custom",+ "agents.source_marketplace": "marketplace","agents.placeholder_unset": "(unset)","agents.edit_btn_done": "Done","agents.edit_btn_edit": "Edit",@@ -419,9 +416,6 @@"agents.delete_confirm": "Uninstall this agent? Related conversations will also be removed.","agents.delete_failed": "Uninstall failed","agents.delete_failed_with": "Uninstall failed: {reason}",- "agents.promote_to_builtin": "Make built-in (dev)",- "agents.promote_confirm": "Promote the custom agent \"{name}\" to built-in? Only agent.json is copied to src/builtin and data/builtin (meta/ and self-evolved skills/ are dropped); the custom copy is removed.",- "agents.promote_failed_with": "Promote to built-in failed: {reason}","agents.edit_chat_empty": "Tell me how you'd like to adjust this agent","agents.clear_confirm": "Clear the edit chat for this agent?","agents.agent_not_found": "Agent not found",@@ -628,7 +622,7 @@"settings.section.tools_note": "Search and image-gen API keys are stored locally only — never synced or sent off-device.","settings.delete": "Delete","settings.search.title": "Search API Key",- "settings.search.sub": "Priority: paid API > model-native search > built-in keyless scraper.",+ "settings.search.sub": "Priority: paid API > model-native search > bundled keyless scraper.","settings.search.provider": "Provider","settings.search.api_key": "API Key","settings.search.add": "+ Add search key",@@ -638,7 +632,7 @@"settings.search.adding": "Adding…","settings.search.add_ok": "Added","settings.search.add_failed": "Add failed",- "settings.search.empty": "No search API key configured yet (built-in keyless scraper will be used).",+ "settings.search.empty": "No search API key configured yet (bundled keyless scraper will be used).","settings.search.active_tag": "Active","settings.search.confirm_delete": "Delete the {provider} search API key?","settings.image.title": "Image generation API Key",@@ -873,7 +867,7 @@"devtools.archives.tools_empty": "(no tools — or pre-upgrade archive)","devtools.archives.tools_source_extra": "Caller-injected (e.g. group_chat commander's plan_set / agent management tools)","devtools.archives.tools_source_orkas": "Orkas-injected (override / extension)",- "devtools.archives.tools_source_core_agent": "core-agent builtin",+ "devtools.archives.tools_source_core_agent": "core-agent bundled","agent_modal.title": "New agent","agent_modal.tab_create": "Create","agent_modal.tab_external": "External",@@ -972,6 +966,16 @@"project.action.new_conv": "New chat","project.action.rename": "Rename","project.action.delete": "Delete",+ "project.chat.placeholder": "Type @ to choose agents, skills, connectors.",+ "project.chat.hint": "Project tasks stay independent while sharing agents and files.",+ "project.files.title": "Files",+ "project.files.add": "Add file",+ "project.files.empty": "No project files yet.",+ "project.files.remove": "Remove file",+ "project.files.uploading": "Uploading...",+ "project.files.upload_failed": "{name} failed to upload: {reason}",+ "project.files.upload_failed_list": "Some files failed to upload:\n{list}",+ "project.files.delete_failed": "Failed to delete project file, please try again","project.bindings.picker_search_placeholder": "Search by name or description","project.bindings.picker_no_match": "No matches found.","agents.no_project_agents": "This project has no agents bound. Open the project page to add some.",@@ -991,7 +995,7 @@"project.bindings.candidates_empty_skills": "No skills available to add.","project.bindings.stale": "Removed","project.bindings.empty_in_chat": "This project has no agents bound. Open the project page to add one.",- "project.bindings.open_settings": "Open project page",+ "project.bindings.open_settings": "Open","search.history_title": "Recent searches","search.history_clear": "Clear","search.failed": "Search failed: {msg}",@@ -1010,7 +1014,7 @@"search.scope.agent": "Agent","search.scope.skill": "Skill","search.source.custom": "Custom",- "search.source.builtin": "Built-in",+ "search.source.marketplace": "marketplace","search.no_results": "No results for \"{query}\"","search.role.user": "Me","search.role.ai": "AI",diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.jsonindex 0404fc2d..6be76847 100644--- a/src/renderer/locales/ja.json+++ b/src/renderer/locales/ja.json@@ -144,6 +144,7 @@"chat.new_conv_title": "新規会話","chat.conv_pin_title": "固定","chat.conv_unpin_title": "固定解除",+ "chat.pin_failed": "固定状態の更新に失敗しました。もう一度試すか、会話一覧を再読み込みしてください。","chat.conv_del_title": "削除","chat.conv_del_confirm": "この会話を削除しますか?","chat.loading": "読み込み中...",@@ -190,7 +191,8 @@"conversation_info.load_failed": "会話情報を読み込めませんでした: {reason}","conversation_info.empty_tasks": "タスクはまだありません","conversation_info.empty_steps": "ステップはありません",- "conversation_info.empty_files": "生成されたファイルはまだありません",+ "conversation_info.empty_files": "ファイルはまだありません",+ "conversation_info.files_truncated": "先頭 {count} 件のファイルを表示しています","conversation_info.empty_attachments": "添付ファイルはありません","conversation_info.task_plan_fallback": "実行計画","conversation_info.step_files": "ファイル",@@ -312,14 +314,12 @@"chat.created_skill_chip": "スキルを開く: {name}","chat.create_agent_failed": "エージェントの作成に失敗しました: {reason}","chat.create_agent_streaming_placeholder": "エージェント設定を組み立てています…",- "chat.create_skill_streaming_placeholder": "スキルファイルを組み立てています…",- "chat.skill_file_streaming_placeholder": "{path} を書き込み中…",- "chat.skill_file_streaming_placeholder_unknown": "ファイルを書き込み中…",+ "chat.create_skill_streaming_placeholder": "スキル設定を整理しています…","skills.title": "スキル","skills.add": "+ 追加","skills.more_btn": "その他","skills.custom_group": "カスタム",- "skills.builtin_group": "プラットフォーム",+ "skills.builtin_group": "マーケットプレイス","skills.empty": "スキルはまだありません","skills.use": "使用","skills.edit": "編集",@@ -340,7 +340,7 @@"skills.use_prefix": "{skill} スキルを使用: {content}","skills.rename_title": "クリックして名前を変更","skills.source_custom": "カスタム",- "skills.source_builtin": "組み込み",+ "skills.source_marketplace": "マーケットプレイス","skills.name_invalid": "名前は英字で始めてください。使用可能: 英数字、アンダースコア、ハイフン、単一の内部スペース","skills.desc_unset": "(説明なし)","skills.no_match": "一致するスキルはありません",@@ -367,15 +367,12 @@"skills.save_failed": "保存に失敗しました","skills.delete_confirm": "スキル「{name}」とその全ファイルをアンインストールしますか?","skills.delete_failed_with": "アンインストールに失敗しました: {reason}",- "skills.promote_to_builtin": "組み込みにする(開発)",- "skills.promote_confirm": "カスタムスキル「{name}」を組み込みに昇格しますか?src/builtin と data/builtin の両方に書き込み、カスタムコピーは削除されます。",- "skills.promote_failed_with": "組み込み化に失敗しました: {reason}","agents.title": "エージェント","agents.create_btn": "+ 作成","agents.more_btn": "その他","agents.empty": "エージェントはまだありません","agents.custom_group": "カスタム",- "agents.builtin_group": "プラットフォーム",+ "agents.builtin_group": "マーケットプレイス","agents.back": "エージェントに戻る","agents.update_failed": "更新に失敗しました","agents.use": "使用",@@ -396,8 +393,8 @@"agents.clear_chat_title": "このエージェントの編集チャットをクリア","agents.chat_input_placeholder": "調整内容を説明...","agents.unnamed": "無題",- "agents.source_builtin": "組み込み","agents.source_custom": "カスタム",+ "agents.source_marketplace": "マーケットプレイス","agents.placeholder_unset": "(未設定)","agents.edit_btn_done": "完了","agents.edit_btn_edit": "編集",@@ -414,9 +411,6 @@"agents.delete_confirm": "このエージェントをアンインストールしますか?関連する会話も削除されます。","agents.delete_failed": "アンインストールに失敗しました","agents.delete_failed_with": "アンインストールに失敗しました: {reason}",- "agents.promote_to_builtin": "組み込みにする(開発)",- "agents.promote_confirm": "カスタムエージェント「{name}」を組み込みに昇格しますか?agent.json のみが src/builtin と data/builtin にコピーされます(meta/ と自己進化スキルは除外)。カスタムコピーは削除されます。",- "agents.promote_failed_with": "組み込み化に失敗しました: {reason}","agents.edit_chat_empty": "このエージェントをどう調整したいか教えてください","agents.clear_confirm": "このエージェントの編集チャットをクリアしますか?","agents.agent_not_found": "エージェントが見つかりません",@@ -623,7 +617,7 @@"settings.section.tools_note": "検索と画像生成の API キーはローカルにのみ保存され、同期や外部送信はされません。","settings.delete": "削除","settings.search.title": "検索 API キー",- "settings.search.sub": "優先順位: 有料 API > モデルネイティブ検索 > 組み込みのキー不要スクレイパー。",+ "settings.search.sub": "優先順位: 有料 API > モデルネイティブ検索 > 同梱のキー不要スクレイパー。","settings.search.provider": "プロバイダー","settings.search.api_key": "API キー","settings.search.add": "+ 検索キーを追加",@@ -633,7 +627,7 @@"settings.search.adding": "追加中…","settings.search.add_ok": "追加しました","settings.search.add_failed": "追加に失敗しました",- "settings.search.empty": "検索 API キーはまだ設定されていません(組み込みのキー不要スクレイパーを使用します)。",+ "settings.search.empty": "検索 API キーはまだ設定されていません(同梱のキー不要スクレイパーを使用します)。","settings.search.active_tag": "有効","settings.search.confirm_delete": "{provider} の検索 API キーを削除しますか?","settings.image.title": "画像生成 API キー",@@ -865,7 +859,7 @@"devtools.archives.tools_empty": "(ツールなし、またはアップグレード前のアーカイブ)","devtools.archives.tools_source_extra": "呼び出し元注入(例: group_chat commander の plan_set / agent 管理ツール)","devtools.archives.tools_source_orkas": "Orkas 注入(上書き / 拡張)",- "devtools.archives.tools_source_core_agent": "core-agent 組み込み",+ "devtools.archives.tools_source_core_agent": "core-agent 同梱","agent_modal.title": "新規エージェント","agent_modal.tab_create": "作成","agent_modal.tab_external": "外部",@@ -964,6 +958,16 @@"project.action.new_conv": "新規チャット","project.action.rename": "名前を変更","project.action.delete": "削除",+ "project.chat.placeholder": "@ を入力してエージェント、スキル、コネクタを選択",+ "project.chat.hint": "プロジェクト内のタスクは独立し、エージェントとファイルを共有します。",+ "project.files.title": "ファイル",+ "project.files.add": "ファイルを追加",+ "project.files.empty": "プロジェクトファイルはまだありません。",+ "project.files.remove": "ファイルを削除",+ "project.files.uploading": "アップロード中...",+ "project.files.upload_failed": "{name} のアップロードに失敗しました: {reason}",+ "project.files.upload_failed_list": "一部のファイルをアップロードできませんでした:\n{list}",+ "project.files.delete_failed": "プロジェクトファイルを削除できませんでした。もう一度お試しください","project.bindings.picker_search_placeholder": "名前または説明で検索","project.bindings.picker_no_match": "一致するものがありません。","agents.no_project_agents": "このプロジェクトに紐づくエージェントはありません。プロジェクトページを開いて追加してください。",@@ -983,7 +987,7 @@"project.bindings.candidates_empty_skills": "追加できるスキルはありません。","project.bindings.stale": "削除済み","project.bindings.empty_in_chat": "このプロジェクトに紐づくエージェントはありません。プロジェクトページを開いて追加してください。",- "project.bindings.open_settings": "プロジェクトページを開く",+ "project.bindings.open_settings": "開く","search.history_title": "最近の検索","search.history_clear": "クリア","search.failed": "検索に失敗しました: {msg}",@@ -1002,7 +1006,7 @@"search.scope.agent": "エージェント","search.scope.skill": "スキル","search.source.custom": "カスタム",- "search.source.builtin": "組み込み",+ "search.source.marketplace": "マーケットプレイス","search.no_results": "「{query}」の結果はありません","search.role.user": "自分","search.role.ai": "AI",diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.jsonindex 27cfad68..6d39a25a 100644--- a/src/renderer/locales/zh.json+++ b/src/renderer/locales/zh.json@@ -149,6 +149,7 @@"chat.new_conv_title": "新对话","chat.conv_pin_title": "置顶","chat.conv_unpin_title": "取消置顶",+ "chat.pin_failed": "置顶状态更新失败,请重试或刷新对话列表。","chat.conv_del_title": "删除","chat.conv_del_confirm": "删除这个对话?","chat.loading": "加载中...",@@ -195,7 +196,8 @@"conversation_info.load_failed": "对话信息加载失败:{reason}","conversation_info.empty_tasks": "暂无任务","conversation_info.empty_steps": "暂无步骤",- "conversation_info.empty_files": "暂无生成文件",+ "conversation_info.empty_files": "暂无文件",+ "conversation_info.files_truncated": "仅显示前 {count} 个文件","conversation_info.empty_attachments": "暂无附件","conversation_info.task_plan_fallback": "执行计划","conversation_info.step_files": "文件",@@ -318,8 +320,6 @@"chat.create_agent_failed": "智能体创建失败:{reason}","chat.create_agent_streaming_placeholder": "正在整理智能体配置…","chat.create_skill_streaming_placeholder": "正在整理技能配置…",- "chat.skill_file_streaming_placeholder": "正在写入 {path}…",- "chat.skill_file_streaming_placeholder_unknown": "正在写入文件…","skills.title": "技能库","skills.add": "+ 添加","skills.more_btn": "更多",@@ -345,7 +345,7 @@"skills.use_prefix": "使用 {skill} 技能:{content}","skills.rename_title": "点击重命名","skills.source_custom": "自定义",- "skills.source_builtin": "内置",+ "skills.source_marketplace": "平台","skills.name_invalid": "名称需以字母开头,可含字母 / 数字 / 下划线 / 横线,词之间允许单个空格","skills.desc_unset": "(未设置描述)","skills.no_match": "无匹配技能",@@ -374,9 +374,6 @@"skills.delete_failed_with": "删除失败:{reason}","skills.delete_confirm": "确认卸载技能 \"{name}\" 及其所有文件?","skills.delete_failed_with": "卸载失败:{reason}",- "skills.promote_to_builtin": "设为内置(开发)",- "skills.promote_confirm": "确认把自定义技能 \"{name}\" 提升为内置?会同步写入 src/builtin 与 data/builtin,并删除原自定义目录。",- "skills.promote_failed_with": "提升为内置失败:{reason}","agents.title": "智能体","agents.create_btn": "+ 创建","agents.more_btn": "更多",@@ -398,8 +395,8 @@"agents.clear_chat_title": "清空当前智能体的对话记录","agents.chat_input_placeholder": "描述需要调整的内容...","agents.unnamed": "未命名",- "agents.source_builtin": "内置","agents.source_custom": "自定义",+ "agents.source_marketplace": "平台","agents.placeholder_unset": "(未填写)","agents.edit_btn_done": "完成","agents.edit_btn_edit": "编辑",@@ -419,9 +416,6 @@"agents.delete_confirm": "确认卸载这个智能体?相关对话会一并删除。","agents.delete_failed": "卸载失败","agents.delete_failed_with": "卸载失败:{reason}",- "agents.promote_to_builtin": "设为内置(开发)",- "agents.promote_confirm": "确认把自定义智能体 \"{name}\" 提升为内置?只复制 agent.json 到 src/builtin 与 data/builtin(meta/ 与自演化 skills/ 会丢弃),并删除原自定义目录。",- "agents.promote_failed_with": "提升为内置失败:{reason}","agents.edit_chat_empty": "跟我说你想怎么调整这个智能体","agents.clear_confirm": "确认清空当前智能体的编辑对话记录?","agents.agent_not_found": "智能体不存在",@@ -628,7 +622,7 @@"settings.section.tools_note": "搜索与图片 API Key 只保存在本机,不上云、不外发。","settings.delete": "删除","settings.search.title": "搜索 API Key",- "settings.search.sub": "优先级:搜索 API > 模型原生搜索 > 内置免费搜索。",+ "settings.search.sub": "优先级:搜索 API > 模型原生搜索 > 本地免费搜索。","settings.search.provider": "服务商","settings.search.api_key": "API Key","settings.search.add": "+ 添加搜索 Key",@@ -638,7 +632,7 @@"settings.search.adding": "添加中…","settings.search.add_ok": "已添加","settings.search.add_failed": "添加失败",- "settings.search.empty": "尚未配置搜索 API Key(将使用内置免费搜索)。",+ "settings.search.empty": "尚未配置搜索 API Key(将使用本地免费搜索)。","settings.search.active_tag": "当前生效","settings.search.confirm_delete": "确认删除 {provider} 的搜索 API Key?","settings.image.title": "图片生成 API Key",@@ -873,7 +867,7 @@"devtools.archives.tools_empty": "(无工具或非新版本存档)","devtools.archives.tools_source_extra": "调用方注入(如群聊 commander 的 plan_set / agent 管理工具)","devtools.archives.tools_source_orkas": "Orkas 注入(覆盖 / 扩展)",- "devtools.archives.tools_source_core_agent": "core-agent 内置",+ "devtools.archives.tools_source_core_agent": "core-agent 随附","agent_modal.title": "新建智能体","agent_modal.tab_create": "创建","agent_modal.tab_external": "外接",@@ -972,6 +966,16 @@"project.action.new_conv": "新对话","project.action.rename": "重命名","project.action.delete": "删除",+ "project.chat.placeholder": "输入 @ 选择智能体、技能、连接器",+ "project.chat.hint": "项目内任务彼此独立,共用项目智能体和文件。",+ "project.files.title": "文件",+ "project.files.add": "添加文件",+ "project.files.empty": "暂无项目文件。",+ "project.files.remove": "移除文件",+ "project.files.uploading": "正在上传...",+ "project.files.upload_failed": "{name} 上传失败:{reason}",+ "project.files.upload_failed_list": "部分文件上传失败:\n{list}",+ "project.files.delete_failed": "删除项目文件失败,请重试","project.bindings.picker_search_placeholder": "按名称或描述搜索","project.bindings.picker_no_match": "没有匹配结果。","agents.no_project_agents": "本项目尚未添加任何智能体。请打开项目页面进行配置。",@@ -991,7 +995,7 @@"project.bindings.candidates_empty_skills": "没有可添加的技能。","project.bindings.stale": "已删除","project.bindings.empty_in_chat": "本项目尚未添加任何智能体。请打开项目页面进行配置。",- "project.bindings.open_settings": "打开项目页面",+ "project.bindings.open_settings": "打开","search.history_title": "搜索历史","search.history_clear": "清空","search.failed": "搜索失败: {msg}",@@ -1010,7 +1014,7 @@"search.scope.agent": "智能体","search.scope.skill": "技能","search.source.custom": "自定义",- "search.source.builtin": "内置",+ "search.source.marketplace": "平台","search.no_results": "未找到「{query}」相关内容","search.role.user": "我","search.role.ai": "AI",diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.jsindex 21d4c6cf..122afabe 100644--- a/src/renderer/modules/agents.js+++ b/src/renderer/modules/agents.js@@ -41,6 +41,18 @@ function _isReservedAgentName(name) {return _RESERVED_AGENT_NAMES.has(key);}+function _agentSource(source) {+ return (typeof normalizeCatalogSource === 'function')+ ? normalizeCatalogSource(source)+ : String(source || '');+}++function _isAgentPlatformSource(source) {+ return (typeof isMarketplaceCatalogSource === 'function')+ ? isMarketplaceCatalogSource(source)+ : _agentSource(source) === 'marketplace';+}+/** Version + category chips for a marketplace-installed agent. Mirrors the* marketplace card footer so users see the same metadata in the agents grid.* `_mpCategoriesCache` is a module-level variable in `marketplace.js` (flat top-level@@ -106,7 +118,10 @@ async function loadAgents(forceRefresh) {// < orkas < 全(q)'). Without this, the backend's listAgents// internal sort (by agent_id, a 12-char nanoid) feels random to// users. The override here fixes that.- _agentsCache = (data.agents || []).slice().sort((a, b) => {+ _agentsCache = (data.agents || []).map((a) => ({+ ...a,+ source: _agentSource(a.source),+ })).sort((a, b) => {if (a.source !== b.source) return a.source === 'custom' ? -1 : 1;const ka = pinyinSortKey(a.name || a.agent_id || '');const kb = pinyinSortKey(b.name || b.agent_id || '');@@ -163,7 +178,7 @@ function renderAgentsList(agents) { renderAgentsGrid(agents); }function renderAgentsGrid(agents) {const custom = agents.filter(a => a.source === 'custom');- const builtin = agents.filter(a => a.source === 'builtin');+ const marketplace = agents.filter(a => _isAgentPlatformSource(a.source));const emptyEl = document.getElementById('agents-empty');const customGroup = document.getElementById('agents-grid-custom-group');const builtinGroup = document.getElementById('agents-grid-builtin-group');@@ -198,7 +213,7 @@ function renderAgentsGrid(agents) {// Marketplace-installed (`builtin`) agents carry version + category from _install.json /// agent.json — show them as inline chips so users see "where this came from" without// opening the detail page. Custom agents skip — they have no published version.- const platformChips = a.source === 'builtin' ? _agentPlatformChipsHtml(a) : '';+ const platformChips = _isAgentPlatformSource(a.source) ? _agentPlatformChipsHtml(a) : '';return `<div class="agent-card${enabled ? '' : ' is-disabled'}" data-id="${escapeHtml(a.agent_id)}" data-source="${a.source}"><div class="agent-card-header">@@ -223,7 +238,7 @@ function renderAgentsGrid(agents) {gridEl.innerHTML = list.map(cardHtml).join('');};renderGroup(custom, customGroup, customGrid);- renderGroup(builtin, builtinGroup, builtinGrid);+ renderGroup(marketplace, builtinGroup, builtinGrid);for (const card of document.querySelectorAll('.agent-card')) {const id = card.dataset.id;@@ -379,7 +394,7 @@ window.addEventListener('i18n-change', () => {async function refreshAgentsAfterMarketplaceReconcile() {await loadAgents(true);if (_agentEditing) return;- if (_selectedAgent?.id && _selectedAgent.source === 'builtin') {+ if (_selectedAgent?.id && _isAgentPlatformSource(_selectedAgent.source)) {await selectAgent(_selectedAgent.id);}}@@ -398,6 +413,11 @@ function _renderAgentRowMenuItems(menu, agentId) {// Dev-only entry on builtin: tag the label so the user knows this isn't a// normal user capability (mirrors marketplace.upload's "(dev)" treatment).const editLabelSuffix = (a?.source === 'builtin' && false) ? t('common.dev_suffix') : '';+ // Dev mode lifts the source guard for marketplace edit / delete.+ const canEdit = isCustom || (_isAgentPlatformSource(a?.source) && false);+ // Dev-only entry on builtin: tag the label so the user knows this isn't a+ // normal user capability (mirrors marketplace.upload's "(dev)" treatment).+ const editLabelSuffix = (_isAgentPlatformSource(a?.source) && false) ? t('common.dev_suffix') : '';const toggleLabel = enabled ? t('component.disable') : t('component.enable');const items = [];if (canEdit) {@@ -468,6 +488,7 @@ async function selectAgent(agentId) {const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}`);const data = await res.json();if (!data.ok || !data.agent) return;+ data.agent.source = _agentSource(data.agent.source);_selectedAgent = { id: data.agent.agent_id, name: data.agent.name, source: data.agent.source };_renderAgentDetail(data.agent, false);// Reset every nested scroll container — `.agents-detail-content` and@@ -490,7 +511,7 @@ async function selectAgent(agentId) {// `agents.js::_renderAgentDetail` and `skills.js::useSkill`. Two forms:// - custom item: single "自定义" chip (kept for symmetry with prior chrome)// - marketplace-installed item: category chip, without author uid / official tags-// `item.source` distinguishes custom vs marketplace-installed; `item.category` (code) maps+ // `item.source` distinguishes custom vs marketplace-installed; `item.category` (code) maps// to display name via `_mpCategoriesCache` (loaded at marketplace boot, hot in localStorage).function _renderSourceMetaHtml(item) {if (!item) return '';@@ -509,6 +530,7 @@ function _renderSourceMetaHtml(item) {}function _renderAgentDetail(agent, editing) {+ agent = { ...agent, source: _agentSource(agent.source) };document.getElementById('agents-detail-content').style.display = '';const nameEl = document.getElementById('agents-detail-name');@@ -518,8 +540,7 @@ function _renderAgentDetail(agent, editing) {const editBtn = document.getElementById('agent-edit-btn');nameEl.textContent = agent.name || '';- // Header chips: custom = single "自定义" tag; marketplace-installed (source=builtin) drops- // the "内置" wording entirely and shows category only, without author uid / official tags.+ // Header chips: custom = single "自定义" tag; marketplace-installed items show category only.sourceEl.innerHTML = _renderSourceMetaHtml(agent);// Runtime slot lives at the top of the body now (not the header):// an always-editable dropdown so the user can flip Orkas ↔ local CLI@@ -550,6 +571,8 @@ function _renderAgentDetail(agent, editing) {if (!editing && !localizedDesc) descEl.innerHTML = unsetHtml;// Detail header actions, fixed order: use (icon) / edit / enable-disable / delete.+ // Detail header actions, fixed order:+ // use (icon) / edit / enable-disable / delete// Edit mode hides everything except the "done" button (the relabeled// "edit" button).const useBtn = document.getElementById('agent-use-btn');@@ -564,15 +587,22 @@ function _renderAgentDetail(agent, editing) {if (enableBtn) enableBtn.style.display = editing ? 'none' : '';if (promoteBtn) promoteBtn.style.display = (isCustom && false && !editing) ? '' : 'none';+ const uploadBtn = document.getElementById('agent-upload-marketplace-btn');+ const delBtn = document.getElementById('agent-delete-btn');+ const isCustom = agent.source === 'custom';+ const canEdit = isCustom || (_isAgentPlatformSource(agent.source) && false);+ if (useBtn) useBtn.style.display = editing ? 'none' : '';+ if (enableBtn) enableBtn.style.display = editing ? 'none' : '';// Upload button visibility: gated by marketplace_dev.js's presence (OrkasOpen lacks it).if (uploadBtn) uploadBtn.style.display = (typeof openMarketplaceUpload === 'function' && !editing) ? '' : 'none';if (delBtn) delBtn.style.display = (canEdit && !editing) ? '' : 'none';if (editBtn) {editBtn.style.display = canEdit ? '' : 'none';- // Tag the "Edit" label on builtin agents (dev-only entry); "Done" stays+ // Tag the "Edit" label on marketplace agents (dev-only entry); "Done" stays// bare because the user is already in edit mode and the marker would be// redundant noise.const editSuffix = (!editing && agent.source === 'builtin' && false) ? t('common.dev_suffix') : '';+ const editSuffix = (!editing && _isAgentPlatformSource(agent.source) && false) ? t('common.dev_suffix') : '';editBtn.textContent = editing ? t('agents.edit_btn_done') : (t('agents.edit_btn_edit') + editSuffix);}_renderAgentEnabledButton({ id: agent.agent_id, enabled: agent.enabled !== false });@@ -602,6 +632,7 @@ function _renderAgentOutputFormatSection(agent) {const canEdit = agent.source === 'custom'|| (agent.source === 'builtin' && typeof isDevMode === 'function' && false);|| (agent.source === 'builtin' && typeof isDevMode === 'function' && false);+ || (_isAgentPlatformSource(agent.source) && typeof isDevMode === 'function' && false);slot.innerHTML = '';const mount = document.createElement('div');@@ -862,6 +893,7 @@ async function _renderAgentDetailProjectDir(agent) {const canEdit = agent.source === 'custom'|| (agent.source === 'builtin' && typeof isDevMode === 'function' && false);+ || (_isAgentPlatformSource(agent.source) && typeof isDevMode === 'function' && false);const renderInfo = (info) => {if (_selectedAgent?.id !== agent.agent_id || slot.dataset.agentId !== agent.agent_id) return;@@ -1021,6 +1053,8 @@ function _toggleAgentFieldEditable(on) {async function toggleAgentEditMode() {if (!_selectedAgent) return;if (_selectedAgent.source === 'builtin') return;+ // Marketplace editing is dev-only; lift the source guard accordingly.+ if (_isAgentPlatformSource(_selectedAgent.source) && !false) return;if (_agentEditing) {await _exitAgentEditMode();} else {@@ -1087,7 +1121,7 @@ function _bindAgentFieldSave() {}function _scheduleAgentFieldSave(field, value) {- if (!_selectedAgent || _selectedAgent.source === 'builtin') return;+ if (!_selectedAgent || _isAgentPlatformSource(_selectedAgent.source)) return;_pendingAgentField = { field, value };clearTimeout(_agentFieldSaveTimer);_agentFieldSaveTimer = setTimeout(_flushAgentFieldSave, 800);@@ -1482,12 +1516,18 @@ async function _autoSendAgentChat(content) {async function deleteSelectedAgent() {if (!_selectedAgent || _selectedAgent.source === 'builtin') return;+ if (!_selectedAgent) return;+ const isMarketplace = _isAgentPlatformSource(_selectedAgent.source);+ if (isMarketplace && !false) return;if (!(await uiConfirm(t('agents.delete_confirm')))) return;const agentId = _selectedAgent.id;try {const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}`,{ method: 'DELETE' });const data = await res.json();+ const data = isMarketplace+ ? await window.orkas.invoke('agents.builtin.delete', { agent_id: agentId })+ : await (await apiFetch(`/api/agents/${encodeURIComponent(agentId)}`, { method: 'DELETE' })).json();if (!data.ok) throw new Error(data.error || t('agents.delete_failed'));_selectedAgent = null; _agentEditing = false;document.getElementById('agents-chat-col').style.display = 'none';@@ -1760,6 +1800,9 @@ function _resolveActiveProjectId(anchorId) {if (anchorId === 'new-chat-recipient-chip') {return (typeof getCommanderProjectId === 'function') ? getCommanderProjectId() : '';}+ if (anchorId === 'project-chat-recipient-chip') {+ return (typeof _projectDetailPid !== 'undefined') ? (_projectDetailPid || '') : '';+ }if (anchorId === 'chat-recipient-chip') {if (typeof currentCid !== 'undefined' && currentCid&& typeof conversations !== 'undefined' && Array.isArray(conversations)) {@@ -1867,15 +1910,17 @@ function _renderAgentPickerList(filterText) {: agents;// Recipient chip exposes "commander" as a virtual top entry so the user can// switch back without an empty-state. Other anchors keep agent-only listing.- const isRecipientPicker = anchorId === 'chat-recipient-chip' || anchorId === 'new-chat-recipient-chip';+ const isRecipientPicker = anchorId === 'chat-recipient-chip'+ || anchorId === 'new-chat-recipient-chip'+ || anchorId === 'project-chat-recipient-chip';const commanderName = t('chat.recipient_commander');const commanderMatchesFilter = !q || commanderName.toLowerCase().includes(q);if (!filtered.length && !(isRecipientPicker && commanderMatchesFilter)) {listEl.innerHTML = `<div class="skill-picker-empty">${escapeHtml(t('agents.no_match'))}</div>`;return;}- const groups = { custom: [], builtin: [] };- for (const a of filtered) (groups[a.source] || groups.custom).push(a);+ const groups = { custom: [], marketplace: [] };+ for (const a of filtered) (groups[_agentSource(a.source)] || groups.custom).push(a);const groupHtml = (label, list) => {if (!list.length) return '';return `<div class="skill-picker-group-label">${escapeHtml(label)}</div>` +@@ -1902,7 +1947,9 @@ function _renderAgentPickerList(filterText) {const projectEmptyHint = (!q && _pickerBoundAgentIds && _pickerBoundAgentIds.size === 0)? `<div class="skill-picker-empty-hint">${escapeHtml(t('agents.no_project_agents'))}</div>`: '';- listEl.innerHTML = projectEmptyHint + commanderHtml + groupHtml(t('agents.source_custom'), groups.custom) + groupHtml(t('agents.source_builtin'), groups.builtin);+ listEl.innerHTML = projectEmptyHint + commanderHtml+ + groupHtml(t('agents.source_custom'), groups.custom)+ + groupHtml(t('agents.source_marketplace'), groups.marketplace);_bindAgentPickerListItems(listEl, anchorId);}@@ -1935,8 +1982,11 @@ function _renderSkillPickerList(listEl, filterText, anchorId) {listEl.innerHTML = `<div class="skill-picker-empty">${escapeHtml(t('skills.no_match'))}</div>`;return;}- const groups = { custom: [], builtin: [] };- for (const s of filtered) (groups[s.source] || groups.custom).push(s);+ const groups = { custom: [], marketplace: [] };+ for (const s of filtered) {+ const source = (typeof normalizeCatalogSource === 'function') ? normalizeCatalogSource(s.source) : s.source;+ (groups[source] || groups.custom).push(s);+ }const groupHtml = (label, list) => {if (!list.length) return '';return `<div class="skill-picker-group-label">${escapeHtml(label)}</div>` +@@ -1950,7 +2000,8 @@ function _renderSkillPickerList(listEl, filterText, anchorId) {</div>`;}).join('');};- listEl.innerHTML = groupHtml(t('skills.source_custom'), groups.custom) + groupHtml(t('skills.source_builtin'), groups.builtin);+ listEl.innerHTML = groupHtml(t('skills.source_custom'), groups.custom)+ + groupHtml(t('skills.source_marketplace'), groups.marketplace);_bindAgentPickerListItems(listEl, anchorId);}@@ -2021,7 +2072,9 @@ function _moveAgentPickerActive(delta) {}function _targetFromPickerAnchor(anchorId) {- return anchorId === 'new-chat-recipient-chip' ? 'new-chat' : 'conversation';+ if (anchorId === 'new-chat-recipient-chip') return 'new-chat';+ if (anchorId === 'project-chat-recipient-chip') return 'project';+ return 'conversation';}async function _triggerPickerItem(kind, itemId, itemName, anchorId) {@@ -2029,14 +2082,14 @@ async function _triggerPickerItem(kind, itemId, itemName, anchorId) {if (kind === 'skill') {setChatSkill(target, itemName || itemId);_consumeAtKeyChar();- const inputId = target === 'new-chat' ? 'new-chat-input' : 'chat-input';+ const inputId = target === 'new-chat' ? 'new-chat-input' : (target === 'project' ? 'project-chat-input' : 'chat-input');_focusInput(document.getElementById(inputId));return;}if (kind === 'connector') {setChatConnector(target, itemId, itemName || itemId);_consumeAtKeyChar();- const inputId = target === 'new-chat' ? 'new-chat-input' : 'chat-input';+ const inputId = target === 'new-chat' ? 'new-chat-input' : (target === 'project' ? 'project-chat-input' : 'chat-input');_focusInput(document.getElementById(inputId));return;}@@ -2048,9 +2101,11 @@ async function _triggerPickerItem(kind, itemId, itemName, anchorId) {// - recipient chip / @ picker → update the persistent recipient chip.// - other anchors → spin up a fresh conversation for that agent.async function _triggerAgent(agentId, agentName, anchorId) {- const isRecipientAnchor = anchorId === 'chat-recipient-chip' || anchorId === 'new-chat-recipient-chip';+ const isRecipientAnchor = anchorId === 'chat-recipient-chip'+ || anchorId === 'new-chat-recipient-chip'+ || anchorId === 'project-chat-recipient-chip';if (isRecipientAnchor) {- const target = anchorId === 'new-chat-recipient-chip' ? 'new-chat' : 'conversation';+ const target = _targetFromPickerAnchor(anchorId);if (agentId === '__commander__') {setChatRecipient(target, { kind: 'commander' });} else {@@ -2060,7 +2115,7 @@ async function _triggerAgent(agentId, agentName, anchorId) {// `@` is now redundant (the chip carries the recipient) and would also// leak into the sent text — strip it._consumeAtKeyChar();- const inputId = target === 'new-chat' ? 'new-chat-input' : 'chat-input';+ const inputId = target === 'new-chat' ? 'new-chat-input' : (target === 'project' ? 'project-chat-input' : 'chat-input');_focusInput(document.getElementById(inputId));return;}@@ -2125,7 +2180,7 @@ function bindAgentPickers() {if (active) { active.click(); e.preventDefault(); }}});- for (const id of ['chat-recipient-chip', 'new-chat-recipient-chip']) {+ for (const id of ['chat-recipient-chip', 'new-chat-recipient-chip', 'project-chat-recipient-chip']) {const btn = document.getElementById(id);if (!btn || btn.dataset.bound === '1') continue;btn.dataset.bound = '1';@@ -2198,6 +2253,12 @@ function bindAgentPickers() {chatInput.addEventListener('keydown', onAtKey('chat-recipient-chip'));chatInput.addEventListener('keydown', onBackspaceMention);}+ const projectChatInput = document.getElementById('project-chat-input');+ if (projectChatInput && !projectChatInput.dataset.atBound) {+ projectChatInput.dataset.atBound = '1';+ projectChatInput.addEventListener('keydown', onAtKey('project-chat-recipient-chip'));+ projectChatInput.addEventListener('keydown', onBackspaceMention);+ }// One global click handler is enough — guard with a flag on the picker.const picker = document.getElementById('agent-picker');if (picker && !picker.dataset.outsideBound) {diff --git a/src/renderer/modules/auto-title.js b/src/renderer/modules/auto-title.jsnew file mode 100644index 00000000..7119ad96--- /dev/null+++ b/src/renderer/modules/auto-title.js@@ -0,0 +1,50 @@+// Heuristic conversation auto-title — mirror of `src/main/util/auto-title.ts`.+//+// Defined as a top-level renderer module so `_autoTitle` is a global available+// to consumers in `agents.js` / `conversation.js` / `project-detail.js` once+// `<script src="./modules/auto-title.js">` runs. Renderer rules (PC/CLAUDE.md+// §8) forbid `import`/`export` in renderer files; the regex/constant pair+// stays duplicated on this side by design.+//+// Drift between this file and `src/main/util/auto-title.ts` is caught by+// `test/renderer/auto-title-parity.test.ts` (asserts regex.source/flags ++// TITLE_MAX). Add a new filler? Update BOTH sides + the parity fixture set.+//+// CJS bridge at the bottom: §9 escape so the parity test can `require()` the+// constants directly. No-op in the browser (`module` is undefined).++const _AUTO_TITLE_ZH_FILLER = /^(帮我看一下|可不可以|帮我看下|帮我看看|麻烦你|帮我看|我想要|想问问|能不能|可以不|可以吗|请帮我|看一下|麻烦|帮我|我想|想问|请问|看下|看看)\s*/;+const _AUTO_TITLE_EN_FILLER = /^(could you|would you|can you|help me|i'?d like to|i want to|please)\s+/i;+const _AUTO_TITLE_CLAUSE = /[,。?!;;,.?!]/;+const _AUTO_TITLE_MAX = 30;++/** Returns the auto-derived sidebar title for `text`. Empty input → ''+ * (caller is expected to fall back to its own placeholder, typically+ * `t('chat.default_title')`). Backend equivalent: `chats.ts::autoTitle`. */+function _autoTitle(text) {+ const raw = String(text == null ? '' : text).trim().replace(/\s+/g, ' ');+ if (!raw) return '';+ let s = raw;+ for (let i = 0; i < 5; i++) {+ const before = s;+ s = s.replace(_AUTO_TITLE_ZH_FILLER, '').replace(_AUTO_TITLE_EN_FILLER, '');+ if (s === before) break;+ }+ s = s.trim();+ const clauseIdx = s.search(_AUTO_TITLE_CLAUSE);+ if (clauseIdx >= 4) s = s.slice(0, clauseIdx);+ s = s.trim();+ if (!s) s = raw;+ if (s.length > _AUTO_TITLE_MAX) s = s.slice(0, _AUTO_TITLE_MAX) + '…';+ return s;+}++if (typeof module !== 'undefined' && typeof module.exports === 'object') {+ module.exports = {+ _autoTitle,+ _AUTO_TITLE_ZH_FILLER,+ _AUTO_TITLE_EN_FILLER,+ _AUTO_TITLE_CLAUSE,+ _AUTO_TITLE_MAX,+ };+}diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.jsindex f32751a7..cc2e6df0 100644--- a/src/renderer/modules/boot.js+++ b/src/renderer/modules/boot.js@@ -256,4 +256,5 @@ function setView(view, cid, opts = {}) {} else {currentCid = null;}+ if (typeof renderProjectsSection === 'function') renderProjectsSection();}diff --git a/src/renderer/modules/chat-file-viewer.js b/src/renderer/modules/chat-file-viewer.jsindex 20e2871a..375b4b70 100644--- a/src/renderer/modules/chat-file-viewer.js+++ b/src/renderer/modules/chat-file-viewer.js@@ -10,8 +10,12 @@// video (.mp4/.webm/.mov/.m4v/.ogv) → <video controls>// pdf (.pdf) → <iframe> + Chromium PDFium// html (.html/.htm) → sandbox="allow-scripts" iframe-// md (.md/.markdown) → renderMarkdown(text) in a <div>-// text (.txt/.json/.csv/.code…) → <pre> with the source+// md (.md/.markdown) → mountMdViewEdit (markdown toolbar+// only fires here — that's the+// contract the markdown editor+// carries that text files don't)+// text (.txt/.json/.csv/.code…) → mountTextViewEdit (<pre> view ++// plain textarea edit, no toolbar)// else → uiConfirm "Open the folder?"//// chat-media://local/<abs> serves pdf/html bytes (streamed via@@ -34,14 +38,24 @@// opts.cid — pass through when the file is a per-conv attachment, so// main can include the cid's attachment dir in the reveal /// read scope. Workspace-only paths can omit it.+// opts.projectId — pass through when the file belongs to a project file+// pool so reveal / text preview can include that scope.let _viewerEl = null;let _viewerBody = null;let _viewerTitle = null;let _viewerRevealBtn = null;+let _viewerMdActions = null;let _viewerKeyHandler = null;let _viewerCurrentPath = null;let _viewerCurrentCid = null;+let _viewerCurrentProjectId = null;+// Active view/edit controller — md (mountMdViewEdit) or text+// (mountTextViewEdit). Both expose the same shape (`destroy / isDirty /+// getMode / setMode`), so the close path can teardown without branching.+let _viewerEditController = null;+let _viewerDirty = false;+let _viewerRenderSeq = 0;const _viewerLog = (typeof createLogger === 'function')? createLogger('chat-file-viewer')@@ -132,6 +146,7 @@ function _ensureViewer() {<div class="chat-file-viewer-header"><span class="chat-file-viewer-title"></span><div class="chat-file-viewer-actions">+ <div class="chat-file-viewer-md-actions"></div><button type="button" class="chat-file-viewer-reveal" aria-label="${revealLabel}" title="${revealLabel}">${folderIcon}</button><button type="button" class="chat-file-viewer-close" aria-label="${closeLabel}" title="${closeLabel}">×</button></div>@@ -145,6 +160,7 @@ function _ensureViewer() {_viewerBody = root.querySelector('.chat-file-viewer-body');_viewerTitle = root.querySelector('.chat-file-viewer-title');_viewerRevealBtn = root.querySelector('.chat-file-viewer-reveal');+ _viewerMdActions = root.querySelector('.chat-file-viewer-md-actions');// i18n change → re-label the icon-only buttons. Same lazy listener pattern// as chat-lightbox; the singleton is created on first open so the@@ -166,12 +182,35 @@ function _ensureViewer() {return root;}+function _confirmDiscardViewerEdits() {+ if (!_viewerDirty) return true;+ return window.confirm(_viewerLabel('chat.md_drawer.close_confirm', 'Discard unsaved changes?'));+}++function _teardownViewerContent() {+ if (_viewerEditController) {+ try { _viewerEditController.destroy(); }+ catch (err) { _viewerLog.warn('edit controller destroy threw', err); }+ }+ _viewerEditController = null;+ _viewerDirty = false;+ if (_viewerBody) _viewerBody.innerHTML = '';+ if (_viewerMdActions) _viewerMdActions.innerHTML = '';+ if (_viewerEl) _viewerEl.classList.remove('is-markdown', 'is-text');+}++function _typesetViewerMarkdown() {+ if (typeof typesetMath !== 'function' || !_viewerBody) return;+ try { typesetMath(_viewerBody); } catch (_) { /* non-fatal */ }+}+async function _onRevealClick() {const p = _viewerCurrentPath;if (!p) return;try {const payload = { path: p };if (_viewerCurrentCid) payload.cid = _viewerCurrentCid;+ if (_viewerCurrentProjectId) payload.projectId = _viewerCurrentProjectId;const res = await window.orkas.invoke('workspace.revealPath', payload);if (!res || !res.ok) {_viewerLog.warn('reveal failed', { path: p, error: res && res.error });@@ -181,10 +220,24 @@ async function _onRevealClick() {}}-function _openViewerShell(displayName) {+function _openViewerShell(displayName, opts) {const el = _ensureViewer();+ if (!_confirmDiscardViewerEdits()) return null;+ _teardownViewerContent();+ _viewerRenderSeq += 1;+ const absPath = opts && opts.absPath;+ const cid = (opts && opts.cid) || null;+ const projectId = (opts && opts.projectId) || null;+ _viewerCurrentPath = absPath || null;+ _viewerCurrentCid = cid;+ _viewerCurrentProjectId = projectId;_viewerTitle.textContent = displayName || '';- _viewerBody.innerHTML = '';+ // `is-markdown` / `is-text` switch the body to a flex column so an editor+ // textarea can fill the available height. View-mode `<pre>` and view-mode+ // markdown both rely on this same layout — see style.css §chat-file-viewer+ // for the per-class rules.+ if (opts && opts.kind === 'markdown') el.classList.add('is-markdown');+ if (opts && opts.kind === 'text') el.classList.add('is-text');el.classList.add('is-open');el.setAttribute('aria-hidden', 'false');if (!_viewerKeyHandler) {@@ -192,41 +245,48 @@ function _openViewerShell(displayName) {if (!_isViewerOpen()) return;// IME guard: Esc commits IME composition cancel — don't double-fire close.if (e.isComposing || e.keyCode === 229) return;+ const active = document.activeElement;+ if (active && active.tagName === 'TEXTAREA' && active.closest('.chat-file-viewer')) return;if (e.key === 'Escape') closeChatFileViewer();};document.addEventListener('keydown', _viewerKeyHandler);}- return el;+ return _viewerRenderSeq;}-function closeChatFileViewer() {+function closeChatFileViewer(opts) {if (!_viewerEl) return;+ const force = !!(opts && opts.force);+ if (!force && !_confirmDiscardViewerEdits()) return false;+ _viewerRenderSeq += 1;_viewerEl.classList.remove('is-open');_viewerEl.setAttribute('aria-hidden', 'true');// Drop iframe / blob src so big preview docs can be GC'd promptly when// the user closes the overlay. Without this, hidden iframes keep the// PDFium / HTML document alive in memory until the next reopen.- if (_viewerBody) _viewerBody.innerHTML = '';+ _teardownViewerContent();_viewerCurrentPath = null;_viewerCurrentCid = null;+ _viewerCurrentProjectId = null;if (_viewerKeyHandler) {document.removeEventListener('keydown', _viewerKeyHandler);_viewerKeyHandler = null;}+ return true;}// ── Per-kind body builders ───────────────────────────────────────────────-function _renderPdfBody(absPath, displayName) {- _openViewerShell(displayName);+function _renderPdfBody(absPath, displayName, cid, projectId) {+ if (!_openViewerShell(displayName, { kind: 'pdf', absPath, cid, projectId })) return;const url = _chatMediaLocalUrl(absPath);// `#toolbar=1&navpanes=0` are Chromium PDFium control hints (keep toolbar,// hide left sidebar). Same pattern as the KB context PDF viewer._viewerBody.innerHTML = `<iframe class="chat-file-viewer-pdf" src="${url}#toolbar=1&navpanes=0" title="${escapeHtml(displayName || '')}"></iframe>`;}-function _renderHtmlBody(absPath, displayName) {- _openViewerShell(displayName);+function _renderHtmlBody(absPath, displayName, cid, projectId) {+ if (!_openViewerShell(displayName, { kind: 'html', absPath, cid, projectId })) return;const url = _chatMediaLocalUrl(absPath);// sandbox: allow-scripts ONLY. chat-media:// is a distinct origin from// file://, so SOP blocks parent.* access; we additionally forbid@@ -238,47 +298,88 @@ function _renderHtmlBody(absPath, displayName) {_viewerBody.innerHTML = `<iframe class="chat-file-viewer-html" sandbox="${sandbox}" src="${url}" title="${escapeHtml(displayName || '')}"></iframe>`;}-function _renderVideoBody(absPath, displayName) {- _openViewerShell(displayName);+function _renderVideoBody(absPath, displayName, cid, projectId) {+ if (!_openViewerShell(displayName, { kind: 'video', absPath, cid, projectId })) return;const url = _chatMediaLocalUrl(absPath);_viewerBody.innerHTML = `<div class="chat-file-viewer-video-wrap"><video class="chat-file-viewer-video" controls preload="metadata" src="${url}"></video></div>`;}-async function _renderMarkdownBody(absPath, displayName, cid) {- _openViewerShell(displayName);+async function _renderMarkdownBody(absPath, displayName, cid, projectId) {+ const seq = _openViewerShell(displayName, { kind: 'markdown', absPath, cid, projectId });+ if (!seq) return;_viewerBody.innerHTML = `<div class="chat-file-viewer-loading">…</div>`;- const text = await _readTextFile(absPath, cid);- if (text === null) return; // _readTextFile already routed to the fallback dialog- // renderMarkdown is the single markdown surface; matches chat bubbles so- // generated reports look identical here and inline.- const md = (typeof renderMarkdown === 'function') ? renderMarkdown(text) : escapeHtml(text);- _viewerBody.innerHTML = `<div class="chat-file-viewer-md">${md}</div>`;- // Same async LaTeX typeset chat bubbles use. Skipped silently if math.js- // isn't loaded (e.g. tests).- if (typeof typesetMath === 'function') {- try { typesetMath(_viewerBody); } catch (_) { /* non-fatal */ }+ const text = await _readTextFile(absPath, cid, projectId, seq);+ if (text === null || seq !== _viewerRenderSeq || !_isViewerOpen()) return; // _readTextFile already routed to the fallback dialog+ if (typeof mountMdViewEdit !== 'function') {+ _viewerLog.warn('mountMdViewEdit missing; falling back to read-only markdown preview');+ const md = (typeof renderMarkdown === 'function') ? renderMarkdown(text) : escapeHtml(text);+ _viewerBody.innerHTML = `<div class="chat-file-viewer-md">${md}</div>`;+ _typesetViewerMarkdown();+ return;}+ _viewerEditController = mountMdViewEdit({+ bodyEl: _viewerBody,+ actionsEl: _viewerMdActions,+ source: { kind: 'workspace', absPath, cid: cid || undefined, projectId: projectId || undefined },+ capabilities: projectId+ ? { edit: false, save: false, delete: false, reveal: false, taskCheckbox: false }+ : { reveal: false, delete: false },+ initialMode: 'view',+ initialContent: text,+ actionIconOnly: true,+ callbacks: {+ onDirtyChange: (dirty) => { _viewerDirty = !!dirty; },+ onSaved: () => _typesetViewerMarkdown(),+ },+ });+ _typesetViewerMarkdown();}-async function _renderTextBody(absPath, displayName, cid) {- _openViewerShell(displayName);+async function _renderTextBody(absPath, displayName, cid, projectId) {+ const seq = _openViewerShell(displayName, { kind: 'text', absPath, cid, projectId });+ if (!seq) return;_viewerBody.innerHTML = `<div class="chat-file-viewer-loading">…</div>`;- const text = await _readTextFile(absPath, cid);- if (text === null) return;- _viewerBody.innerHTML = `<pre class="chat-file-viewer-text">${escapeHtml(text)}</pre>`;+ // Pre-fetch via _readTextFile so the too_large / read-failure path falls+ // back to the "open the folder?" dialog (same UX as the read-only path+ // before). On success, hand the text to mountTextViewEdit; it owns the+ // view ↔ edit transitions, save IPC, and dirty tracking from there.+ const text = await _readTextFile(absPath, cid, projectId, seq);+ if (text === null || seq !== _viewerRenderSeq || !_isViewerOpen()) return;+ if (typeof mountTextViewEdit !== 'function') {+ _viewerLog.warn('mountTextViewEdit missing; falling back to read-only text preview');+ _viewerBody.innerHTML = `<pre class="chat-file-viewer-text">${escapeHtml(text)}</pre>`;+ return;+ }+ _viewerEditController = mountTextViewEdit({+ bodyEl: _viewerBody,+ actionsEl: _viewerMdActions,+ source: { absPath, cid: cid || undefined, projectId: projectId || undefined },+ // Project files are read-only by design (the LLM owns project workspace+ // mutations); workspace / per-conv attachments allow edit + save.+ capabilities: projectId ? { edit: false, save: false } : { edit: true, save: true },+ initialMode: 'view',+ initialContent: text,+ actionIconOnly: true,+ callbacks: {+ onDirtyChange: (dirty) => { _viewerDirty = !!dirty; },+ },+ });}// Fetch a file's text via IPC. Returns the text on success; on rejection// surfaces the fallback dialog (and returns null so the caller knows to// stop). Closes the overlay before showing the dialog so it doesn't stack// on top of a half-built viewer.-async function _readTextFile(absPath, cid) {+async function _readTextFile(absPath, cid, projectId, seq) {_viewerCurrentPath = absPath;_viewerCurrentCid = cid || null;+ _viewerCurrentProjectId = projectId || null;try {const payload = { path: absPath };if (cid) payload.cid = cid;+ if (projectId) payload.projectId = projectId;const res = await window.orkas.invoke('produced.readText', payload);+ if (seq && seq !== _viewerRenderSeq) return null;if (res && res.ok) return String(res.text || '');// Specifically distinguish too_large so the user sees "file is X MB,// open in folder?" instead of a generic failure.@@ -287,13 +388,13 @@ async function _readTextFile(absPath, cid) {if (err === 'too_large') {const sizeMb = ((res && res.size) || 0) / 1024 / 1024;const capMb = ((res && res.cap) || 2 * 1024 * 1024) / 1024 / 1024;- await _showUnsupportedDialog(absPath, cid, {+ await _showUnsupportedDialog(absPath, cid, projectId, {messageKey: 'chat.preview_too_large_message',vars: { name: absPath.split(/[\\/]/).pop() || absPath, size: sizeMb.toFixed(1), cap: capMb.toFixed(0) },fallback: `File is ${sizeMb.toFixed(1)} MB (over the ${capMb.toFixed(0)} MB preview cap). Open the containing folder?`,});} else {- await _showUnsupportedDialog(absPath, cid, {+ await _showUnsupportedDialog(absPath, cid, projectId, {messageKey: 'chat.preview_read_failed_message',vars: { name: absPath.split(/[\\/]/).pop() || absPath },fallback: 'Could not read this file. Open the containing folder?',@@ -301,9 +402,10 @@ async function _readTextFile(absPath, cid) {}return null;} catch (e) {+ if (seq && seq !== _viewerRenderSeq) return null;_viewerLog.warn('readText threw', { path: absPath, error: String(e && e.message || e) });closeChatFileViewer();- await _showUnsupportedDialog(absPath, cid, {+ await _showUnsupportedDialog(absPath, cid, projectId, {messageKey: 'chat.preview_read_failed_message',vars: { name: absPath.split(/[\\/]/).pop() || absPath },fallback: 'Could not read this file. Open the containing folder?',@@ -315,7 +417,7 @@ async function _readTextFile(absPath, cid) {// Fallback dialog: explain to the user that we can't preview this file// inline, and offer to open the folder it lives in. uiConfirm returns true// on the (relabeled) primary button.-async function _showUnsupportedDialog(absPath, cid, opts) {+async function _showUnsupportedDialog(absPath, cid, projectId, opts) {const name = absPath.split(/[\\/]/).pop() || absPath;const ext = _extOf(name) || _viewerLabel('chat.preview_unsupported_no_ext', '(no extension)');const message = opts && opts.messageKey@@ -343,6 +445,7 @@ async function _showUnsupportedDialog(absPath, cid, opts) {try {const payload = { path: absPath };if (cid) payload.cid = cid;+ if (projectId) payload.projectId = projectId;const res = await window.orkas.invoke('workspace.revealPath', payload);if (!res || !res.ok) _viewerLog.warn('fallback reveal failed', { path: absPath, error: res && res.error });} catch (err) {@@ -355,10 +458,9 @@ async function _showUnsupportedDialog(absPath, cid, opts) {function openChatFileViewer(absPath, displayName, opts) {if (!absPath) return;const cid = (opts && opts.cid) || null;+ const projectId = (opts && opts.projectId) || null;const name = displayName || (absPath.split(/[\\/]/).pop() || absPath);const kind = _kindOf(name);- _viewerCurrentPath = absPath;- _viewerCurrentCid = cid;if (kind === 'image') {// Delegate — the image lightbox already has zoom / pan / keyboard. We@@ -369,13 +471,13 @@ function openChatFileViewer(absPath, displayName, opts) {}return;}- if (kind === 'pdf') return _renderPdfBody(absPath, name);- if (kind === 'video') return _renderVideoBody(absPath, name);- if (kind === 'html') return _renderHtmlBody(absPath, name);- if (kind === 'markdown') return _renderMarkdownBody(absPath, name, cid);- if (kind === 'text') return _renderTextBody(absPath, name, cid);+ if (kind === 'pdf') return _renderPdfBody(absPath, name, cid, projectId);+ if (kind === 'video') return _renderVideoBody(absPath, name, cid, projectId);+ if (kind === 'html') return _renderHtmlBody(absPath, name, cid, projectId);+ if (kind === 'markdown') return _renderMarkdownBody(absPath, name, cid, projectId);+ if (kind === 'text') return _renderTextBody(absPath, name, cid, projectId);// unsupported — go straight to the dialog, never open the shell.- return _showUnsupportedDialog(absPath, cid, {});+ return _showUnsupportedDialog(absPath, cid, projectId, {});}// CJS bridge for vitest — pure functions only, per PC/CLAUDE.md §9.diff --git a/src/renderer/modules/chat-md-drawer.js b/src/renderer/modules/chat-md-drawer.jsindex 7010bb6f..f8e3fb65 100644--- a/src/renderer/modules/chat-md-drawer.js+++ b/src/renderer/modules/chat-md-drawer.js@@ -1,7 +1,7 @@// ─── Right-side markdown drawer for the chat view ───// Hosted next to the main chat history, slides in from the right. Two source// kinds today (defined by mountMdViewEdit):-// workspace — clicked an LLM-produced .md / .markdown file chip+// workspace — a caller explicitly wants a side drawer for a workspace file// ephemeral — context-menu "临时编辑" on a chat selection//// Single-instance: reopening always closes the previous mount. The drawer'sdiff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.jsindex a35f5c21..8e77f148 100644--- a/src/renderer/modules/connectors.js+++ b/src/renderer/modules/connectors.js@@ -1,7 +1,7 @@// Connectors panel — curated OAuth-only catalog of MCP-based integrations.//-// Layout: a single scrollable grid view with two stacked sections — "已连接" (Connected) on top,-// "可用" (Available) below. No tab switching; same shape as the Skills panel's+// Layout: a single scrollable grid view with two stacked sections — connected on top,+// available below. No tab switching; same shape as the Skills panel's// Custom / Built-in split. Both groups hide themselves when empty.//// Click model: only the action buttons on a card are clickable. Clicking elsewhere on a card@@ -9,10 +9,10 @@// click handler was firing OAuth flows by accident. Buttons stop propagation as a defence in// depth.//-// OAuth flow UX: clicking "连接" just opens the system browser and returns control to the+// OAuth flow UX: clicking Connect just opens the system browser and returns control to the// renderer's _runConnect Promise (which the main process resolves once the deep-link callback-// completes). **The card itself does NOT change state during the flow** — no "授权中" badge, no-// disabled button. The user can click "连接" again at any time; server-side startOAuth+// completes). **The card itself does NOT change state during the flow** — no authorizing badge, no+// disabled button. The user can click Connect again at any time; server-side startOAuth// supersedes any prior pending flow, and the renderer surfaces only real errors (the// "superseded" message is swallowed since it's caused by the user's own re-click).@@ -25,7 +25,7 @@ let _connectorsState = {/** Per-card connecting flag. Set when `_runConnect` is in flight (browser-open → deep-link* return → /oauth/exchange → MCP connect → list_tools). Visible only post-return when the* user comes back to PC and the IPC is still running through exchange + MCP setup — without- * this they'd see a static "连接" button with no indication anything is happening. Button+ * this they'd see a static Connect button with no indication anything is happening. Button* stays clickable; re-click supersedes the prior flow (see comment in `_runConnect`). */connecting: new Set(),};@@ -63,7 +63,7 @@ function _deriveBundleInstance(entry) {&& members.every((m) => m.status && m.status.kind === 'connected');const anyErrored = members.find((m) => m.status && m.status.kind === 'error');const accountLabel = members.map((m) => m.oauth_grant && m.oauth_grant.account_label).find(Boolean) || '';- // For enabled: bundle is "enabled" iff every member is enabled (any disabled → show "停用-able").+ // For enabled: bundle is "enabled" iff every member is enabled (any disabled → show Enable).const allEnabled = members.every((m) => m.enabled !== false);return {id: entry.id,@@ -182,12 +182,12 @@ function _renderCatalogCard(entry, instance) {const accountLabel = (instance && instance.oauth_grant && instance.oauth_grant.account_label) || '';const errorMsg = errored && instance && instance.status && instance.status.message;- // ⋯ menu lives on connected cards only — it hosts the destructive "断开" action so it stays+ // The ⋯ menu lives on connected cards only — it hosts the destructive disconnect action so it stays// one click away from accidental triggers. Un-connected / errored cards still surface the- // disconnect action as a bottom-row button (they need it visible to recover; the "停用" toggle+ // disconnect action as a bottom-row button (they need it visible to recover; the disable toggle// doesn't apply when there's nothing to disable).const menuHtml = connected- ? `<button class="connector-card-menu-btn" data-act="menu" aria-label="${escapeHtml(t('common.more') || '⋯')}">⋯</button>`+ ? `<button class="connector-card-menu-btn" data-act="menu" aria-label="${escapeHtml(t('common.more'))}">⋯</button>`: '';// Bottom-row action:@@ -197,10 +197,10 @@ function _renderCatalogCard(entry, instance) {// before `_runConnect`'s `finally` clears the connecting flag, and the user sees// the spinner vanish "the moment they return from the browser" even though the// IPC chain (loadConnectors + grid re-render) is still finishing.- // - connected: 启用 / 停用 toggle (per-user soft switch — hides instance from LLM)- // - errored: 断开 (recover from a stuck error state)- // - oauth_pending: disabled "敬请期待"- // - default (uninstalled): 连接 (start OAuth)+ // - connected: enable / disable toggle (per-user soft switch — hides instance from LLM)+ // - errored: disconnect (recover from a stuck error state)+ // - oauth_pending: disabled unavailable button+ // - default (uninstalled): connect (start OAuth)let action = '';const isConnecting = _connectorsState.connecting && _connectorsState.connecting.has(e.id);if (isConnecting) {@@ -257,7 +257,7 @@ function _renderCatalogCard(entry, instance) {return card;}-// Tiny absolute-positioned popover anchored under the ⋯ button — one item for now ("断开").+// Tiny absolute-positioned popover anchored under the ⋯ button — one disconnect item for now.// Closes on outside click / Esc / window scroll. Keeping it inline so we don't pull in a generic// menu primitive for one use site; if a second connector-card menu item ever lands, refactor.function _openCardMenu(anchorBtn, entry, instance) {@@ -357,7 +357,7 @@ async function _runConnect(entry) {try {const res = await window.orkas.invoke('connectors.start_oauth', { catalog_id: entry.id });if (res && res.ok && res.instance) {- // Refresh state + re-render the grid. The new instance shows up in the "已连接" group.+ // Refresh state + re-render the grid. The new instance shows up in the connected group.await loadConnectors();} else if (res && !res.ok) {const msg = (res.error || '').toLowerCase();diff --git a/src/renderer/modules/conversation-info.js b/src/renderer/modules/conversation-info.jsindex 54e37e7e..3ac649d9 100644--- a/src/renderer/modules/conversation-info.js+++ b/src/renderer/modules/conversation-info.js@@ -1,8 +1,9 @@// ─── Conversation info side panel ───────────────────────────────────────// Right-side companion panel for the active conversation. It summarizes the-// structured plan, produced files, and attachments without adding new backend-// state: everything is derived from the same history / plan / attachment-// endpoints already used by the chat view.+// structured plan, workspace files, and attachments. The file tab reads the+// live conversation workspace first, then merges chip-tracked produced files+// from history so the panel stays aligned with disk even when tools create+// files through bash / CLI flows.const ConversationInfo = (() => {const _infoLog = (typeof createLogger === 'function')@@ -13,12 +14,20 @@ const ConversationInfo = (() => {let _open = false;let _activeTab = 'tasks';let _seq = 0;+ let _taskSeq = 0;+ let _attachmentSeq = 0;let _loading = false;let _error = '';let _snapshot = {conversation: null,history: [],plan: null,+ members: [],+ files: [],+ fileRoot: '',+ fileRootExists: false,+ filesTruncated: false,+ filesCount: 0,attachments: [],};@@ -55,6 +64,19 @@ const ConversationInfo = (() => {.filter(Boolean);}+ function _normalizePath(p) {+ return String(p || '').replace(/\\/g, '/').replace(/\/+/g, '/');+ }++ function _relPathUnder(root, target) {+ const r = _normalizePath(root).replace(/\/+$/, '');+ const t = _normalizePath(target);+ if (!r || !t) return '';+ if (t === r) return '';+ const prefix = r + '/';+ return t.startsWith(prefix) ? t.slice(prefix.length) : '';+ }+function _samePrefix(a, b) {if (!Array.isArray(a) || !Array.isArray(b) || a.length > b.length) return false;for (let i = 0; i < a.length; i++) {@@ -76,8 +98,23 @@ const ConversationInfo = (() => {return common;}+ // One-time warn when the shared icons helpers (`window.fileKindIconHtml` /+ // `window.uiIconHtml`, defined by `modules/icons.js`) are missing — typical+ // cause is an `index.html` script-list refactor that put `icons.js` after a+ // consumer. Without this warn the panel just paints rows without icons,+ // silently degrading; logging once lets DevTools surface the broken load+ // order on the first render attempt. The flag is per-module-lifetime to+ // avoid spamming on every refresh.+ let _warnedIconsMissing = false;+ function _warnIconsHelperMissingOnce(helperName) {+ if (_warnedIconsMissing) return;+ _warnedIconsMissing = true;+ _infoLog.warn(`icons.js helper missing: ${helperName} — check index.html <script> load order`);+ }+function _iconForName(name, kind) {if (typeof window !== 'undefined' && typeof window.fileKindIconHtml === 'function') return window.fileKindIconHtml(name, kind);+ _warnIconsHelperMissingOnce('fileKindIconHtml');return '';}@@ -85,6 +122,7 @@ const ConversationInfo = (() => {if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {return window.uiIconHtml(name, className);}+ _warnIconsHelperMissingOnce('uiIconHtml');return '';}@@ -114,12 +152,20 @@ const ConversationInfo = (() => {async function _load(cid) {const enc = encodeURIComponent(cid);- const [historyData, planData, attachmentData] = await Promise.all([+ const [historyData, planData, memberData, filesData, attachmentData] = await Promise.all([_fetchJson(`/api/conversations/${enc}/history?limit=500`),_fetchJson(`/api/conversations/${enc}/plan`).catch((err) => {_infoLog.warn('plan load failed', { cid, error: err && err.message });return { plan: null };}),+ _fetchJson(`/api/conversations/${enc}/members`).catch((err) => {+ _infoLog.warn('member load failed', { cid, error: err && err.message });+ return { actors: [] };+ }),+ _fetchJson(`/api/conversations/${enc}/files`).catch((err) => {+ _infoLog.warn('file list load failed', { cid, error: err && err.message });+ return { items: [], root: '', rootExists: false, truncated: false, count: 0 };+ }),_fetchJson(`/api/conversations/${enc}/attachments`).catch((err) => {_infoLog.warn('attachment load failed', { cid, error: err && err.message });return { items: [] };@@ -129,10 +175,51 @@ const ConversationInfo = (() => {conversation: historyData.conversation || null,history: Array.isArray(historyData.history) ? historyData.history : [],plan: planData.plan || null,+ members: Array.isArray(memberData.actors) ? memberData.actors : [],+ files: Array.isArray(filesData.items) ? filesData.items : [],+ fileRoot: typeof filesData.root === 'string' ? filesData.root : '',+ fileRootExists: filesData.rootExists === true,+ filesTruncated: filesData.truncated === true,+ filesCount: Number(filesData.count) || 0,attachments: Array.isArray(attachmentData.items) ? attachmentData.items : [],};}+ async function _loadTaskSnapshot(cid) {+ const enc = encodeURIComponent(cid);+ const [historyData, planData, memberData] = await Promise.all([+ _fetchJson(`/api/conversations/${enc}/history?limit=500`),+ _fetchJson(`/api/conversations/${enc}/plan`).catch((err) => {+ _infoLog.warn('plan load failed', { cid, error: err && err.message });+ return { plan: null };+ }),+ _fetchJson(`/api/conversations/${enc}/members`).catch((err) => {+ _infoLog.warn('member load failed', { cid, error: err && err.message });+ return { actors: [] };+ }),+ ]);+ return {+ conversation: historyData.conversation || null,+ history: Array.isArray(historyData.history) ? historyData.history : [],+ plan: planData.plan || null,+ members: Array.isArray(memberData.actors) ? memberData.actors : [],+ };+ }++ function _normalizeAttachmentItems(items) {+ return (Array.isArray(items) ? items : [])+ .filter((item) => item && item.status !== 'error')+ .map((item) => ({+ name: String(item.name || ''),+ displayName: item.displayName ? String(item.displayName) : '',+ kind: item.kind || _kindForName(item.name || item.displayName || ''),+ bytes: Number(item.bytes) || 0,+ mtime: item.mtime,+ status: item.status || '',+ }))+ .filter((item) => item.name);+ }+function _currentConversationTitle() {const c = _snapshot.conversation|| (Array.isArray(conversations) ? conversations.find((x) => x && x.conversation_id === _cid) : null);@@ -149,27 +236,147 @@ const ConversationInfo = (() => {return '';}- function _parseAnnouncementSteps(text) {+ function _normalizeActorKey(value) {+ return String(value || '').trim().replace(/^@+/, '').replace(/\s+/g, '').toLowerCase();+ }++ function _buildMemberLookup(members) {+ const byKey = new Map();+ const add = (key, actor) => {+ const norm = _normalizeActorKey(key);+ if (norm && actor) byKey.set(norm, actor);+ };+ for (const actor of Array.isArray(members) ? members : []) {+ if (!actor || !actor.id) continue;+ add(actor.id, actor);+ add(actor.name, actor);+ }+ add('commander', { id: 'commander', kind: 'commander', name: _label('chat.recipient_commander', 'Commander') });+ add('指挥官', { id: 'commander', kind: 'commander', name: _label('chat.recipient_commander', 'Commander') });+ add('我自己', { id: 'commander', kind: 'commander', name: _label('chat.recipient_commander', 'Commander') });+ add('自己', { id: 'commander', kind: 'commander', name: _label('chat.recipient_commander', 'Commander') });+ add('user', { id: 'user', kind: 'user', name: _label('chat.from_user', 'User') });+ add('用户', { id: 'user', kind: 'user', name: _label('chat.from_user', 'User') });+ return { byKey };+ }++ function _normalizeAssignee(raw, lookup) {+ const ref = String(raw || '').trim().replace(/^@+/, '').trim();+ if (!ref) return '';+ const actor = lookup && lookup.byKey ? lookup.byKey.get(_normalizeActorKey(ref)) : null;+ if (actor && actor.id) return String(actor.id);+ const key = _normalizeActorKey(ref);+ if (key === 'commander' || key === '指挥官' || key === '我自己' || key === '自己') return 'commander';+ if (key === 'user' || key === '用户') return 'user';+ return ref;+ }++ function _parseAnnouncementSteps(text, lookup) {const lines = String(text || '').split(/\r?\n/);const steps = [];for (const line of lines) {const m = line.match(/^\s*(\d+)[\.\)、)]\s+(.+?)\s*$/u);if (!m) continue;const idx = Number(m[1]);- const body = String(m[2] || '').replace(/[((][^))]*[))]\s*$/u, '').trim();+ let body = String(m[2] || '').trim();+ let assignee = '';+ const assigneeMatch = body.match(/[((]([^))]*)[))]\s*$/u);+ if (assigneeMatch) {+ assignee = _normalizeAssignee(assigneeMatch[1], lookup);+ body = body.slice(0, assigneeMatch.index).trim();+ }if (!body) continue;- steps.push({ index: idx, title: body, status: 'pending' });+ steps.push({ index: idx, title: body, status: 'pending', ...(assignee ? { assignee } : {}) });}return steps;}+ function _actorMatches(actorValue, ref, lookup) {+ if (!actorValue || !ref) return false;+ const actor = lookup && lookup.byKey ? lookup.byKey.get(_normalizeActorKey(actorValue)) : null;+ const refActor = lookup && lookup.byKey ? lookup.byKey.get(_normalizeActorKey(ref)) : null;+ const actorId = actor?.id || String(actorValue);+ const refId = refActor?.id || String(ref);+ if (actorId === refId) return true;+ return _normalizeActorKey(actorId) === _normalizeActorKey(refId)+ || _normalizeActorKey(actor?.name) === _normalizeActorKey(ref)+ || _normalizeActorKey(actorValue) === _normalizeActorKey(refActor?.name);+ }++ function _isUserVisibleTurn(m) {+ return !!m && !m.dispatch && !m.plan_announcement && (m.from || m.role);+ }++ function _messageTargetsAssignee(m, assignee, lookup) {+ if (!m || !m.dispatch || !assignee) return false;+ const to = Array.isArray(m.to) ? m.to : [];+ if (to.some((target) => _actorMatches(target, assignee, lookup))) return true;+ const text = String(m.text || m.content || '').trim();+ const mention = text.match(/^@([^\s,,::]+)/u);+ return !!mention && _actorMatches(mention[1], assignee, lookup);+ }++ function _messageCarriesStepIndex(m, step) {+ const idx = Number(step && step.index);+ if (!Number.isFinite(idx)) return false;+ return Number(m && (m.triggered_step ?? m.plan_step_index ?? m.form?.plan_step_index)) === idx;+ }++ function _inferHistoricalSteps(steps, section, lookup) {+ if (!Array.isArray(steps) || !steps.length) return [];+ const usedDispatches = new Set();+ const usedDoneTurns = new Set();+ let previousDoneIdx = -1;+ return steps.map((step) => {+ const assignee = step.assignee || '';+ const explicitIdx = section.findIndex((m) => _messageCarriesStepIndex(m, step));+ const explicitDoneIdx = section.findIndex((m) =>+ _messageCarriesStepIndex(m, step) && _isUserVisibleTurn(m));+ const dispatchIdx = explicitIdx >= 0 ? explicitIdx : section.findIndex((m, idx) =>+ !usedDispatches.has(idx) && _messageTargetsAssignee(m, assignee, lookup));+ let doneIdx = -1;+ if (explicitDoneIdx >= 0) {+ doneIdx = explicitDoneIdx;+ } else if (assignee === 'commander') {+ const start = Math.max(0, previousDoneIdx + 1);+ doneIdx = section.findIndex((m, idx) =>+ idx >= start+ && !usedDoneTurns.has(idx)+ && _isUserVisibleTurn(m)+ && _actorMatches(m.from || m.role, 'commander', lookup));+ } else if (assignee) {+ const start = dispatchIdx >= 0 ? dispatchIdx : Math.max(0, previousDoneIdx + 1);+ doneIdx = section.findIndex((m, idx) =>+ idx >= start+ && !usedDoneTurns.has(idx)+ && _isUserVisibleTurn(m)+ && _actorMatches(m.from || m.role, assignee, lookup));+ }+ if (doneIdx >= 0) {+ usedDoneTurns.add(doneIdx);+ if (dispatchIdx >= 0) usedDispatches.add(dispatchIdx);+ previousDoneIdx = Math.max(previousDoneIdx, doneIdx);+ return { ...step, status: 'done' };+ }+ if (dispatchIdx >= 0) {+ usedDispatches.add(dispatchIdx);+ return { ...step, status: 'in_progress' };+ }+ return step;+ });+ }+function _buildTasks() {const history = _snapshot.history || [];const plan = _snapshot.plan;+ const lookup = _buildMemberLookup(_snapshot.members);const tasks = [];for (let i = 0; i < history.length; i++) {const m = history[i];if (!m || !m.plan_announcement) continue;+ const nextPlanIdx = history.findIndex((next, idx) => idx > i && next && next.plan_announcement);+ const sectionEnd = nextPlanIdx >= 0 ? nextPlanIdx : history.length;+ const parsedSteps = _parseAnnouncementSteps(m.text || m.content || '', lookup);const fallbackTitle = _nearestPriorUserText(history, i - 1)|| _currentConversationTitle()|| _label('conversation_info.task_plan_fallback', 'Execution plan');@@ -177,7 +384,8 @@ const ConversationInfo = (() => {id: `plan-${m.id || i}`,title: fallbackTitle,time: m.ts || m.time || '',- steps: _parseAnnouncementSteps(m.text || m.content || ''),+ steps: _inferHistoricalSteps(parsedSteps, history.slice(i + 1, sectionEnd), lookup),+ _historyIndex: i,current: false,});}@@ -195,13 +403,21 @@ const ConversationInfo = (() => {current: true,};if (tasks.length) {- tasks[tasks.length - 1] = { ...tasks[tasks.length - 1], ...current };+ tasks[tasks.length - 1] = { ...tasks[tasks.length - 1], ...current, _historyIndex: tasks[tasks.length - 1]._historyIndex };} else {tasks.push(current);}}- return tasks.sort((a, b) => new Date(b.time || 0).getTime() - new Date(a.time || 0).getTime());+ return tasks+ .sort((a, b) => {+ const at = new Date(a.time || 0).getTime();+ const bt = new Date(b.time || 0).getTime();+ const timeDiff = (Number.isFinite(bt) ? bt : 0) - (Number.isFinite(at) ? at : 0);+ if (timeDiff !== 0) return timeDiff;+ return (b._historyIndex ?? -1) - (a._historyIndex ?? -1);+ })+ .map(({ _historyIndex, ...task }) => task);}function _statusLabel(status) {@@ -238,7 +454,9 @@ const ConversationInfo = (() => {if (!a) return '';if (a === 'commander') return _label('chat.recipient_commander', 'Commander');if (a === 'user') return _label('chat.from_user', 'User');- return '@' + a;+ const lookup = _buildMemberLookup(_snapshot.members);+ const actor = lookup.byKey.get(_normalizeActorKey(a));+ return '@' + (actor?.name || a);}function _renderStep(step) {@@ -282,7 +500,7 @@ const ConversationInfo = (() => {}).join('')}</div>`;}- function _collectProducedFiles() {+ function _collectHistoryProducedFiles() {const byPath = new Map();for (const m of _snapshot.history || []) {const ts = m && (m.ts || m.time || '');@@ -305,11 +523,60 @@ const ConversationInfo = (() => {return Array.from(byPath.values()).sort((a, b) => String(a.path).localeCompare(String(b.path)));}+ function _collectVisibleFiles() {+ const byPath = new Map();+ const fileRoot = _snapshot.fileRoot || '';+ const workspaceFiles = Array.isArray(_snapshot.files) ? _snapshot.files : [];+ for (const item of workspaceFiles) {+ const p = item && item.path ? String(item.path) : '';+ if (!p) continue;+ const key = _normalizePath(p);+ const relPath = item.relPath ? String(item.relPath) : _relPathUnder(fileRoot, p);+ byPath.set(key, {+ path: p,+ relPath,+ name: item.name || _baseName(p),+ time: item.mtime ? new Date(Number(item.mtime)).toISOString() : '',+ bytes: Number(item.bytes) || 0,+ source: 'workspace',+ });+ }++ const hasAuthoritativeWorkspaceSnapshot = !!fileRoot && _snapshot.fileRootExists === true;+ for (const produced of _collectHistoryProducedFiles()) {+ const p = produced && produced.path ? String(produced.path) : '';+ if (!p) continue;+ const key = _normalizePath(p);+ if (byPath.has(key)) continue;+ const relPath = _relPathUnder(fileRoot, p);+ if (relPath && hasAuthoritativeWorkspaceSnapshot && !_snapshot.filesTruncated) {+ // The workspace snapshot is authoritative for files under its root.+ // If a produced file was deleted or renamed, don't keep showing the+ // stale history record.+ continue;+ }+ byPath.set(key, {+ ...produced,+ relPath,+ name: _baseName(p),+ source: 'produced',+ });+ }++ return Array.from(byPath.values()).sort((a, b) => {+ const ar = a.relPath || a.path || '';+ const br = b.relPath || b.path || '';+ return String(ar).localeCompare(String(br));+ });+ }+function _buildFileTree(files) {const root = { dirs: new Map(), files: [] };- const common = _commonDirSegments(files.map((f) => f.path));+ const hasRelPaths = files.some((f) => f && f.relPath);+ const common = hasRelPaths ? [] : _commonDirSegments(files.map((f) => f.path));for (const file of files) {- const all = _splitPath(file.path);+ const treePath = hasRelPaths ? (file.relPath || _baseName(file.path)) : file.path;+ const all = _splitPath(treePath);const rel = _samePrefix(common, all) ? all.slice(common.length) : all;const parts = rel.length ? rel : [_baseName(file.path)];let node = root;@@ -326,7 +593,7 @@ const ConversationInfo = (() => {const dirs = Array.from(node.dirs.entries()).sort((a, b) => a[0].localeCompare(b[0]));const files = node.files.slice().sort((a, b) => a.name.localeCompare(b.name));const dirHtml = dirs.map(([name, child]) => `- <details class="conversation-info-dir" style="--depth:${depth}" open>+ <details class="conversation-info-dir" style="--depth:${depth}"><summary class="conversation-info-dir-summary"><span class="conversation-info-dir-folder-icon conversation-info-dir-folder-closed">${_uiIcon('folder', 'ui-icon conversation-info-dir-svg-icon')}</span><span class="conversation-info-dir-folder-icon conversation-info-dir-folder-open">${_uiIcon('folder-open', 'ui-icon conversation-info-dir-svg-icon')}</span>@@ -337,7 +604,7 @@ const ConversationInfo = (() => {`).join('');const fileHtml = files.map((file) => `<button type="button" class="conversation-info-file" style="--depth:${depth}"- data-file-path="${escapeHtml(file.path)}" title="${escapeHtml(file.path)}">+ data-file-path="${escapeHtml(file.path)}" draggable="true" title="${escapeHtml(file.path)}"><span class="conversation-info-file-icon">${_iconForName(file.name)}</span><span class="conversation-info-file-name">${escapeHtml(file.name)}</span></button>@@ -346,12 +613,15 @@ const ConversationInfo = (() => {}function _renderFiles() {- const files = _collectProducedFiles();+ const files = _collectVisibleFiles();if (!files.length) {- return `<div class="conversation-info-empty">${escapeHtml(_label('conversation_info.empty_files', 'No generated files yet'))}</div>`;+ return `<div class="conversation-info-empty">${escapeHtml(_label('conversation_info.empty_files', 'No files yet'))}</div>`;}const tree = _buildFileTree(files);- return `<div class="conversation-info-tree">${_renderTreeNode(tree, 0)}</div>`;+ const trunc = _snapshot.filesTruncated+ ? `<div class="conversation-info-empty is-small">${escapeHtml(_label('conversation_info.files_truncated', 'Showing first {count} files', { count: _snapshot.filesCount || files.length }))}</div>`+ : '';+ return `${trunc}<div class="conversation-info-tree">${_renderTreeNode(tree, 0)}</div>`;}function _collectConversationAttachments() {@@ -371,6 +641,7 @@ const ConversationInfo = (() => {if (!name) continue;byName.set(name, {name,+ displayName: item.displayName ? String(item.displayName) : '',kind: item.kind || _kindForName(name),bytes: Number(item.bytes) || 0,time: item.mtime ? new Date(Number(item.mtime) * 1000).toISOString() : '',@@ -392,13 +663,14 @@ const ConversationInfo = (() => {}return `<div class="conversation-info-attachment-list">${items.map((item) => {const name = String(item.name || '');+ const label = String(item.displayName || item.name || '');const size = _formatBytes(item.bytes);const meta = [item.kind || '', size].filter(Boolean).join(' · ');return `- <button type="button" class="conversation-info-attachment" data-attachment-name="${escapeHtml(name)}" title="${escapeHtml(name)}">- <span class="conversation-info-file-icon">${_iconForName(name, item.kind)}</span>+ <button type="button" class="conversation-info-attachment" data-attachment-name="${escapeHtml(name)}" title="${escapeHtml(label)}">+ <span class="conversation-info-file-icon">${_iconForName(label, item.kind)}</span><span class="conversation-info-attachment-main">- <span class="conversation-info-file-name">${escapeHtml(name)}</span>+ <span class="conversation-info-file-name">${escapeHtml(label)}</span>${meta ? `<span class="conversation-info-attachment-meta">${escapeHtml(meta)}</span>` : ''}</span></button>@@ -471,13 +743,65 @@ const ConversationInfo = (() => {}}+ async function refreshAttachments(cid, opts = {}) {+ const target = cid || _cid;+ if (!target || target !== _cid || !_open) return;+ const items = Array.isArray(opts.items) ? _normalizeAttachmentItems(opts.items) : null;+ if (items) {+ _snapshot = { ..._snapshot, attachments: items };+ if (_activeTab === 'attachments') _renderBody();+ return;+ }++ const seq = ++_attachmentSeq;+ try {+ const data = await _fetchJson(`/api/conversations/${encodeURIComponent(target)}/attachments`);+ if (seq !== _attachmentSeq || target !== _cid) return;+ _snapshot = {+ ..._snapshot,+ attachments: Array.isArray(data.items) ? data.items : [],+ };+ if (_activeTab === 'attachments') _renderBody();+ } catch (err) {+ _infoLog.warn('attachment refresh failed', { cid: target, error: err && err.message });+ }+ }++ async function refreshTasks(cid, opts = {}) {+ const target = cid || _cid;+ if (!target || target !== _cid || !_open) return;+ const seq = ++_taskSeq;+ const silent = !!opts.silent;+ if (!silent && _activeTab === 'tasks') {+ _loading = true;+ _error = '';+ _renderBody();+ }+ try {+ const partial = await _loadTaskSnapshot(target);+ if (seq !== _taskSeq || target !== _cid) return;+ _snapshot = { ..._snapshot, ...partial };+ _error = '';+ } catch (err) {+ if (seq !== _taskSeq || target !== _cid) return;+ _error = (err && err.message) || String(err);+ } finally {+ if (seq === _taskSeq && target === _cid) {+ _loading = false;+ if (_activeTab === 'tasks') _renderBody();+ }+ }+ }+function bind(cid) {_cid = cid || null;_open = false;- _snapshot = { conversation: null, history: [], plan: null, attachments: [] };+ _snapshot = { conversation: null, history: [], plan: null, members: [], files: [], fileRoot: '', fileRootExists: false, filesTruncated: false, filesCount: 0, attachments: [] };_error = '';_loading = false;_seq++;+ _taskSeq++;+ _attachmentSeq++;_syncChrome();_renderBody();if (_open && _cid) refresh(_cid);@@ -542,6 +866,18 @@ const ConversationInfo = (() => {_openAttachment(attachment.dataset.attachmentName || '');}});+ body.addEventListener('dragstart', (ev) => {+ const file = ev.target.closest('.conversation-info-file[data-file-path]');+ if (!file || !ev.dataTransfer) return;+ const path = file.dataset.filePath || '';+ if (!path) return;+ const name = (file.querySelector('.conversation-info-file-name')?.textContent || _baseName(path)).trim();+ try {+ ev.dataTransfer.effectAllowed = 'copy';+ ev.dataTransfer.setData('application/x-orkas-file', JSON.stringify({ path, name }));+ ev.dataTransfer.setData('text/plain', path);+ } catch (_) { /* best-effort */ }+ });}_syncChrome();_renderBody();@@ -561,7 +897,8 @@ const ConversationInfo = (() => {bind,unbind,refresh,- refreshAttachments: refresh,+ refreshTasks,+ refreshAttachments,};})();diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.jsindex aac78309..65f79b49 100644--- a/src/renderer/modules/conversation.js+++ b/src/renderer/modules/conversation.js@@ -215,6 +215,8 @@ function _initAllMentionMirrors() {if (chatInput) _initMentionMirror(chatInput);const newChatInput = document.getElementById('new-chat-input');if (newChatInput) _initMentionMirror(newChatInput);+ const projectChatInput = document.getElementById('project-chat-input');+ if (projectChatInput) _initMentionMirror(projectChatInput);}const CHAT_INPUT_RESERVE_FALLBACK = 140;@@ -275,6 +277,7 @@ const _RECIPIENT_LS_KEY = 'chat.recipientByCid';let _recipientByCid = {}; // { [cid]: {kind,id,name} } — agents only; commander = absencelet _newChatRecipient = { ..._COMMANDER }; // ephemeral, reset on view-enterlet _pendingNewChatRecipient = null; // captured at send time, transferred to new cid+let _projectChatRecipient = { ..._COMMANDER }; // ephemeral recipient for project detail composerfunction _loadRecipientMap() {try {@@ -305,6 +308,7 @@ function _normRecipient(next) {function _activeRecipient(target) {if (target === 'new-chat') return _newChatRecipient;+ if (target === 'project') return _projectChatRecipient;if (currentCid && _recipientByCid[currentCid]) return _recipientByCid[currentCid];return _COMMANDER;}@@ -340,6 +344,8 @@ function setChatRecipient(target, next, _opts = {}) {if (!r) return;if (target === 'new-chat') {_newChatRecipient = r;+ } else if (target === 'project') {+ _projectChatRecipient = r;} else if (currentCid) {if (r.kind === 'commander') delete _recipientByCid[currentCid];else _recipientByCid[currentCid] = r;@@ -364,9 +370,11 @@ function _transferNewChatRecipientTo(cid) {}function _renderRecipientChip(target) {- const targets = target ? [target] : ['conversation', 'new-chat'];+ const targets = target ? [target] : ['conversation', 'new-chat', 'project'];for (const tg of targets) {- const id = tg === 'new-chat' ? 'new-chat-recipient-name' : 'chat-recipient-name';+ const id = tg === 'new-chat'+ ? 'new-chat-recipient-name'+ : (tg === 'project' ? 'project-chat-recipient-name' : 'chat-recipient-name');const nameEl = document.getElementById(id);if (!nameEl) continue;const r = _activeRecipient(tg);@@ -496,10 +504,77 @@ function _forgetCidRecipient(cid) {const _autoEvalInflight = new Set(); // cid setconst _latestInFlight = new Map(); // cid → string[] (mirrors state_changed.state.in_flight)const _runtimeRecoveryTimers = new Map(); // cid → timeout id+const _lastGroupWorkEventAt = new Map(); // cid → ms timestamp of process/artifact/assistant message+const _groupObserverCtrls = new Map(); // cid → recovery observer controller+const _groupEventDedupe = new Map(); // cid → recently handled visible group events// cid → most recent interactive agent that produced an end-of-turn message.// Used as Phase 1.5 sticky when there's no plan + nobody in flight (single// agent dispatch via @-mention finished a turn but user hasn't replied yet).const _lastInteractiveTurnAgent = new Map();+const GROUP_EVENT_DEDUPE_LIMIT = 600;++function _groupEventDedupeKey(evData) {+ if (!evData || typeof evData !== 'object') return '';+ if (evData.type === 'message' && evData.msg) {+ const gm = evData.msg;+ if (gm.id) return `message:${gm.id}:${evData.turn_end ? 1 : 0}`;+ return `message:${gm.from || ''}:${gm.to || ''}:${gm.ts || ''}:${(gm.text || '').length}:${evData.turn_end ? 1 : 0}`;+ }+ if (evData.type === 'artifact_created') {+ const artifact = evData.artifact || {};+ if (artifact.id) return `artifact:${evData.actor || artifact.agent_id || ''}:${artifact.id}`;+ }+ if (evData.type === 'process') {+ const actor = String(evData.actor || '');+ const data = evData.data || {};+ if (data.type === 'delta') return '';+ if (data.type === 'progress' && data.text) {+ return `process:progress:${actor}:${String(data.text).slice(0, 500)}`;+ }+ if (data.type === 'event') {+ const evt = data.event || {};+ if (evt.stream === 'assistant') return '';+ const payload = evt.data || {};+ const eventId = payload.id || payload.call_id || payload.tool_call_id || payload.request_id || '';+ const phase = payload.phase || payload.status || payload.type || '';+ const name = payload.name || payload.tool || payload.command || '';+ if (eventId || phase || name) {+ return `process:event:${actor}:${evt.stream || ''}:${eventId}:${phase}:${name}`;+ }+ }+ }+ return '';+}++// Mirror of the carve-outs in `_groupEventDedupeKey`: text-streaming events+// (per-token deltas and assistant-stream chunks) carry no stable ID, so they+// can't be deduped between the primary sendStream and the secondary observer.+// The observer uses this to drop them while the primary is still alive.+function _isUndedupableLiveEvent(evData) {+ if (!evData || evData.type !== 'process') return false;+ const data = evData.data || {};+ if (data.type === 'delta') return true;+ if (data.type === 'event' && data.event && data.event.stream === 'assistant') return true;+ return false;+}++function _rememberGroupEventIfDuplicate(cid, evData) {+ const key = _groupEventDedupeKey(evData);+ if (!cid || !key) return false;+ let seen = _groupEventDedupe.get(cid);+ if (!seen) {+ seen = new Map();+ _groupEventDedupe.set(cid, seen);+ }+ if (seen.has(key)) return true;+ seen.set(key, Date.now());+ while (seen.size > GROUP_EVENT_DEDUPE_LIMIT) {+ const oldest = seen.keys().next().value;+ if (oldest == null) break;+ seen.delete(oldest);+ }+ return false;+}function _stopRuntimeActorRecovery(cid) {const timer = _runtimeRecoveryTimers.get(cid);@@ -507,6 +582,13 @@ function _stopRuntimeActorRecovery(cid) {_runtimeRecoveryTimers.delete(cid);}+function _stopGroupEventObserver(cid) {+ const ctrl = _groupObserverCtrls.get(cid);+ if (!ctrl) return;+ _groupObserverCtrls.delete(cid);+ try { ctrl.abort(); } catch (_) {}+}+async function _syncPendingActorsFromRuntime(cid, opts = {}) {if (!cid || !isConvPending(cid)) return false;const state = pendingConvs.get(cid);@@ -539,9 +621,10 @@ async function _syncPendingActorsFromRuntime(cid, opts = {}) {} catch (_) {}}if (window.ConversationInfo) {- try { window.ConversationInfo.refresh(cid, { silent: true }); } catch (_) {}+ try { window.ConversationInfo.refreshTasks(cid, { silent: true }); } catch (_) {}}if (!processing) {+ _stopGroupEventObserver(cid);if (hasLiveController) {_latestInFlight.set(cid, []);setGroupConversationBusy(cid, false);@@ -567,6 +650,17 @@ async function _syncPendingActorsFromRuntime(cid, opts = {}) {_updateConvSidebarBadge(cid, true);startPolling(cid);if (cid === currentCid) _updateConvSendUI(cid);+ if (hasLiveController) {+ // Keep a second, read-only group event stream attached while a plan-driven+ // run is active. The request-scoped send stream can be interrupted by+ // renderer lifecycle / abort races; this observer is cheap and idempotent,+ // and process-event de-dupe below is now render-aware so duplicates are+ // less dangerous than a missing live rail.+ _observeConversationRunFromPlanAction(cid, {+ attachExisting: true,+ allowWithController: true,+ });+ }if (!hasLiveController) {// Runtime polling can tell us who is working, but it does not carry// process/delta events. When the local send-stream was lost (refresh,@@ -598,7 +692,7 @@ function _startRuntimeActorRecovery(cid) {_stopRuntimeActorRecovery(cid);return;}- const recovered = await _syncPendingActorsFromRuntime(cid);+ const recovered = await _syncPendingActorsFromRuntime(cid, { allowController: true });if (!isConvPending(cid) || pendingConvs.get(cid)?.aborted) {_stopRuntimeActorRecovery(cid);return;@@ -828,9 +922,18 @@ async function _openActorAgentDetail(actorId) {try {const res = await apiFetch(`/api/agents/${encodeURIComponent(aid)}`);const data = await res.json();- if (!data?.ok || !data?.agent) return;+ if (!data?.ok || !data?.agent) {+ // Agent was deleted / renamed / never installed under this uid — the+ // user clicked the actor header and landed on the Agents tab with no+ // detail panel. Tell them why instead of silently dropping the click.+ _convLog.warn('open message actor: agent not found', { agent_id: aid });+ try { await uiAlert(t('agents.agent_not_found')); } catch (_) {}+ return;+ }} catch (err) {- _convLog.warn('open message actor failed', { agent_id: aid, error: String(err && err.message || err) });+ const msg = String(err && err.message || err);+ _convLog.warn('open message actor failed', { agent_id: aid, error: msg });+ try { await uiAlert(t('chat.unknown_error') + ': ' + msg); } catch (_) {}return;}if (typeof _showAgentsDetailView === 'function') await _showAgentsDetailView(aid);@@ -1023,9 +1126,11 @@ function _groupMsgToLegacy(gm) {// ─── Chat attachments (pending-send pool per cid) ─────────────────────────// User picks files via "+" → we upload them to `<cid>/` and remember them in// this Map. On send we hand the filenames to the server; on success the list-// for that cid is cleared (per-message granularity). Each entry is {name, kind, bytes, dataUrl?}.+// for that cid is cleared (per-message granularity). Each entry is+// {name, displayName?, kind, bytes, dataUrl?, sha256?, reused?}. `name` is the+// real attachment-pool filename; `displayName` is the stable composer label.-const _chatAttachments = new Map(); // cid → Array<{name, kind, bytes, dataUrl?}>+const _chatAttachments = new Map(); // cid → Array<{name, displayName?, kind, bytes, dataUrl?, sha256?, reused?}>// Draft cid used by the commander (new-chat) tab — files land under// `data/<uid>/chat_attachments/main_chat/` until the user hits send, at which@@ -1042,6 +1147,7 @@ const CHAT_ATTACH_ACCEPT = [const CHAT_IMAGE_EXTS = ['.png', '.jpg', '.jpeg', '.webp', '.gif'];const CHAT_VIDEO_EXTS = ['.mp4', '.webm', '.mov', '.m4v', '.ogv'];+const ORKAS_FILE_DRAG_MIME = 'application/x-orkas-file';function _chatFileIconHtml(name, kind) {if (typeof window !== 'undefined' && typeof window.fileKindIconHtml === 'function') return window.fileKindIconHtml(name, kind);@@ -1061,6 +1167,61 @@ function _chatAttachKindFromExt(ext) {return 'text';}+function _chatAttachBaseName(p) {+ const parts = String(p || '').split(/[\\/]/).filter(Boolean);+ return parts.length ? parts[parts.length - 1] : String(p || '');+}++function _chatAttachHex(buf) {+ return Array.from(new Uint8Array(buf))+ .map((b) => b.toString(16).padStart(2, '0'))+ .join('');+}++async function _chatAttachSha256(buf) {+ const subtle = globalThis.crypto && globalThis.crypto.subtle;+ if (!subtle || typeof subtle.digest !== 'function') return '';+ const digest = await subtle.digest('SHA-256', buf);+ return _chatAttachHex(digest);+}++async function _chatAttachPrepareUploadFiles(cid, fileList) {+ const files = Array.from(fileList || []);+ const rejected = [];+ const prepared = [];+ const seenHashes = new Set(+ _chatAttachList(cid)+ .map((item) => item && item.sha256 ? `${Number(item.bytes) || 0}:${item.sha256}` : '')+ .filter(Boolean),+ );++ for (const file of files) {+ const ext = _chatAttachExtOf(file.name);+ if (!CHAT_ATTACH_ACCEPT.includes(ext)) {+ rejected.push(t('chat.attach_unsupported', { name: file.name }));+ continue;+ }++ let buf;+ let sha256 = '';+ try {+ buf = await file.arrayBuffer();+ } catch (err) {+ rejected.push(t('chat.attach_upload_fail', { name: file.name, reason: err.message || t('chat.attach_upload_generic_fail') }));+ continue;+ }+ try { sha256 = await _chatAttachSha256(buf); }+ catch (_) { sha256 = ''; }++ const key = sha256 ? `${buf.byteLength}:${sha256}` : '';+ if (key && seenHashes.has(key)) continue;+ if (key) seenHashes.add(key);+ prepared.push({ file, ext, buf, sha256 });+ }++ return { prepared, rejected };+}+// Build the `chat-media://` URL for serving an attachment's raw bytes to an// <img> or <video>. The main-process handler enforces uid + path safety; we// just URL-encode both path segments here.@@ -1076,13 +1237,16 @@ function _chatAttachSet(cid, items) {_chatAttachments.set(cid, items);_chatAttachRenderChips(cid);if (cid && cid === currentCid && window.ConversationInfo) {- window.ConversationInfo.refreshAttachments(cid);+ window.ConversationInfo.refreshAttachments(cid, { items });}}function _chatAttachClear(cid) {_chatAttachments.delete(cid);_chatAttachRenderChips(cid);+ if (cid && cid === currentCid && window.ConversationInfo) {+ window.ConversationInfo.refreshAttachments(cid, { items: [] });+ }}// cid → DOM host id for the chip row. Draft cid (commander tab) renders into the@@ -1109,10 +1273,11 @@ function _chatAttachRenderChips(cid) {}host.style.display = '';host.innerHTML = items.map((it, i) => {+ const displayName = it.displayName || it.name;const icon = it.kind === 'image'- ? (it.dataUrl ? `<img class="chat-attach-thumb" src="${it.dataUrl}" alt="">` : _chatFileIconHtml(it.name, it.kind))- : _chatFileIconHtml(it.name, it.kind);- const label = escapeHtml(it.name);+ ? (it.dataUrl ? `<img class="chat-attach-thumb" src="${it.dataUrl}" alt="">` : _chatFileIconHtml(displayName, it.kind))+ : _chatFileIconHtml(displayName, it.kind);+ const label = escapeHtml(displayName);const busy = it.status === 'uploading';const errored = it.status === 'error';const klass = `chat-attach-chip${busy ? ' is-uploading' : ''}${errored ? ' is-error' : ''}`;@@ -1146,9 +1311,9 @@ async function _chatAttachRemove(cid, idx) {if (item.dataUrl && item.dataUrl.startsWith('blob:')) {try { URL.revokeObjectURL(item.dataUrl); } catch (_) { /* ignore */ }}- // Only hit the server if the upload actually completed — placeholders- // that errored out or are still uploading have no disk counterpart yet.- if (item.status !== 'uploading') {+ // Only delete files this chip created. Reused files can belong to earlier+ // messages, so removing the pending chip must leave the original on disk.+ if (item.status !== 'uploading' && !item.reused) {try {await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/attachments?name=${encodeURIComponent(item.name)}`, {method: 'DELETE',@@ -1169,23 +1334,36 @@ function _chatAttachReplaceByTempId(cid, tempId, patch) {// Drop the entry entirely (error path).items.splice(idx, 1);} else {- items[idx] = { ...items[idx], ...patch };+ const next = { ...items[idx], ...patch };+ const dupIdx = next.name+ ? items.findIndex((it, i) => i !== idx && it.name === next.name && it.status !== 'uploading')+ : -1;+ if (dupIdx >= 0) {+ if (items[idx].dataUrl && items[idx].dataUrl.startsWith('blob:')) {+ try { URL.revokeObjectURL(items[idx].dataUrl); } catch (_) { /* ignore */ }+ }+ items.splice(idx, 1);+ } else {+ items[idx] = next;+ }}_chatAttachSet(cid, items);}async function _chatAttachUpload(cid, fileList) {- const files = Array.from(fileList || []);- if (!files.length) return;+ const { prepared, rejected } = await _chatAttachPrepareUploadFiles(cid, fileList);+ if (!prepared.length) {+ if (rejected.length) uiAlert(t('chat.attach_rejected_prefix', { list: rejected.join('\n') }));+ return;+ }- // ── Step 1: show placeholders immediately ────────────────────────────- // Append a busy chip for each file *before* any network I/O so the user- // sees the chip appear the instant they pick files. Images get a cheap- // local preview via URL.createObjectURL — no extra roundtrip needed.+ // ── Step 1: show placeholders after client-side hash dedupe ───────────+ // Hashing before painting chips prevents one add/drop action with several+ // identical files from flashing duplicate thumbnails above the composer.const placeholders = [];const current = _chatAttachList(cid).slice();- for (const file of files) {- const ext = _chatAttachExtOf(file.name);+ for (const item of prepared) {+ const { file, ext, buf, sha256 } = item;const kind = _chatAttachKindFromExt(ext);const tempId = `att-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;let localPreview = null;@@ -1193,31 +1371,24 @@ async function _chatAttachUpload(cid, fileList) {try { localPreview = URL.createObjectURL(file); } catch (_) { /* ignore */ }}const entry = {- tempId, name: file.name, kind, bytes: file.size || 0,- dataUrl: localPreview, status: 'uploading',+ tempId, name: file.name, displayName: file.name, kind, bytes: file.size || 0,+ dataUrl: localPreview, sha256, status: 'uploading',};current.push(entry);- placeholders.push({ tempId, file, ext });+ placeholders.push({ tempId, file, ext, buf, sha256 });}_chatAttachSet(cid, current);// ── Step 2: upload all in parallel; rendering is already done ─────────- const rejected = [];await Promise.all(placeholders.map(async (ph) => {- if (!CHAT_ATTACH_ACCEPT.includes(ph.ext)) {- _chatAttachReplaceByTempId(cid, ph.tempId, null);- rejected.push(t('chat.attach_unsupported', { name: ph.file.name }));- return;- }try {- const buf = await ph.file.arrayBuffer();const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/attachments/upload`, {method: 'POST',headers: {'Content-Type': 'application/octet-stream','X-Filename': encodeURIComponent(ph.file.name),},- body: buf,+ body: ph.buf,});const data = await res.json();if (!data.ok) {@@ -1230,8 +1401,11 @@ async function _chatAttachUpload(cid, fileList) {// roundtrip to fetch a dataUrl the server would just base64 back._chatAttachReplaceByTempId(cid, ph.tempId, {name: info.name,+ displayName: ph.file.name,kind: info.kind,bytes: info.bytes,+ reused: !!data.reused,+ sha256: ph.sha256,status: 'ready',});} catch (err) {@@ -1245,6 +1419,93 @@ async function _chatAttachUpload(cid, fileList) {}}+function _chatAttachInternalDragItems(dataTransfer) {+ if (!dataTransfer || !dataTransfer.types) return [];+ let hasInternal = false;+ for (let i = 0; i < dataTransfer.types.length; i++) {+ if (dataTransfer.types[i] === ORKAS_FILE_DRAG_MIME) {+ hasInternal = true;+ break;+ }+ }+ if (!hasInternal) return [];+ let raw = '';+ try { raw = dataTransfer.getData(ORKAS_FILE_DRAG_MIME); }+ catch (_) { return []; }+ if (!raw) return [];+ try {+ const parsed = JSON.parse(raw);+ const list = Array.isArray(parsed) ? parsed : [parsed];+ return list+ .map((item) => ({+ path: typeof item?.path === 'string' ? item.path : '',+ name: typeof item?.name === 'string' ? item.name : '',+ }))+ .filter((item) => item.path);+ } catch (_) {+ return [];+ }+}++async function _chatAttachImportPaths(cid, entries) {+ const files = Array.isArray(entries) ? entries.filter((it) => it && it.path) : [];+ if (!files.length) return;++ const placeholders = [];+ const current = _chatAttachList(cid).slice();+ for (const item of files) {+ const displayName = item.name || _chatAttachBaseName(item.path);+ const ext = _chatAttachExtOf(displayName);+ const kind = _chatAttachKindFromExt(ext);+ const tempId = `att-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+ current.push({+ tempId,+ name: displayName,+ displayName,+ kind,+ bytes: 0,+ dataUrl: null,+ status: 'uploading',+ });+ placeholders.push({ tempId, path: item.path, name: displayName });+ }+ _chatAttachSet(cid, current);++ const rejected = [];+ await Promise.all(placeholders.map(async (ph) => {+ try {+ const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/attachments/import`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ path: ph.path, name: ph.name }),+ });+ const data = await res.json();+ if (!data.ok) {+ _chatAttachReplaceByTempId(cid, ph.tempId, null);+ rejected.push(t('chat.attach_upload_fail', { name: ph.name, reason: data.error || t('chat.attach_upload_generic_fail') }));+ return;+ }+ const info = data.info;+ _chatAttachReplaceByTempId(cid, ph.tempId, {+ name: info.name,+ displayName: ph.name,+ kind: info.kind,+ bytes: info.bytes,+ dataUrl: (info.kind === 'image' || info.kind === 'video') ? _chatMediaUrl(cid, info.name) : null,+ reused: !!data.reused,+ status: 'ready',+ });+ } catch (err) {+ _chatAttachReplaceByTempId(cid, ph.tempId, null);+ rejected.push(t('chat.attach_upload_fail', { name: ph.name, reason: err.message || t('chat.attach_upload_generic_fail') }));+ }+ }));++ if (rejected.length) {+ uiAlert(t('chat.attach_rejected_prefix', { list: rejected.join('\n') }));+ }+}+async function _chatAttachRefreshFromServer(cid) {try {const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/attachments`);@@ -1409,32 +1670,14 @@ function _hydrateMessageProducedChips(msgDiv) {e.stopPropagation();const p = chip.dataset.producedPath;if (!p) return;- // Markdown lands in the right-side drawer with view/edit semantics- // (reuses the KB editor — see modules/md-view-edit.js). Other kinds- // continue to use the existing in-app preview overlay / fallback.- if (_isMarkdownPath(p) && typeof openChatMdDrawer === 'function') {- const base = p.split(/[\\/]/).pop() || p;- openChatMdDrawer({- source: { kind: 'workspace', absPath: p, cid: currentCid || undefined },- initialMode: 'view',- title: base,- });- return;- }if (typeof openChatFileViewer === 'function') {const base = p.split(/[\\/]/).pop() || p;- openChatFileViewer(p, base);+ openChatFileViewer(p, base, currentCid ? { cid: currentCid } : undefined);}});});}-function _isMarkdownPath(p) {- if (!p) return false;- const lower = p.toLowerCase();- return lower.endsWith('.md') || lower.endsWith('.markdown');-}-function _hydrateMessageAttachmentThumbs(msgDiv, cid) {// Image chips have a thumb we want to enlarge via the lightbox; the rest// (pdf / docx / text / video) get the same kind-aware viewer as produced@@ -1512,26 +1755,31 @@ function _bindChatPasteAttach(inputSelector, getCid) {function _bindChatDropAttach(wrapSelector, getCid) {const el = document.querySelector(wrapSelector);if (!el || el.dataset.dropBound === '1') return;- const isFileDrag = (e) => {+ const isAttachDrag = (e) => {const types = e.dataTransfer && e.dataTransfer.types;if (!types) return false;for (let i = 0; i < types.length; i++) {- if (types[i] === 'Files') return true;+ if (types[i] === 'Files' || types[i] === ORKAS_FILE_DRAG_MIME) return true;}return false;};const allow = (e) => {- if (!isFileDrag(e)) return;+ if (!isAttachDrag(e)) return;e.preventDefault();e.dataTransfer.dropEffect = 'copy';};el.addEventListener('dragover', allow);el.addEventListener('dragenter', allow);el.addEventListener('drop', (e) => {- if (!isFileDrag(e)) return;+ if (!isAttachDrag(e)) return;e.preventDefault();const cid = getCid();if (!cid) return;+ const internalFiles = _chatAttachInternalDragItems(e.dataTransfer);+ if (internalFiles.length) {+ _chatAttachImportPaths(cid, internalFiles);+ return;+ }_chatAttachUpload(cid, e.dataTransfer.files);});el.dataset.dropBound = '1';@@ -1703,6 +1951,10 @@ async function _toggleConversationPinned(cid, pinned) {conversations = snapshot;renderConversationList();_convLog.warn('toggle conversation pin failed', err);+ // Surface failure to the user — silent rollback leaves a chip-flicker+ // with no explanation (typical race: another tab/device deleted the+ // conv while this pin was in flight, or the server transient-errored).+ try { await uiAlert(t('chat.pin_failed')); } catch (_) {}}}@@ -2008,10 +2260,10 @@ async function loadConversationHistory(cid) {// adds it post-scroll and it ends up below the visible area._ensureConvCreateAgentInline();_scrollToBottomNoAnim(container);- if (window.ConversationInfo) window.ConversationInfo.refresh(cid);+ if (window.ConversationInfo) window.ConversationInfo.refreshTasks(cid);} catch (e) {container.innerHTML = `<div class="empty">${escapeHtml(t('chat.load_failed', { msg: e.message || '' }))}</div>`;- if (window.ConversationInfo) window.ConversationInfo.refresh(cid);+ if (window.ConversationInfo) window.ConversationInfo.refreshTasks(cid);}}@@ -2083,7 +2335,7 @@ async function _recoverPolledVisibleMessages(cid, rawMessages) {}if (changed) {try { if (window.PlanRail) window.PlanRail.refresh(cid, { force: true }); } catch (_) {}- try { if (window.ConversationInfo) window.ConversationInfo.refresh(cid); } catch (_) {}+ try { if (window.ConversationInfo) window.ConversationInfo.refreshTasks(cid); } catch (_) {}}return changed;}@@ -3063,9 +3315,12 @@ function _makeConvChatController(cid) {controller: { abort: () => _convChatCtrls.get(id)?.abort() },aborted: false,});+ _lastGroupWorkEventAt.set(id, Date.now());+ _groupEventDedupe.delete(id);_updateConvSendUI(id);_updateConvSidebarBadge(id, true);startPolling(id);+ _startRuntimeActorRecovery(id);},onAbort(_msgEl, id) {const state = pendingConvs.get(id);@@ -3181,7 +3436,9 @@ function _makeStreamPaintYield() {function _observeConversationRunFromPlanAction(cid, opts = {}) {if (!cid) return null;const attachExisting = !!opts.attachExisting;- if (_convChatCtrls.has(cid)) return null;+ const allowWithController = !!opts.allowWithController;+ if (_convChatCtrls.has(cid) && !allowWithController) return null;+ if (allowWithController && _groupObserverCtrls.has(cid)) return null;if (!attachExisting && (pendingConvs.has(cid) || isGroupConversationBusy(cid))) return null;const controller = new AbortController();@@ -3195,6 +3452,7 @@ function _observeConversationRunFromPlanAction(cid, opts = {}) {try { controller.abort(); } catch (_) {}},};+ if (allowWithController) _groupObserverCtrls.set(cid, ctrl);const activate = () => {if (activated || controller.signal.aborted) return;@@ -3205,12 +3463,14 @@ function _observeConversationRunFromPlanAction(cid, opts = {}) {msgEl = existing.loadingEl || (cid === currentCid? _createStreamingAssistantMessage(container, { hiddenUntilActor: true }): null);- _convChatCtrls.set(cid, ctrl);+ if (!allowWithController) {+ _convChatCtrls.set(cid, ctrl);+ }pendingConvs.set(cid, {...existing,loadingEl: msgEl,needsIndicator: false,- controller: ctrl,+ controller: allowWithController ? (existing.controller || ctrl) : ctrl,aborted: false,});setGroupConversationBusy(cid, true);@@ -3266,6 +3526,17 @@ function _observeConversationRunFromPlanAction(cid, opts = {}) {if (st.status === 'running' || inFlight.length > 0) sawActivity = true;}if (sawActivity) activate();+ // While the primary IPC sendStream still holds the live source of+ // truth for rendering, skip events the dedupe layer can't+ // disambiguate. `_groupEventDedupeKey` returns empty for delta+ // tokens and assistant-stream events (no stable ID), so feeding+ // them from both subscribers doubles every appended chunk into+ // the streaming bubble. The observer remains active for ID-bearing+ // events so the resilience story (primary dies mid-turn → bubble+ // still receives message/artifact/state_changed) is preserved.+ if (allowWithController && _convChatCtrls.has(cid) && _isUndedupableLiveEvent(evData)) {+ continue;+ }_handleGroupBusEvent(cid, msgEl, evData, { archive: true });const paintWait = maybeYieldToPaint();if (paintWait) await paintWait;@@ -3281,14 +3552,23 @@ function _observeConversationRunFromPlanAction(cid, opts = {}) {} finally {settled = true;clearTimeout(noActivityTimer);- if (_convChatCtrls.get(cid) === ctrl) _convChatCtrls.delete(cid);+ if (allowWithController) {+ if (_groupObserverCtrls.get(cid) === ctrl) _groupObserverCtrls.delete(cid);+ } else if (_convChatCtrls.get(cid) === ctrl) {+ _convChatCtrls.delete(cid);+ }if (activated) {+ if (allowWithController) {+ if (window.PlanRail) window.PlanRail.refresh(cid, { force: true });+ if (window.ConversationInfo) window.ConversationInfo.refreshTasks(cid, { silent: true });+ return;+ }setGroupConversationBusy(cid, false);_removeEmptyStreamingPlaceholder(msgEl);_finishStreamingMsg(cid);_scheduleHistoryReconcileAfterStream(cid);if (window.PlanRail) window.PlanRail.refresh(cid, { force: true });- if (window.ConversationInfo) window.ConversationInfo.refresh(cid, { silent: true });+ if (window.ConversationInfo) window.ConversationInfo.refreshTasks(cid, { silent: true });}}})();@@ -3511,6 +3791,10 @@ function _setProcessLineContent(line, text, kind) {line.innerHTML = `${icon}<span class="stream-process-text">${escapeHtml(body)}</span>`;}+function _processLineCount(msg) {+ return msg?.querySelectorAll?.('[data-role="process"] .stream-process-line')?.length || 0;+}+function _eventProcessKind(evt, text) {if (!evt || typeof evt !== 'object') return _processKindOf(text);const stream = evt.stream;@@ -3730,6 +4014,9 @@ function _streamingMarkAborted(msg) {function _finishStreamingMsg(cid) {_stopRuntimeActorRecovery(cid);+ _stopGroupEventObserver(cid);+ _lastGroupWorkEventAt.delete(cid);+ _groupEventDedupe.delete(cid);pendingConvs.delete(cid);if (isGroupConversationBusy(cid)) startPolling(cid);else stopPolling(cid);@@ -4179,7 +4466,12 @@ function createChatController(config) {}const paintWait = maybeYieldToPaint();if (paintWait) await paintWait;- } catch (_) { /* skip malformed */ }+ } catch (err) {+ _convLog.warn('stream event handler failed', {+ cid: id,+ error: String(err && err.message || err),+ });+ }}}} catch (err) {@@ -4583,6 +4875,13 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {// { type: 'aborted', cid }function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {}) {if (!evData || typeof evData !== 'object') return;+ if (+ evData.type === 'process'+ || evData.type === 'artifact_created'+ || (evData.type === 'message' && evData.msg && evData.msg.from !== 'user')+ ) {+ _lastGroupWorkEventAt.set(cid, Date.now());+ }// Bump the conv to the top of the sidebar list whenever a user-visible// message lands — applies to both currently-viewed and background convs,// so the sidebar stays ordered by last activity in real time. Skip@@ -4590,7 +4889,7 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {// user's view; visible end-of-turn replies will bump shortly after).if (evData.type === 'message' && evData.msg && !evData.msg.dispatch) {_bumpConvToTop(cid);- if (window.ConversationInfo) window.ConversationInfo.refresh(cid);+ if (window.ConversationInfo) window.ConversationInfo.refreshTasks(cid);}// Cross-cid leakage guard: per-cid controllers stay alive when the user// navigates away mid-stream (a legit pattern — let the conv finish in@@ -4605,6 +4904,7 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {// and on switch-back `loadConversationHistory` rebuilds the cid's view// from disk — so dropping live UI updates here is safe.if (cid !== currentCid) return;+ if (evData.type !== 'process' && _rememberGroupEventIfDuplicate(cid, evData)) return;if (evData.type === 'message') {const gm = evData.msg;if (!gm) return;@@ -4705,7 +5005,15 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {if (cid === currentCid) _updateConvSendUI(cid);}const target = _ensureActorPlaceholder(cid, actor, streamingMsg);- if (!target) return;+ if (!target) {+ _convLog.warn('group process target missing', {+ cid,+ actor,+ kind: data.type || '',+ });+ return;+ }+ if (_rememberGroupEventIfDuplicate(cid, evData)) return;// Diagnostic — count how many deltas reach the renderer per actor.// If this number is much smaller than the bus emit count from the// turn-end log, the bottleneck is upstream (IPC batching). If it's@@ -4716,14 +5024,37 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {window._convDeltaCount[actor] = (window._convDeltaCount[actor] || 0) + 1;}}- if (data.type === 'delta' && typeof data.text === 'string') {- // Token-by-token streaming → write into the placeholder's final- // body so the user sees the reply form character-by-character.- _streamingAppendFinalDelta(target, data.text);- } else if (data.type === 'progress' && data.text) {- _streamingAppendProgress(target, String(data.text));- } else if (data.type === 'event') {- _renderAgentEvent(target, data.event);+ try {+ if (data.type === 'delta' && typeof data.text === 'string') {+ // Token-by-token streaming → write into the placeholder's final+ // body so the user sees the reply form character-by-character.+ _streamingAppendFinalDelta(target, data.text);+ } else if (data.type === 'progress' && data.text) {+ _streamingAppendProgress(target, String(data.text));+ } else if (data.type === 'event') {+ const before = _processLineCount(target);+ _renderAgentEvent(target, data.event);+ const evt = data.event || {};+ const line = evt.stream === 'tool' ? _formatEventLine(evt) : null;+ if (line && _processLineCount(target) <= before) {+ _streamingAppendProgress(target, line, _eventProcessKind(evt, line));+ }+ }+ } catch (err) {+ const evt = data.event || {};+ const fallback = data.type === 'progress'+ ? String(data.text || '')+ : (evt && evt.stream ? _formatEventLine(evt) : '');+ _convLog.warn('group process render failed', {+ cid,+ actor,+ kind: data.type || '',+ stream: evt.stream || '',+ error: String(err && err.message || err),+ });+ if (fallback) {+ try { _streamingAppendProgress(target, fallback, _eventProcessKind(evt, fallback)); } catch (_) {}+ }}} else if (evData.type === 'artifact_created') {const actor = String(evData.actor || evData.artifact?.agent_id || '');@@ -4747,7 +5078,7 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {// reply should default to that agent without them having to @-mention._evaluateAutoRecipient(cid);if (window.PlanRail) window.PlanRail.refresh(cid, { force: true });- if (window.ConversationInfo) window.ConversationInfo.refresh(cid, { silent: true });+ if (window.ConversationInfo) window.ConversationInfo.refreshTasks(cid, { silent: true });} else if (evData.type === 'state_changed') {// Each in_flight actor gets a placeholder so its delta tokens / tool// calls render in its own bubble even before its `message` arrives.@@ -4774,7 +5105,7 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {if (window.PlanRail) {window.PlanRail.setInFlight(cid, inFlight);}- if (window.ConversationInfo) window.ConversationInfo.refresh(cid, { silent: true });+ if (window.ConversationInfo) window.ConversationInfo.refreshTasks(cid, { silent: true });_updateConvSidebarBadge(cid, false);if (cid === currentCid) _updateConvSendUI(cid);} else if (evData.type === 'aborted') {@@ -4934,19 +5265,18 @@ function _stripAgentCreateBlocksForStream(buf) {return _replaceOuterAgentBlocks(buf, _streamPlaceholderHtml('chat.create_agent_streaming_placeholder'));}+function _skillStreamPlaceholderHtml() {+ return _streamPlaceholderHtml('chat.create_skill_streaming_placeholder');+}+// `<<<skill-file path=X ... >>>` blocks (skill edit chat). Different fence// shape from `<agent>` (see strip-structural-blocks.js header) but same user-facing-// contract: streaming placeholder hides the raw block + reveals the file-// being written. The path attribute (when present) flows into the-// localised "Writing X…" label so the placeholder is informative;-// unattributed blocks fall back to a generic "Writing file…" label.+// contract: streaming placeholder hides raw file content while the skill is+// being assembled. Do not surface per-file paths here: one skill can emit+// several file blocks, and repeating "Writing SKILL.md" made the stream noisy.function _stripSkillFileBlocksForStream(buf) {- return _replaceOuterSkillFileBlocks(buf, (path) => {- const label = path- ? t('chat.skill_file_streaming_placeholder', { path })- : t('chat.skill_file_streaming_placeholder_unknown');- return `\n<em class="stream-placeholder">${escapeHtml(label)}</em>\n`;- });+ const placeholder = _skillStreamPlaceholderHtml();+ return _replaceOuterSkillFileBlocks(buf, () => placeholder);}// `<skill>` container (commander create / edit). Pure logic lives in@@ -4957,10 +5287,11 @@ function _stripSkillFileBlocksForStream(buf) {// composes `_replaceOuterAgentBlocks`). Set A / set B fixtures pinned in// `test/renderer/strip-structural-blocks.test.ts`.function _stripSkillCreateBlocksForStream(buf) {- return _stripSkillCreateContainer(+ const placeholder = _skillStreamPlaceholderHtml();+ return _collapseRepeatedStructuralPlaceholders(_stripSkillCreateContainer(buf,- _streamPlaceholderHtml('chat.create_skill_streaming_placeholder'),- );+ placeholder,+ ), placeholder);}function _stripAgentFormBlockForStream(buf) {@@ -5608,13 +5939,14 @@ function _refreshTaskSurfacesAfterAbort(cid) {}} catch (_) {}try {- if (window.ConversationInfo) window.ConversationInfo.refresh(cid, { silent: true });+ if (window.ConversationInfo) window.ConversationInfo.refreshTasks(cid, { silent: true });} catch (_) {}}function abortConvStream(cid) {const state = pendingConvs.get(cid);_stopRuntimeActorRecovery(cid);+ _stopGroupEventObserver(cid);setGroupConversationBusy(cid, false);// Group chat: also tell the bus to abort all in-flight worker turns + clear// queues. Cancelling just the IPC stream would leave agents running in the@@ -5767,4 +6099,3 @@ if (typeof window !== 'undefined') {_initChatSelectionMenu();}}-diff --git a/src/renderer/modules/ipc-shim.js b/src/renderer/modules/ipc-shim.jsindex c674a18f..1de35989 100644--- a/src/renderer/modules/ipc-shim.js+++ b/src/renderer/modules/ipc-shim.js@@ -61,6 +61,7 @@ const _IPC_ROUTES = [['DELETE', /^\/api\/conversations\/([^/]+)$/, 'conversations.delete', ['cid']],['POST', /^\/api\/conversations\/([^/]+)\/pin$/, 'conversations.pin', ['cid']],['GET', /^\/api\/conversations\/([^/]+)\/history$/, 'conversations.history', ['cid']],+ ['GET', /^\/api\/conversations\/([^/]+)\/files$/, 'conversations.files.list', ['cid']],['POST', /^\/api\/conversations\/([^/]+)\/send$/, 'groupChat.send', ['cid']],['POST', /^\/api\/conversations\/([^/]+)\/send\/stream$/, 'conversations.sendStream', ['cid'], { stream: true }],['POST', /^\/api\/conversations\/([^/]+)\/abort$/, 'groupChat.abort', ['cid']],@@ -74,6 +75,7 @@ const _IPC_ROUTES = [['POST', /^\/api\/conversations\/([^/]+)\/marketplace-install$/, 'groupChat.resolveMarketplaceInstallRequest', ['cid']],['GET', /^\/api\/conversations\/([^/]+)\/attachments$/, 'conversations.attachments.list', ['cid']],['POST', /^\/api\/conversations\/([^/]+)\/attachments\/upload$/, { upload: 'conversations.attachments.upload' }, ['cid']],+ ['POST', /^\/api\/conversations\/([^/]+)\/attachments\/import$/, 'conversations.attachments.import', ['cid']],['DELETE', /^\/api\/conversations\/([^/]+)\/attachments$/, 'conversations.attachments.delete', ['cid']],['GET', /^\/api\/agents\/([^/]+)$/, 'agents.get', ['agent_id']],['DELETE', /^\/api\/agents\/([^/]+)$/, 'agents.delete', ['agent_id']],diff --git a/src/renderer/modules/md-view-edit.js b/src/renderer/modules/md-view-edit.jsindex eb5a6fc6..3539a337 100644--- a/src/renderer/modules/md-view-edit.js+++ b/src/renderer/modules/md-view-edit.js@@ -15,7 +15,7 @@//// API:// mountMdViewEdit({ bodyEl, actionsEl, source, capabilities?, initialMode?,-// initialContent?, initialDraft?, callbacks? })+// initialContent?, initialDraft?, actionIconOnly?, callbacks? })// → { destroy, refreshContent, getMode, setMode, isDirty,// getDraft, setDraftAsContent, getSource }//@@ -103,6 +103,7 @@ function mountMdViewEdit(opts) {callbacks,bodyEl,actionsEl,+ actionIconOnly: opts.actionIconOnly === true,// Canonical content (from disk / source). Ephemeral seeds this with// initialText; the "is dirty" check compares draft vs. this.content: '',@@ -288,6 +289,18 @@ function _mveRenderError(state, msg) {state.actionsEl.innerHTML = '';}+function _mveActionButton(state, action, labelKey, iconName, extraClass) {+ const label = t(labelKey);+ const cls = `btn btn-sm${state.actionIconOnly ? ' btn-icon ctx-viewer-action-icon-btn' : ''}${extraClass ? ` ${extraClass}` : ''}`;+ if (!state.actionIconOnly) {+ return `<button class="${cls}" data-mve-action="${action}">${escapeHtml(label)}</button>`;+ }+ const icon = (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function')+ ? window.uiIconHtml(iconName, 'ui-icon ctx-viewer-action-icon')+ : escapeHtml(label);+ return `<button type="button" class="${cls}" data-mve-action="${action}" aria-label="${escapeHtml(label)}" title="${escapeHtml(label)}">${icon}</button>`;+}+function _mveRenderView(state) {state.mode = 'view';const bodyEl = state.bodyEl;@@ -297,9 +310,9 @@ function _mveRenderView(state) {if (state.caps.taskCheckbox) _mveBindTaskCheckboxes(state, bodyEl);const actions = [];- if (state.caps.edit) actions.push(`<button class="btn btn-sm" data-mve-action="edit">${escapeHtml(t('contexts.viewer.edit'))}</button>`);- if (state.caps.reveal) actions.push(`<button class="btn btn-sm" data-mve-action="reveal">${escapeHtml(t('contexts.viewer.open_system'))}</button>`);- if (state.caps.delete) actions.push(`<button class="btn btn-sm btn-danger" data-mve-action="delete">${escapeHtml(t('contexts.viewer.delete'))}</button>`);+ if (state.caps.edit) actions.push(_mveActionButton(state, 'edit', 'contexts.viewer.edit', 'pencil'));+ if (state.caps.reveal) actions.push(_mveActionButton(state, 'reveal', 'contexts.viewer.open_system', 'folder-open'));+ if (state.caps.delete) actions.push(_mveActionButton(state, 'delete', 'contexts.viewer.delete', 'trash', 'btn-danger'));actionsEl.innerHTML = actions.join('');actionsEl.querySelector('[data-mve-action="edit"]')?.addEventListener('click', () => _mveEnterEdit(state));@@ -350,11 +363,11 @@ function _mveRenderEditor(state) {// Actions: save/cancel for persisted sources; copy/sendToChat for ephemeral.const actions = [];if (state.caps.save) {- actions.push(`<button class="btn btn-sm btn-primary" data-mve-action="save">${escapeHtml(t('contexts.viewer.save'))}</button>`);- actions.push(`<button class="btn btn-sm" data-mve-action="cancel">${escapeHtml(t('contexts.viewer.cancel'))}</button>`);+ actions.push(_mveActionButton(state, 'save', 'contexts.viewer.save', 'check', 'btn-primary'));+ actions.push(_mveActionButton(state, 'cancel', 'contexts.viewer.cancel', 'x'));} else if (state.source.kind === 'ephemeral') {- actions.push(`<button class="btn btn-sm" data-mve-action="copy-draft">${escapeHtml(t('chat.md_drawer.copy_draft'))}</button>`);- actions.push(`<button class="btn btn-sm btn-primary" data-mve-action="send-to-chat">${escapeHtml(t('chat.md_drawer.send_to_chat'))}</button>`);+ actions.push(_mveActionButton(state, 'copy-draft', 'chat.md_drawer.copy_draft', 'clipboard-list'));+ actions.push(_mveActionButton(state, 'send-to-chat', 'chat.md_drawer.send_to_chat', 'send', 'btn-primary'));}actionsEl.innerHTML = actions.join('');diff --git a/src/renderer/modules/plan-rail.js b/src/renderer/modules/plan-rail.jsindex ef28cfa3..c921d7ba 100644--- a/src/renderer/modules/plan-rail.js+++ b/src/renderer/modules/plan-rail.js@@ -135,8 +135,8 @@ async function _finishStepAction(cid, stepIndex, opts = {}) {}function _refreshConversationInfo(cid) {- if (window.ConversationInfo && typeof window.ConversationInfo.refresh === 'function') {- window.ConversationInfo.refresh(cid, { silent: true });+ if (window.ConversationInfo && typeof window.ConversationInfo.refreshTasks === 'function') {+ window.ConversationInfo.refreshTasks(cid, { silent: true });}}@@ -222,6 +222,20 @@ function _buildProgressText(plan) {return `${done}/${plan.steps.length}`;}+function _isPlanFullyComplete(plan) {+ const steps = plan && Array.isArray(plan.steps) ? plan.steps : [];+ if (!steps.length) return false;+ if (Array.isArray(_currentInFlight) && _currentInFlight.length > 0) return false;+ return steps.every((s) => s && (s.status === 'done' || s.status === 'skipped'));+}++function _hideRail(root, body, progress, wrap) {+ root.style.display = 'none';+ body.innerHTML = '';+ progress.textContent = '';+ if (wrap) wrap.classList.remove('has-plan-rail');+}+function _render(plan) {const root = document.getElementById('plan-rail');const body = document.getElementById('plan-rail-body');@@ -235,10 +249,13 @@ function _render(plan) {const wrap = root.closest('.chat-input-wrapper');if (!plan || !Array.isArray(plan.steps) || plan.steps.length === 0) {_lastPlan = null;- root.style.display = 'none';- body.innerHTML = '';- progress.textContent = '';- if (wrap) wrap.classList.remove('has-plan-rail');+ _hideRail(root, body, progress, wrap);+ return;+ }+ if (_isPlanFullyComplete(plan)) {+ _lastPlan = plan;+ _clearStepActionRequests(_currentCid);+ _hideRail(root, body, progress, wrap);return;}_lastPlan = plan;diff --git a/src/renderer/modules/project-detail.js b/src/renderer/modules/project-detail.jsindex b6f4af97..e9099203 100644--- a/src/renderer/modules/project-detail.js+++ b/src/renderer/modules/project-detail.js@@ -1,8 +1,6 @@// ─── Project detail panel ───────────────────────────────────────────────-// Drives `#panel-project`: shows the project's bindings (agents + skills)-// and exposes Add / Remove for each. Opened by clicking a project row in-// the sidebar (`projects.js::_renderProjectRow` — single click both-// expands the row and switches view here).+// Drives `#panel-project`: shows the project composer, files, and bindings+// (agents + skills), and exposes Add / Remove for each.//// Header carries 3 actions: + New chat / Rename / Delete. The "Back" button// was intentionally removed — the sidebar IS the back navigation.@@ -13,7 +11,7 @@const _projectDetailLog = createLogger('project-detail');let _projectDetailPid = ''; // pid currently rendered in the panel-let _projectDetailMeta = null; // { project, agentDetails, skillDetails }+let _projectDetailMeta = null; // { project, agentDetails, skillDetails, files }// ── Public: navigate-into ──────────────────────────────────────────────@@ -25,17 +23,19 @@ async function loadProjectDetail(pid) {return;}try {- const [getRes, listRes] = await Promise.all([+ const [getRes, listRes, filesRes] = await Promise.all([window.orkas.invoke('projects.get', { projectId: pid }),window.orkas.invoke('projects.bindings.list', { projectId: pid }),+ window.orkas.invoke('projects.files.list', { projectId: pid }),]);- if (!getRes?.ok || !listRes?.ok) {- throw new Error((getRes && getRes.error) || (listRes && listRes.error) || 'load_failed');+ if (!getRes?.ok || !listRes?.ok || !filesRes?.ok) {+ throw new Error((getRes && getRes.error) || (listRes && listRes.error) || (filesRes && filesRes.error) || 'load_failed');}_projectDetailMeta = {project: getRes.project,agentDetails: Array.isArray(listRes.agentDetails) ? listRes.agentDetails : [],skillDetails: Array.isArray(listRes.skillDetails) ? listRes.skillDetails : [],+ files: Array.isArray(filesRes.files) ? filesRes.files : [],};_renderProjectDetail();} catch (err) {@@ -48,13 +48,17 @@ async function loadProjectDetail(pid) {function _renderProjectDetailEmpty() {const titleEl = document.getElementById('project-detail-title');if (titleEl) titleEl.textContent = '';- document.getElementById('project-agents-list').innerHTML = '';- document.getElementById('project-skills-list').innerHTML = '';+ const agents = document.getElementById('project-agents-list');+ const skills = document.getElementById('project-skills-list');+ const files = document.getElementById('project-files-list');+ if (agents) agents.innerHTML = '';+ if (skills) skills.innerHTML = '';+ if (files) files.innerHTML = '';}function _renderProjectDetail() {if (!_projectDetailMeta) { _renderProjectDetailEmpty(); return; }- const { project, agentDetails, skillDetails } = _projectDetailMeta;+ const { project, agentDetails, skillDetails, files } = _projectDetailMeta;const titleEl = document.getElementById('project-detail-title');if (titleEl) titleEl.textContent = project?.name || '';@@ -65,9 +69,13 @@ function _renderProjectDetail() {document.getElementById('project-skills-list').innerHTML = _renderBindingsRows('skill', skillDetails,);+ _renderProjectFiles(files || []);applyDomI18n();_bindRemoveButtons();+ _bindProjectFileRows();+ if (typeof refreshWorkspaceChip === 'function') refreshWorkspaceChip();+ if (typeof hydrateUiIcons === 'function') hydrateUiIcons(document.getElementById('project-detail-content'));}function _renderBindingsRows(kind, items) {@@ -78,9 +86,9 @@ function _renderBindingsRows(kind, items) {for (const it of sorted) {const id = (kind === 'agent') ? it.agent_id : it.id;const name = escapeHtml(it.name || id);- const desc = _pickItemDescription(it, lang);+ const desc = kind === 'agent' ? '' : _pickItemDescription(it, lang);const descHtml = desc ? `<div class="project-binding-desc muted">${escapeHtml(desc)}</div>` : '';- const sourceTag = it.source ? `<span class="project-binding-source">${escapeHtml(it.source)}</span>` : '';+ const sourceTag = _projectBindingSourceHtml(it.source, kind);rows.push(`<div class="project-binding-row" data-kind="${kind}" data-id="${escapeHtml(id)}"><div class="project-binding-main">@@ -101,6 +109,204 @@ function _renderBindingsRows(kind, items) {return rows.join('');}+function _formatProjectFileBytes(bytes) {+ const n = Number(bytes);+ if (!Number.isFinite(n) || n <= 0) return '';+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(n < 10 * 1024 ? 1 : 0)} KB`;+ return `${(n / 1024 / 1024).toFixed(n < 10 * 1024 * 1024 ? 1 : 0)} MB`;+}++function _renderProjectFiles(files) {+ const list = document.getElementById('project-files-list');+ const status = document.getElementById('project-files-status');+ if (!list) return;+ if (status) status.textContent = '';+ const sorted = (files || []).slice().sort(_byDisplayName);+ if (!sorted.length) {+ list.innerHTML = `<div class="empty" data-i18n="project.files.empty">${escapeHtml(t('project.files.empty'))}</div>`;+ return;+ }+ const removeLabel = escapeHtml(t('project.files.remove'));+ list.innerHTML = sorted.map((f) => {+ const name = f.name || '';+ const label = escapeHtml(name);+ const icon = (typeof window !== 'undefined' && typeof window.fileKindIconHtml === 'function')+ ? window.fileKindIconHtml(name, f.kind)+ : '';+ const meta = _formatProjectFileBytes(f.bytes);+ return `+ <div class="project-file-row" data-project-file="${label}">+ <button type="button" class="project-file-main" title="${label}" data-action="open-file">+ <span class="project-file-icon">${icon}</span>+ <span class="project-file-name">${label}</span>+ ${meta ? `<span class="project-file-meta">${escapeHtml(meta)}</span>` : ''}+ </button>+ <button type="button" class="project-file-remove" data-action="remove-file"+ title="${removeLabel}" aria-label="${removeLabel}">×</button>+ </div>+ `;+ }).join('');+}++function _bindProjectFileRows() {+ const root = document.getElementById('project-files-list');+ if (!root) return;+ root.querySelectorAll('.project-file-row[data-project-file]').forEach((row) => {+ const name = row.dataset.projectFile || '';+ row.querySelector('[data-action="open-file"]')?.addEventListener('click', async (e) => {+ e.stopPropagation();+ await _openProjectFile(name);+ });+ row.querySelector('[data-action="remove-file"]')?.addEventListener('click', async (e) => {+ e.stopPropagation();+ await _deleteProjectFile(name);+ });+ });+}++async function _openProjectFile(name) {+ if (!_projectDetailPid || !name || typeof openChatFileViewer !== 'function') return;+ try {+ const res = await window.orkas.invoke('projects.files.absPath', {+ projectId: _projectDetailPid,+ name,+ });+ if (!res?.ok || !res.path) throw new Error(res?.error || 'not_found');+ openChatFileViewer(res.path, name, { projectId: _projectDetailPid });+ } catch (err) {+ _projectDetailLog.warn('open project file failed', err);+ }+}++async function _deleteProjectFile(name) {+ if (!_projectDetailPid || !name) return;+ try {+ const res = await window.orkas.invoke('projects.files.delete', {+ projectId: _projectDetailPid,+ name,+ });+ if (!res?.ok) throw new Error(res?.error || 'delete_failed');+ await loadProjectDetail(_projectDetailPid);+ } catch (err) {+ _projectDetailLog.warn('delete project file failed', err);+ if (typeof uiAlert === 'function') uiAlert(t('project.files.delete_failed'));+ }+}++function _arrayBufferToBase64(buf) {+ const bytes = new Uint8Array(buf || new ArrayBuffer(0));+ let binary = '';+ const step = 0x8000;+ for (let i = 0; i < bytes.length; i += step) {+ binary += String.fromCharCode.apply(null, bytes.subarray(i, Math.min(i + step, bytes.length)));+ }+ return btoa(binary);+}++function _setProjectFilesStatus(text) {+ const status = document.getElementById('project-files-status');+ if (status) status.textContent = text || '';+}++async function _uploadProjectFiles(fileList) {+ if (!_projectDetailPid || !fileList || !fileList.length) return;+ const files = Array.from(fileList).filter(Boolean);+ if (!files.length) return;+ _setProjectFilesStatus(t('project.files.uploading'));+ const failed = [];+ await Promise.all(files.map(async (file) => {+ try {+ const buf = await file.arrayBuffer();+ const res = await window.orkas.invoke('projects.files.upload', {+ projectId: _projectDetailPid,+ name: file.name || 'file',+ data: _arrayBufferToBase64(buf),+ });+ if (!res?.ok) {+ failed.push(t('project.files.upload_failed', {+ name: file.name || 'file',+ reason: res?.error || t('chat.attach_upload_generic_fail'),+ }));+ }+ } catch (err) {+ failed.push(t('project.files.upload_failed', {+ name: file.name || 'file',+ reason: err?.message || t('chat.attach_upload_generic_fail'),+ }));+ }+ }));+ await loadProjectDetail(_projectDetailPid);+ if (failed.length && typeof uiAlert === 'function') {+ await uiAlert(t('project.files.upload_failed_list', { list: failed.join('\n') }));+ }+}++async function _submitProjectChat() {+ if (!_projectDetailPid) return;+ const input = document.getElementById('project-chat-input');+ const btn = document.getElementById('project-chat-send-btn');+ const raw = (input?.value || '').trim();+ if (!raw) return;+ if (typeof ensureModelConfigured === 'function' && !ensureModelConfigured()) return;+ const useSelection = (typeof consumeChatUseSelection === 'function')+ ? consumeChatUseSelection('project')+ : null;+ const recipient = (typeof getChatRecipient === 'function')+ ? getChatRecipient('project')+ : null;+ const withUse = (typeof transformWithChatUse === 'function')+ ? transformWithChatUse(raw, useSelection)+ : raw;+ const content = (typeof applyRecipientPrefix === 'function')+ ? applyRecipientPrefix(withUse, 'project')+ : withUse;+ if (btn) btn.disabled = true;+ let convId = '';+ try {+ const res = await apiFetch('/api/conversations/create', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ kind: 'normal', projectId: _projectDetailPid }),+ });+ const data = await res.json();+ if (!data.ok) throw new Error(data.error || t('chat.create_conv_failed'));+ const conv = data.conversation;+ convId = conv.conversation_id;+ conv.title = (typeof _autoTitle === 'function') ? _autoTitle(raw) : raw.slice(0, 32);+ conversations.unshift(conv);+ renderConversationList();+ if (typeof loadProjects === 'function') loadProjects(true);+ } catch (err) {+ if (typeof uiAlert === 'function') {+ await uiAlert(t('chat.create_conv_failed_with_reason', { reason: err?.message || err }));+ }+ if (btn) btn.disabled = false;+ return;+ }++ if (input) {+ input.value = '';+ if (typeof autoGrow === 'function') autoGrow(input, 180);+ }+ const chatInput = document.getElementById('chat-input');+ if (chatInput) {+ chatInput.value = '';+ if (typeof autoGrow === 'function') autoGrow(chatInput, 200);+ }+ if (typeof setView === 'function') setView('conversation', convId, { skipLoad: true });+ if (recipient && typeof setChatRecipient === 'function') {+ setChatRecipient('conversation', recipient);+ }+ if (useSelection && typeof setChatUseSelection === 'function') {+ setChatUseSelection('conversation', useSelection);+ }+ if (btn) btn.disabled = false;+ if (typeof sendInCurrentConversation === 'function') {+ await sendInCurrentConversation(content);+ }+}+function _activeLang() {if (typeof getLang === 'function') return getLang();return 'en';@@ -124,6 +330,18 @@ function _pickItemDescription(item, lang) {return (typeof pickDesc === 'function') ? pickDesc(item, lang) : '';}+function _projectBindingSourceHtml(source, kind) {+ if (!source) return '';+ const label = (typeof catalogSourceLabel === 'function')+ ? catalogSourceLabel(source, kind === 'skill' ? 'skills' : 'agents')+ : String(source);+ if (!label) return '';+ const normalized = (typeof normalizeCatalogSource === 'function')+ ? normalizeCatalogSource(source)+ : String(source);+ return `<span class="project-binding-source project-binding-source--${escapeHtml(normalized)}">${escapeHtml(label)}</span>`;+}+function _bindRemoveButtons() {document.querySelectorAll('#project-detail-content [data-action="remove"]').forEach((btn) => {btn.addEventListener('click', async (e) => {@@ -216,7 +434,7 @@ async function _openAddPicker(kind) {const name = escapeHtml(c.name || id);const desc = _pickItemDescription(c, lang);const descHtml = desc ? `<div class="project-binding-desc muted">${escapeHtml(desc)}</div>` : '';- const source = c.source ? `<span class="project-binding-source">${escapeHtml(c.source)}</span>` : '';+ const source = _projectBindingSourceHtml(c.source, kind);return `<div class="project-binding-picker-item" data-kind="${kind}" data-id="${escapeHtml(id)}"><div class="project-binding-main">@@ -286,16 +504,7 @@ async function _openAddPicker(kind) {setTimeout(() => searchEl.focus(), 0);}-// ── Header actions: New chat / Rename / Delete ────────────────────────--function _onNewConvAction() {- if (!_projectDetailPid) return;- // Pin pid into the commander chip's localStorage key so the new-chat- // panel mounts with this project pre-selected. Mirrors- // `projects.js::_newConvWithProject` semantics — keep the key in sync.- try { localStorage.setItem('commander.lastProject', _projectDetailPid); } catch (_) {}- if (typeof setView === 'function') setView('new-chat');-}+// ── Header actions: Rename / Delete ────────────────────────────────────function _onRenameAction() {if (!_projectDetailMeta) return;@@ -373,6 +582,11 @@ async function _onDeleteAction() {// ── Empty-bindings banner inside in-project conversations ─────────────+function _setConvProjectBannerVisible(visible) {+ const pane = document.querySelector('#panel-conversation .chat-main-pane');+ if (pane) pane.classList.toggle('has-project-empty-banner', !!visible);+}+async function refreshConvProjectEmptyBanner(cid) {const banner = document.getElementById('conv-project-empty-banner');if (!banner) return;@@ -384,6 +598,7 @@ async function refreshConvProjectEmptyBanner(cid) {if (!pid) {banner.style.display = 'none';delete banner.dataset.pid;+ _setConvProjectBannerVisible(false);return;}try {@@ -393,9 +608,13 @@ async function refreshConvProjectEmptyBanner(cid) {// gates whether the user can do anything inside this project.const isEmpty = !(b.agents || []).length;banner.style.display = isEmpty ? '' : 'none';- banner.dataset.pid = pid;+ if (isEmpty) banner.dataset.pid = pid;+ else delete banner.dataset.pid;+ _setConvProjectBannerVisible(isEmpty);} catch (_) {banner.style.display = 'none';+ delete banner.dataset.pid;+ _setConvProjectBannerVisible(false);}}@@ -410,10 +629,6 @@ document.addEventListener('DOMContentLoaded', () => {e.stopPropagation();_openAddPicker('skill');});- document.getElementById('project-action-new-conv')?.addEventListener('click', (e) => {- e.stopPropagation();- _onNewConvAction();- });document.getElementById('project-action-rename')?.addEventListener('click', (e) => {e.stopPropagation();_onRenameAction();@@ -422,6 +637,35 @@ document.addEventListener('DOMContentLoaded', () => {e.stopPropagation();_onDeleteAction();});+ document.getElementById('project-add-file-btn')?.addEventListener('click', (e) => {+ e.stopPropagation();+ document.getElementById('project-file-input')?.click();+ });+ document.getElementById('project-chat-attach-btn')?.addEventListener('click', (e) => {+ e.stopPropagation();+ document.getElementById('project-file-input')?.click();+ });+ document.getElementById('project-file-input')?.addEventListener('change', async (e) => {+ await _uploadProjectFiles(e.target.files);+ e.target.value = '';+ });+ const projectInput = document.getElementById('project-chat-input');+ if (projectInput) {+ projectInput.addEventListener('input', () => {+ if (typeof autoGrow === 'function') autoGrow(projectInput, 180);+ });+ projectInput.addEventListener('keydown', (e) => {+ if (e.isComposing || e.keyCode === 229) return;+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ _submitProjectChat();+ }+ });+ }+ document.getElementById('project-chat-send-btn')?.addEventListener('click', (e) => {+ e.stopPropagation();+ _submitProjectChat();+ });// Inline rename input handlers.const inputEl = document.getElementById('project-detail-title-input');if (inputEl) {diff --git a/src/renderer/modules/projects.js b/src/renderer/modules/projects.jsindex 62e65253..15348a0c 100644--- a/src/renderer/modules/projects.js+++ b/src/renderer/modules/projects.js@@ -155,6 +155,7 @@ function _renderInlineCreateRow() {function _renderProjectRow(p, convs) {const expanded = !!_projectsExpanded[p.project_id];+ const selected = _isProjectSelected(p.project_id);const editing = _projectsInlineRenamePid === p.project_id;const folderIcon = expanded? _projectUiIconHtml('folder-open', 'project-folder-icon')@@ -166,7 +167,7 @@ function _renderProjectRow(p, convs) {value="${escapeHtml(p.name || '')}" autocomplete="off" spellcheck="false" />`: `<span class="project-name" title="${safeName}">${safeName}</span>`;let html = `- <div class="project-row" data-pid="${escapeHtml(p.project_id)}">+ <div class="project-row${selected ? ' active' : ''}" data-pid="${escapeHtml(p.project_id)}"><span class="project-icon">${folderIcon}</span>${nameNode}<button type="button" class="ctx-row-menu-btn project-row-menu-btn" data-project-menu@@ -190,6 +191,12 @@ function _renderProjectRow(p, convs) {return html;}+function _isProjectSelected(pid) {+ return currentView === 'project'+ && typeof _projectDetailPid !== 'undefined'+ && _projectDetailPid === pid;+}+// ── Event wiring ────────────────────────────────────────────────────────function _bindProjectsHandlers(container) {@@ -202,9 +209,9 @@ function _bindProjectsHandlers(container) {_bindInlineRenameInput(input);});- // Project rows: any click → BOTH open the detail page AND toggle the- // expand state of nested conversations (per design — single click does- // both). Exceptions: ⋯ opens its menu; rename input swallows click.+ // Project rows: first click selects/opens the project detail. Once that+ // project is already selected, clicking the row toggles its nested+ // conversations.container.querySelectorAll('.project-row[data-pid]').forEach((row) => {const pid = row.dataset.pid;row.addEventListener('click', (e) => {@@ -217,8 +224,12 @@ function _bindProjectsHandlers(container) {_openProjectRowMenu(e.target.closest('[data-project-menu]'), pid);return;}+ if (!_isProjectSelected(pid)) {+ if (typeof setView === 'function') setView('project', pid);+ renderProjectsSection();+ return;+ }_toggleProjectExpand(pid);- if (typeof setView === 'function') setView('project', pid);});});@@ -405,7 +416,6 @@ function _openProjectRowMenu(anchorBtn, pid) {_closeProjectRowMenu();const items = [- { action: 'new_conv', label: t('project.menu.new_conv') },{ action: 'rename', label: t('project.menu.rename') },{ action: 'delete', label: t('project.menu.delete'), danger: true },];@@ -456,20 +466,10 @@ function _closeProjectRowMenu() {}async function _runProjectMenuAction(action, pid) {- if (action === 'new_conv') return _newConvWithProject(pid);if (action === 'rename') return _startProjectInlineRename(pid);if (action === 'delete') return _confirmDeleteProject(pid);}-// Pin pid into the commander chip's localStorage key BEFORE switching view —-// onEnterCommanderProjectChip (fired from boot.js view-change) reads the same-// key and re-validates against _projectsCache, so by the time the new-chat-// panel mounts the chip is already showing this project.-function _newConvWithProject(pid) {- try { localStorage.setItem(_COMMANDER_LAST_PROJECT_KEY, pid); } catch (_) {}- setView('new-chat');-}-// ── Delete flow ─────────────────────────────────────────────────────────async function _confirmDeleteProject(pid) {diff --git a/src/renderer/modules/search.js b/src/renderer/modules/search.jsindex 057766c1..91351980 100644--- a/src/renderer/modules/search.js+++ b/src/renderer/modules/search.js@@ -212,7 +212,8 @@ const _SEARCH_KIND_META = {const _SEARCH_SOURCE_LABEL = {custom: 'search.source.custom',- builtin: 'search.source.builtin',+ builtin: 'search.source.marketplace',+ marketplace: 'search.source.marketplace',};// Render one result into HTML. Uses the shared `_renderSearchRow` helper for@@ -235,7 +236,8 @@ function _renderSearchRow(r, dataIdx, query) {}} else if (r.kind === 'agent' || r.kind === 'skill') {title = r.name || r.id;- const srcKey = _SEARCH_SOURCE_LABEL[r.source] || '';+ const source = (typeof normalizeCatalogSource === 'function') ? normalizeCatalogSource(r.source) : r.source;+ const srcKey = _SEARCH_SOURCE_LABEL[source] || _SEARCH_SOURCE_LABEL[r.source] || '';sub = srcKey ? t(srcKey) : '';}const active = dataIdx === _searchActiveIdx ? ' active' : '';@@ -418,4 +420,3 @@ function _saveSearchHistoryEntry(query) {cur.unshift(q);_saveSearchHistory(cur.slice(0, _SEARCH_HISTORY_MAX));}-diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.jsindex 66708dc4..a3dcb59f 100644--- a/src/renderer/modules/skills.js+++ b/src/renderer/modules/skills.js@@ -4,6 +4,19 @@ const _skillsLog = createLogger('skills');let _skillsCache = null;let _selectedSkill = null; // { source, id }const _SKILL_SPEC_CATEGORY_CODE_RE = /^[a-z][a-z0-9_-]{0,79}$/;++function _skillSource(source) {+ return (typeof normalizeCatalogSource === 'function')+ ? normalizeCatalogSource(source)+ : String(source || '');+}++function _isSkillPlatformSource(source) {+ return (typeof isMarketplaceCatalogSource === 'function')+ ? isMarketplaceCatalogSource(source)+ : _skillSource(source) === 'marketplace';+}+function _normalizeSkillCategoryForHiddenSave(category) {const code = String(category || '').trim().toLowerCase();return _SKILL_SPEC_CATEGORY_CODE_RE.test(code) ? code : 'general';@@ -55,7 +68,7 @@ async function refreshSkillsAfterMarketplaceReconcile() {_skillTreeCache.clear();await loadSkills(true);if (_skillEditMode) return;- if (_selectedSkill?.id && _selectedSkill.source === 'builtin') {+ if (_selectedSkill?.id && _isSkillPlatformSource(_selectedSkill.source)) {const source = _selectedSkill.source;const id = _selectedSkill.id;const filepath = _selectedSkill.filepath || 'SKILL.md';@@ -75,7 +88,10 @@ async function loadSkills(forceRefresh) {const res = await apiFetch('/api/skills/list');const data = await res.json();if (data.ok) {- _skillsCache = data.skills || [];+ _skillsCache = (data.skills || []).map((s) => ({+ ...s,+ source: _skillSource(s.source),+ }));renderSkillsList(_skillsCache);}} catch (e) {@@ -89,7 +105,7 @@ async function loadSkills(forceRefresh) {// mutually exclusive because both are textual routing hints prepended to the// next message; agents remain separate in the recipient chip.-const _chatUse = { 'new-chat': null, 'conversation': null };+const _chatUse = { 'new-chat': null, 'conversation': null, project: null };function bindSkillPicker() {// Chip remove (×)@@ -163,7 +179,9 @@ function _renderChatUseChipLabel(labelEl, selection) {function _renderChatUseChip(target) {const next = _normalizeChatUseSelection(_chatUse[target]);- const chipId = target === 'new-chat' ? 'new-chat-skill-chip' : 'chat-skill-chip';+ const chipId = target === 'new-chat'+ ? 'new-chat-skill-chip'+ : (target === 'project' ? 'project-chat-skill-chip' : 'chat-skill-chip');const chip = document.getElementById(chipId);if (!chip) return;if (!next) {@@ -187,6 +205,7 @@ function _renderChatUseChip(target) {function refreshChatUseChips() {_renderChatUseChip('new-chat');_renderChatUseChip('conversation');+ _renderChatUseChip('project');}function setChatUseSelection(target, selection) {@@ -200,7 +219,7 @@ function setChatUseSelection(target, selection) {// Return focus to the textarea after selection.const input = target === 'new-chat'? document.getElementById('new-chat-input')- : document.getElementById('chat-input');+ : (target === 'project' ? document.getElementById('project-chat-input') : document.getElementById('chat-input'));input?.focus();}@@ -242,7 +261,7 @@ function renderSkillsList(skills) { renderSkillsGrid(skills); }function renderSkillsGrid(skills) {const custom = skills.filter(s => s.source === 'custom');- const builtin = skills.filter(s => s.source === 'builtin');+ const marketplace = skills.filter(s => _isSkillPlatformSource(s.source));const emptyEl = document.getElementById('skills-empty');const customGroup = document.getElementById('skills-grid-custom-group');const builtinGroup = document.getElementById('skills-grid-builtin-group');@@ -264,14 +283,14 @@ function renderSkillsGrid(skills) {const desc = pickDesc(s, getLang()).trim();const descClass = desc ? 'skill-card-desc' : 'skill-card-desc is-empty';const descText = desc || t('skills.no_desc');- // Source label (custom / builtin) is shown on the detail page only;+ // Source label (custom / marketplace) is shown on the detail page only;// the grid cards stay clean and use the ⋯ menu for actions.const moreBtn = `<button type="button" class="skill-card-more" data-skill-more title="${moreTitle}" aria-label="${moreTitle}">⋯</button>`;const enabled = s.enabled !== false;- // Marketplace-installed (`builtin`) skills carry version + category from _install.json /+ // Marketplace-installed skills carry version + category from _install.json /// SKILL.md frontmatter — show them as inline chips so users see provenance without// opening the detail page. Custom skills skip (no published version).- const platformChips = s.source === 'builtin' ? _skillPlatformChipsHtml(s) : '';+ const platformChips = _isSkillPlatformSource(s.source) ? _skillPlatformChipsHtml(s) : '';return `<div class="skill-card${enabled ? '' : ' is-disabled'}" data-id="${escapeHtml(s.id)}" data-source="${s.source}"><div class="skill-card-header">@@ -295,7 +314,7 @@ function renderSkillsGrid(skills) {gridEl.innerHTML = list.map(cardHtml).join('');};renderGroup(custom, customGroup, customGrid);- renderGroup(builtin, builtinGroup, builtinGrid);+ renderGroup(marketplace, builtinGroup, builtinGrid);// Wire card / ▶ / ⋯ click handlers. (Enable/disable lives in the ⋯ menu// now — no toggle switch on the card.)@@ -373,6 +392,7 @@ function _showSkillsGridView() {}async function _showSkillsDetailView(source, id) {+ source = _skillSource(source);const grid = document.getElementById('skills-grid-view');const detail = document.getElementById('skills-detail-view');if (grid) grid.style.display = 'none';@@ -447,6 +467,10 @@ function _openSkillRowMenu(anchorBtn, id, source) {// Dev-only entry on builtin: tag the label so the user knows this isn't a// normal user capability (mirrors marketplace.upload's "(dev)" treatment).const editLabelSuffix = (source === 'builtin' && false) ? t('common.dev_suffix') : '';+ const canEdit = source === 'custom' || (_isSkillPlatformSource(source) && false);+ // Dev-only entry on marketplace items: tag the label so the user knows this isn't a+ // normal user capability (mirrors marketplace.upload's "(dev)" treatment).+ const editLabelSuffix = (_isSkillPlatformSource(source) && false) ? t('common.dev_suffix') : '';const items = [];if (canEdit) {items.push(`<div class="skill-row-menu-item" data-action="edit">${escapeHtml(t('skills.edit') + editLabelSuffix)}</div>`);@@ -548,6 +572,7 @@ async function _toggleSkillsSource() {}async function expandSkillTree(source, id, childrenEl) {+ source = _skillSource(source);const key = `${source}:${id}`;let tree = _skillTreeCache.get(key);if (!tree) {@@ -675,6 +700,7 @@ function findDirInTree(tree, targetPath) {}async function selectSkillFile(source, id, filepath, nodeEl) {+ source = _skillSource(source);const skill = _skillsCache?.find(s => s.id === id && s.source === source);// Detect "same-skill file switch" vs initial / cross-skill load — only the// former needs scroll preservation (user is mid-page browsing source files).@@ -721,6 +747,7 @@ async function selectSkillFile(source, id, filepath, nodeEl) {// In edit mode only the "done" button (the relabeled "edit") is// shown; everything else hides.const canEditThisSkill = source === 'custom';+ const canEditThisSkill = source === 'custom' || (_isSkillPlatformSource(source) && false);const editingThis = _skillEditMode && _skillEditSkillId === id && canEditThisSkill;const actions = document.getElementById('skills-detail-actions');if (actions) {@@ -1160,9 +1187,10 @@ function _updateEditButtonLabel() {btn.textContent = t('skills.edit_btn_done');return;}- // Tag the "Edit" label on builtin skills (dev-only entry); the "Done"+ // Tag the "Edit" label on marketplace skills (dev-only entry); the "Done"// branch above stays bare — in edit mode the marker is redundant.const suffix = (_selectedSkill?.source === 'builtin' && false) ? t('common.dev_suffix') : '';+ const suffix = (_isSkillPlatformSource(_selectedSkill?.source) && false) ? t('common.dev_suffix') : '';btn.textContent = t('skills.edit_btn_edit') + suffix;}@@ -1176,6 +1204,9 @@ function _updateEditButtonLabel() {async function toggleSkillEditMode(opts = {}) {if (!_selectedSkill) return;if (_selectedSkill.source !== 'custom') return;+ // Marketplace editing is dev-only; lift the source guard accordingly.+ if (_selectedSkill.source !== 'custom'+ && !(_isSkillPlatformSource(_selectedSkill.source) && false)) return;if (_skillEditMode && _skillEditSkillId === _selectedSkill.id) {// Abort any in-flight reply so "done" means "stop + exit", not// "exit but keep streaming". The chat controller is a singleton;@@ -1570,11 +1601,16 @@ function editSelectedSkill() {async function deleteSelectedSkill() {if (!_selectedSkill) return;if (_selectedSkill.source !== 'custom') return;+ const src = _selectedSkill.source;+ if (src !== 'custom' && !(_isSkillPlatformSource(src) && false)) return;const sid = _selectedSkill.id;const cached = _skillsCache?.find(s => s.id === sid && s.source === 'custom');if (!(await uiConfirm(t('skills.delete_confirm', { name: cached?.name || sid })))) return;try {const result = await (await apiFetch(`/api/skills/${sid}`, { method: 'DELETE' })).json();+ const result = _isSkillPlatformSource(src)+ ? await window.orkas.invoke('skills.builtin.delete', { id: sid })+ : await (await apiFetch(`/api/skills/${sid}`, { method: 'DELETE' })).json();if (!result.ok) {await uiAlert(t('skills.delete_failed_with', { reason: result.error || '' }));return;diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.jsindex ddc4e372..89277c1e 100644--- a/src/renderer/modules/state.js+++ b/src/renderer/modules/state.js@@ -287,9 +287,6 @@ function bindStaticHandlers() {});document.getElementById('agent-edit-btn')?.addEventListener('click', toggleAgentEditMode);document.getElementById('agent-delete-btn')?.addEventListener('click', deleteSelectedAgent);- document.getElementById('agent-promote-btn')?.addEventListener('click', () => {- if (_selectedAgent?.source === 'custom') promoteCustomAgent(_selectedAgent.id);- });document.getElementById('agent-upload-marketplace-btn')?.addEventListener('click', () => {// Upload is allowed for both custom AND builtin (dev mode) — same// marketplace publishing flow per CLAUDE.md §11. The row-menu handler@@ -329,9 +326,6 @@ function bindStaticHandlers() {});document.getElementById('skill-edit-btn')?.addEventListener('click', toggleSkillEditMode);document.getElementById('skill-delete-btn')?.addEventListener('click', deleteSelectedSkill);- document.getElementById('skill-promote-btn')?.addEventListener('click', () => {- if (_selectedSkill?.source === 'custom') promoteCustomSkill(_selectedSkill.id);- });document.getElementById('skill-upload-marketplace-btn')?.addEventListener('click', () => {// Upload is allowed for both custom AND builtin (dev mode) — same as// the agent upload handler above; see comment there.diff --git a/src/renderer/modules/strip-structural-blocks.js b/src/renderer/modules/strip-structural-blocks.jsindex de5df558..b7b3f196 100644--- a/src/renderer/modules/strip-structural-blocks.js+++ b/src/renderer/modules/strip-structural-blocks.js@@ -437,6 +437,15 @@ function _replaceOuterSkillFileBlocks(buf, makePlaceholder) {return out;}+function _collapseRepeatedStructuralPlaceholders(buf, placeholder) {+ if (!buf || !placeholder) return buf;+ const marker = String(placeholder).trim();+ if (!marker) return buf;+ const escaped = marker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const collapsed = String(buf).replace(new RegExp(`${escaped}(?:\\s*${escaped})+`, 'g'), marker);+ return collapsed.replace(/\n{3,}/g, '\n\n');+}+// Streaming-time strip for the commander's `<skill>` container. Two modes:// - **Closed** `<skill>...</skill>` → strip outer tags + any `<skill_id>`// sub-tag, keep the inner content. The inner `<<<skill-file>>>` blocks@@ -610,5 +619,6 @@ if (typeof module !== 'undefined' && typeof module.exports === 'object') {_replaceKnownSkillIdsForDisplay,_simplifyKnownSkillFollowPhrasesForDisplay,_normalizeKnownSkillRefsForDisplay,+ _collapseRepeatedStructuralPlaceholders,};}diff --git a/src/renderer/modules/text-view-edit.js b/src/renderer/modules/text-view-edit.jsnew file mode 100644index 00000000..720bff1b--- /dev/null+++ b/src/renderer/modules/text-view-edit.js@@ -0,0 +1,257 @@+// ─── Plain-text view/edit controller ────────────────────────────────────+// Sibling to `mountMdViewEdit` for chat-file-viewer's non-markdown text+// files (.py, .json, .csv, .log, source code, etc.). Same controller shape+// (`destroy / isDirty / getMode / setMode`) so chat-file-viewer can hold+// either MD or text controller in `_viewerEditController` without branching.+//+// Why a sibling instead of a `plainText` flag on mountMdViewEdit:+// - Plain text has no markdown toolbar, no preview toggle, no+// task-checkbox interactivity. Threading `plainText: true` through+// md-view-edit would mean three `if (!plainText) …` branches in the+// editor / view paths — duplicating logic at the call site is less+// code than gating each rendering primitive.+// - PC/CLAUDE.md §8 "only md files show the md toolbar" — a physical+// module boundary makes that invariant unforgeable; adding a flag+// leaves the toolbar visible if anyone later forgets the gate.+//+// Backend reuse: same `produced.readText` / `produced.writeText` IPC as+// the workspace branch of md-view-edit. Path-sandbox + 2 MB read cap+// already enforced on the main side, so nothing new to validate here.+//+// Source shape: { absPath: string, cid?: string, projectId?: string }+// `cid` widens the read/write scope to include this conversation's+// attachment dir; `projectId` widens it to the project file pool.++const _tveLog = createLogger('text-view-edit');++/**+ * Mount a plain-text view/edit surface inside `bodyEl` with action buttons+ * placed in `actionsEl` (Edit in view mode; Save+Cancel in edit mode).+ *+ * Required: opts.bodyEl, opts.actionsEl, opts.source.absPath.+ * Optional: opts.initialContent (skips the initial read), opts.initialMode+ * ('view' default), opts.actionIconOnly, opts.capabilities+ * ({ edit, save } — defaults true; pass { edit: false } to lock+ * read-only for project files etc.), opts.callbacks+ * ({ onDirtyChange, onSaved, onContentLoaded }).+ *+ * Returns a noop-shell controller on misuse rather than throwing — the+ * call site has no good fallback if mount fails after the overlay opened.+ */+function mountTextViewEdit(opts) {+ const bodyEl = opts && opts.bodyEl;+ const actionsEl = opts && opts.actionsEl;+ if (!bodyEl || !actionsEl) {+ _tveLog.warn('mountTextViewEdit called without bodyEl/actionsEl', { hasBody: !!bodyEl, hasActions: !!actionsEl });+ return _tveNoopController();+ }+ const source = opts.source;+ if (!source || typeof source.absPath !== 'string' || !source.absPath) {+ _tveLog.warn('mountTextViewEdit called without source.absPath');+ return _tveNoopController();+ }++ const caps = Object.assign({ edit: true, save: true }, opts.capabilities || {});+ const callbacks = opts.callbacks || {};++ const state = {+ source,+ caps,+ callbacks,+ bodyEl,+ actionsEl,+ actionIconOnly: opts.actionIconOnly === true,+ content: typeof opts.initialContent === 'string' ? opts.initialContent : '',+ draft: '',+ mode: opts.initialMode === 'edit' ? 'edit' : 'view',+ destroyed: false,+ };+ state.draft = state.content;++ if (typeof opts.initialContent !== 'string') {+ _tveLoadAndRender(state);+ } else {+ _tveRender(state);+ }++ function destroy() {+ state.destroyed = true;+ if (bodyEl) bodyEl.innerHTML = '';+ if (actionsEl) actionsEl.innerHTML = '';+ }+ function isDirty() { return state.mode === 'edit' && state.draft !== state.content; }+ function getMode() { return state.mode; }+ function setMode(m) {+ if (state.destroyed) return;+ if (m !== 'view' && m !== 'edit') return;+ if (m === 'edit') _tveEnterEdit(state);+ else _tveRenderView(state);+ }+ async function refreshContent() {+ if (state.destroyed) return;+ await _tveLoadAndRender(state);+ }++ return { destroy, isDirty, getMode, setMode, refreshContent };+}++function _tveNoopController() {+ return {+ destroy() {},+ isDirty() { return false; },+ getMode() { return 'view'; },+ setMode() {},+ refreshContent() {},+ };+}++async function _tveLoadAndRender(state) {+ state.bodyEl.innerHTML = `<div class="chat-file-viewer-loading">…</div>`;+ state.actionsEl.innerHTML = '';+ try {+ const payload = { path: state.source.absPath };+ if (state.source.cid) payload.cid = state.source.cid;+ if (state.source.projectId) payload.projectId = state.source.projectId;+ const res = await window.orkas.invoke('produced.readText', payload);+ if (state.destroyed) return;+ if (!res || !res.ok) {+ _tveRenderError(state, (res && res.error) || 'read_failed');+ return;+ }+ state.content = String(res.text || '');+ state.draft = state.content;+ if (state.callbacks.onContentLoaded) {+ try { state.callbacks.onContentLoaded(state.content); }+ catch (err) { _tveLog.warn('onContentLoaded threw', err); }+ }+ _tveRender(state);+ } catch (err) {+ if (state.destroyed) return;+ _tveRenderError(state, err && err.message || String(err));+ }+}++function _tveRenderError(state, msg) {+ state.bodyEl.innerHTML = `<div class="chat-file-viewer-loading">${escapeHtml(_tveLabel('contexts.viewer.read_failed', `Failed to read file: ${msg}`, { reason: msg }))}</div>`;+ state.actionsEl.innerHTML = '';+}++function _tveRender(state) {+ if (state.destroyed) return;+ if (state.mode === 'edit') _tveRenderEditor(state);+ else _tveRenderView(state);+}++function _tveRenderView(state) {+ state.mode = 'view';+ state.bodyEl.innerHTML = `<pre class="chat-file-viewer-text">${escapeHtml(state.content)}</pre>`;+ const actions = [];+ if (state.caps.edit) actions.push(_tveActionButton(state, 'edit', 'contexts.viewer.edit', 'pencil'));+ state.actionsEl.innerHTML = actions.join('');+ state.actionsEl.querySelector('[data-tve-action="edit"]')?.addEventListener('click', () => _tveEnterEdit(state));+ _tveEmitDirty(state);+}++function _tveEnterEdit(state) {+ if (!state.caps.edit) return;+ state.mode = 'edit';+ state.draft = state.content;+ _tveRenderEditor(state);+ _tveEmitDirty(state);+}++function _tveRenderEditor(state) {+ // Tab key in the textarea inserts \t instead of moving focus — for code /+ // config files this matters (the alternative — sending tab to focus the+ // next action button — has no point inside a fullscreen editor).+ state.bodyEl.innerHTML = `<textarea class="ctx-viewer-editor" data-tve-textarea spellcheck="false">${escapeHtml(state.draft)}</textarea>`;+ const actions = [];+ if (state.caps.save) {+ actions.push(_tveActionButton(state, 'save', 'contexts.viewer.save', 'check', 'btn-primary'));+ actions.push(_tveActionButton(state, 'cancel', 'contexts.viewer.cancel', 'x'));+ }+ state.actionsEl.innerHTML = actions.join('');+ state.actionsEl.querySelector('[data-tve-action="save"]')?.addEventListener('click', () => _tveSave(state));+ state.actionsEl.querySelector('[data-tve-action="cancel"]')?.addEventListener('click', () => _tveCancelEdit(state));++ const ta = state.bodyEl.querySelector('[data-tve-textarea]');+ if (ta) {+ ta.addEventListener('input', () => {+ state.draft = ta.value;+ _tveEmitDirty(state);+ });+ ta.addEventListener('keydown', (e) => {+ if (e.key === 'Tab') {+ e.preventDefault();+ const start = ta.selectionStart;+ const end = ta.selectionEnd;+ const before = ta.value.slice(0, start);+ const after = ta.value.slice(end);+ ta.value = `${before}\t${after}`;+ ta.selectionStart = ta.selectionEnd = start + 1;+ state.draft = ta.value;+ _tveEmitDirty(state);+ }+ });+ ta.focus();+ }+ _tveEmitDirty(state);+}++function _tveCancelEdit(state) {+ state.draft = state.content;+ _tveRenderView(state);+}++async function _tveSave(state) {+ const ta = state.bodyEl.querySelector('[data-tve-textarea]');+ if (ta) state.draft = ta.value;+ const next = state.draft;+ try {+ const payload = { path: state.source.absPath, content: next };+ if (state.source.cid) payload.cid = state.source.cid;+ if (state.source.projectId) payload.projectId = state.source.projectId;+ const res = await window.orkas.invoke('produced.writeText', payload);+ if (!res || !res.ok) {+ await uiAlert(_tveLabel('contexts.save_failed_with', `Save failed: ${(res && res.error) || 'unknown'}`, { reason: (res && res.error) || 'unknown' }));+ return;+ }+ } catch (err) {+ await uiAlert(_tveLabel('contexts.save_failed_with', `Save failed: ${err && err.message || err}`, { reason: err && err.message || String(err) }));+ return;+ }+ state.content = next;+ _tveRenderView(state);+ if (state.callbacks.onSaved) {+ try { state.callbacks.onSaved(next); }+ catch (err) { _tveLog.warn('onSaved threw', err); }+ }+}++function _tveActionButton(state, action, labelKey, iconName, extraClass) {+ const label = _tveLabel(labelKey, labelKey);+ const cls = `btn btn-sm${state.actionIconOnly ? ' btn-icon ctx-viewer-action-icon-btn' : ''}${extraClass ? ` ${extraClass}` : ''}`;+ if (!state.actionIconOnly) {+ return `<button type="button" class="${cls}" data-tve-action="${action}">${escapeHtml(label)}</button>`;+ }+ const icon = (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function')+ ? window.uiIconHtml(iconName, 'ui-icon ctx-viewer-action-icon')+ : escapeHtml(label);+ return `<button type="button" class="${cls}" data-tve-action="${action}" aria-label="${escapeHtml(label)}" title="${escapeHtml(label)}">${icon}</button>`;+}++function _tveEmitDirty(state) {+ if (state.callbacks.onDirtyChange) {+ try { state.callbacks.onDirtyChange(state.mode === 'edit' && state.draft !== state.content); }+ catch (err) { _tveLog.warn('onDirtyChange threw', err); }+ }+}++// Localized label helper — falls back to the provided English when the+// key is missing. Mirrors chat-file-viewer's `_viewerLabel`.+function _tveLabel(key, fallback, vars) {+ try {+ const v = vars ? t(key, vars) : t(key);+ return v === key ? fallback : v;+ } catch (_) { return fallback; }+}diff --git a/src/renderer/modules/user-workspace.js b/src/renderer/modules/user-workspace.jsindex 0d9dce3b..db5e1490 100644--- a/src/renderer/modules/user-workspace.js+++ b/src/renderer/modules/user-workspace.js@@ -24,6 +24,7 @@ const _wsLog = createLogger('user-workspace');const _wsInfoByTarget = {'new-chat': { currentPath: '', defaultPath: '', isDefault: true, recentPaths: [], scope: 'default' },'conversation': { currentPath: '', defaultPath: '', isDefault: true, recentPaths: [], scope: 'default' },+ project: { currentPath: '', defaultPath: '', isDefault: true, recentPaths: [], scope: 'default' },};// ── Workspace display helpers ───────────────────────────────────────@@ -42,6 +43,10 @@ function _wsScopeHintFor(target) {if (target === 'conversation') {return currentCid ? { cid: currentCid } : {};}+ if (target === 'project') {+ const pid = (typeof _projectDetailPid !== 'undefined') ? (_projectDetailPid || '') : '';+ return pid ? { projectId: pid } : {};+ }// new-chat / commander panelif (typeof getCommanderProjectId === 'function') {const pid = getCommanderProjectId();@@ -55,7 +60,7 @@ function _updateChipForTarget(target) {const info = _wsInfoByTarget[target] || _wsInfoByTarget['conversation'];const sel = target === 'new-chat'? '#panel-new-chat .workspace-chip'- : '#panel-conversation .workspace-chip';+ : (target === 'project' ? '#panel-project .workspace-chip' : '#panel-conversation .workspace-chip');const chip = document.querySelector(sel);if (!chip) return;const label = chip.querySelector('.workspace-chip-label');@@ -75,6 +80,7 @@ function _updateChipForTarget(target) {function _updateAllChips() {_updateChipForTarget('new-chat');_updateChipForTarget('conversation');+ _updateChipForTarget('project');}// ── Core actions ────────────────────────────────────────────────────@@ -101,7 +107,7 @@ async function _fetchWorkspaceInfo(target) {/** Refetch info for both targets — called on boot, on commander chip change,* and on conversation switch. */async function _refreshAllWorkspaceInfo() {- await Promise.all([_fetchWorkspaceInfo('new-chat'), _fetchWorkspaceInfo('conversation')]);+ await Promise.all([_fetchWorkspaceInfo('new-chat'), _fetchWorkspaceInfo('conversation'), _fetchWorkspaceInfo('project')]);_updateAllChips();}@@ -312,6 +318,13 @@ async function initUserWorkspace() {if (sendBtn) convBar.insertBefore(chip, sendBtn);else convBar.appendChild(chip);}+ const projectBar = document.querySelector('#panel-project .chat-bottom-bar');+ if (projectBar) {+ const sendBtn = projectBar.querySelector('.chat-send-btn');+ const chip = _createWorkspaceChip('project');+ if (sendBtn) projectBar.insertBefore(chip, sendBtn);+ else projectBar.appendChild(chip);+ }await _refreshAllWorkspaceInfo();}diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.jsindex ccb38592..5e1504fd 100644--- a/src/renderer/modules/utils.js+++ b/src/renderer/modules/utils.js@@ -52,6 +52,29 @@ function escapeHtml(str) {.replace(/"/g, '"').replace(/'/g, ''');}+function normalizeCatalogSource(source) {+ const s = String(source || '').trim().toLowerCase();+ if (s === 'builtin' || s === 'platform') return 'marketplace';+ if (s === 'custom') return 'custom';+ return s;+}++function isCustomCatalogSource(source) {+ return normalizeCatalogSource(source) === 'custom';+}++function isMarketplaceCatalogSource(source) {+ return normalizeCatalogSource(source) === 'marketplace';+}++function catalogSourceLabel(source, kind = 'agents') {+ const normalized = normalizeCatalogSource(source);+ const base = kind === 'skills' ? 'skills' : 'agents';+ if (normalized === 'custom') return t(`${base}.source_custom`);+ if (normalized === 'marketplace') return t(`${base}.source_marketplace`);+ return source ? String(source) : '';+}+// Full markdown renderer (used for skill detail view and chat)function renderMarkdownFull(md) {if (!md) return '';@@ -730,27 +753,11 @@ function nowIsoLocal() {* refreshes with backend's value and the sidebar entry visibly flips.* Empty input returns '' so the caller can fall back to its own* placeholder (`t('chat.new_conv_title')` for the conv list). */-const _AUTO_TITLE_ZH_FILLER = /^(帮我看一下|可不可以|帮我看下|帮我看看|麻烦你|帮我看|我想要|想问问|能不能|可以不|可以吗|请帮我|看一下|麻烦|帮我|我想|想问|请问|看下|看看)\s*/;-const _AUTO_TITLE_EN_FILLER = /^(could you|would you|can you|help me|i'?d like to|i want to|please)\s+/i;-const _AUTO_TITLE_CLAUSE = /[,。?!;;,.?!]/;-const _AUTO_TITLE_MAX = 30;-function _autoTitle(text) {- const raw = String(text == null ? '' : text).trim().replace(/\s+/g, ' ');- if (!raw) return '';- let s = raw;- for (let i = 0; i < 5; i++) {- const before = s;- s = s.replace(_AUTO_TITLE_ZH_FILLER, '').replace(_AUTO_TITLE_EN_FILLER, '');- if (s === before) break;- }- s = s.trim();- const clauseIdx = s.search(_AUTO_TITLE_CLAUSE);- if (clauseIdx >= 4) s = s.slice(0, clauseIdx);- s = s.trim();- if (!s) s = raw;- if (s.length > _AUTO_TITLE_MAX) s = s.slice(0, _AUTO_TITLE_MAX) + '…';- return s;-}+// `_autoTitle` + its regex constants live in `modules/auto-title.js` so the+// regex set has a single renderer-side home and a clean target for the+// `test/renderer/auto-title-parity.test.ts` parity check against+// `src/main/util/auto-title.ts`. The new file is loaded before consumers+// via `<script src="./modules/auto-title.js">` in index.html.function formatTime(iso) {if (!iso) return '-';diff --git a/src/renderer/style.css b/src/renderer/style.cssindex 95bb9bbe..475ff259 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -474,11 +474,22 @@ body.is-sidebar-resizing iframe { pointer-events: none; }text-align: left;}+.sidebar-btn [data-ui-icon] {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 15px;+ height: 15px;+ flex: 0 0 15px;+ line-height: 0;+}+.sidebar-btn-icon {width: 15px;height: 15px;flex: 0 0 15px;color: #94a3b8;+ display: block;}.sidebar-btn.active .sidebar-btn-icon {@@ -625,6 +636,8 @@ body.is-sidebar-resizing iframe { pointer-events: none; }position: relative;}.project-row:hover { background: #f1f5f9; color: var(--text); }+.project-row.active { background: #eff6ff; color: var(--primary); }+.project-row.active .project-icon { color: var(--primary); }.project-row.is-menu-open { background: #f1f5f9; }.project-icon {@@ -707,20 +720,25 @@ body.is-sidebar-resizing iframe { pointer-events: none; }.project-detail-content {flex: 1;overflow-y: auto;- padding: 22px 32px 32px 32px;- max-width: 880px;+ padding: 28px 32px 36px 32px;+ max-width: 1180px;width: 100%;margin: 0 auto;box-sizing: border-box;+ display: flex;+ flex-direction: column;}.project-detail-header {display: flex;align-items: center;- gap: 12px;- margin-bottom: 22px;+ gap: 16px;+ margin-bottom: 20px;}-.project-detail-title {+.project-detail-title-wrap {flex: 1;+ min-width: 0;+}+.project-detail-title {font-size: 22px;font-weight: 600;color: var(--text);@@ -731,7 +749,8 @@ body.is-sidebar-resizing iframe { pointer-events: none; }white-space: nowrap;}.project-detail-title-input {- flex: 1;+ width: 100%;+ box-sizing: border-box;font-size: 22px;font-weight: 600;color: var(--text);@@ -748,13 +767,76 @@ body.is-sidebar-resizing iframe { pointer-events: none; }gap: 8px;flex-shrink: 0;}+.project-detail-grid {+ flex: 1;+ display: grid;+ grid-template-columns: minmax(0, 1fr) 320px;+ gap: 28px;+ align-items: start;+ min-height: 380px;+}+.project-detail-main,+.project-detail-side {+ min-width: 0;+}+.project-detail-main {+ display: flex;+ flex-direction: column;+ justify-content: flex-start;+ padding-top: 8px;+}+.project-composer-card {+ width: 100%;+}+.project-composer-input-area {+ pointer-events: auto;+ display: flex;+ flex-direction: column;+ gap: 6px;+ background: #fff;+ border: 1px solid var(--primary);+ border-radius: 16px;+ padding: 10px 16px;+ box-shadow: 0 8px 32px rgba(37, 99, 235, 0.08);+ position: relative;+ transition: all 0.2s;+}+.project-composer-input-area:focus-within {+ border-color: var(--primary);+ box-shadow: 0 8px 32px rgba(37, 99, 235, 0.16);+ transform: translateY(-2px);+}+.project-composer-input-area textarea {+ flex: 0 1 auto;+ width: 100%;+ min-height: 62px;+ max-height: 220px;+ border: none;+ outline: none;+ resize: none;+ padding: 4px 4px;+ font-size: 15px;+ line-height: 1.55;+ color: var(--text);+ background: transparent;+ font-family: inherit;+}+.project-composer-input-area .chat-input-mirror {+ font-size: 15px;+}+.project-composer-bottom {+ min-height: 40px;+}+.project-chat-send-btn {+ margin-left: auto;+}/* Card-style section. Mirrors the look in shipping-product references —white card on neutral page bg, rounded corners, subtle border. */.project-detail-card {background: #fff;border: 1px solid #e5e7eb;- border-radius: 12px;+ border-radius: 8px;padding: 16px 18px;margin-bottom: 14px;box-shadow: 0 1px 2px rgba(15, 23, 42, 0.03);@@ -811,6 +893,8 @@ body.is-sidebar-resizing iframe { pointer-events: none; }padding: 1px 6px;border-radius: 4px;}+.project-binding-source--custom { color: #1d4ed8; background: #dbeafe; }+.project-binding-source--marketplace { color: #475569; background: #e2e8f0; }.project-binding-source--stale { color: #b45309; background: #fef3c7; }.project-binding-desc {font-size: 12px;@@ -900,6 +984,109 @@ body.is-sidebar-resizing iframe { pointer-events: none; }-webkit-box-orient: vertical;overflow: hidden;}+.project-card-icon-btn {+ width: 28px;+ height: 28px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border: none;+ border-radius: 6px;+ background: transparent;+ color: #64748b;+ font-size: 20px;+ line-height: 1;+ cursor: pointer;+}+.project-card-icon-btn:hover {+ background: #f1f5f9;+ color: var(--text);+}+.project-files-status {+ min-height: 18px;+ margin-top: 8px;+ font-size: 12px;+}+.project-files-list {+ display: flex;+ flex-direction: column;+ gap: 4px;+ margin-top: 4px;+}+.project-file-row {+ display: flex;+ align-items: center;+ gap: 8px;+ min-height: 32px;+ padding: 6px 4px;+ border-radius: 6px;+ color: #334155;+}+.project-file-row:hover { background: #f8fafc; }+.project-file-main {+ flex: 1;+ min-width: 0;+ display: flex;+ align-items: center;+ gap: 7px;+ border: none;+ background: transparent;+ color: inherit;+ font-family: inherit;+ text-align: left;+ cursor: pointer;+ padding: 0;+}+.project-file-icon {+ width: 18px;+ height: 18px;+ flex: 0 0 auto;+ display: inline-flex;+ align-items: center;+ justify-content: center;+}+.project-file-name {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 12.5px;+}+.project-file-meta {+ flex: 0 0 auto;+ color: #94a3b8;+ font-size: 11px;+}+.project-file-remove {+ width: 24px;+ height: 24px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border: none;+ border-radius: 6px;+ background: transparent;+ color: #94a3b8;+ cursor: pointer;+ font-size: 16px;+ line-height: 1;+}+.project-file-row:hover .project-file-remove { color: #64748b; }+.project-file-remove:hover {+ background: #fee2e2;+ color: #dc2626;+}++@media (max-width: 980px) {+ .project-detail-grid {+ grid-template-columns: 1fr;+ min-height: 0;+ }+ .project-detail-actions {+ flex-wrap: wrap;+ justify-content: flex-end;+ }+}/* Empty-bindings banner inside an in-project conversation. */.conv-project-empty-banner {@@ -2304,7 +2491,10 @@ body.model-not-configured .main-content { flex-direction: column; }color: #64748b;box-shadow: 0 6px 18px rgba(15, 23, 42, 0.08);cursor: pointer;- transition: background 120ms ease, color 120ms ease, border-color 120ms ease, box-shadow 120ms ease;+ transition: top 120ms ease, background 120ms ease, color 120ms ease, border-color 120ms ease, box-shadow 120ms ease;+}+.chat-main-pane.has-project-empty-banner .conversation-info-toggle {+ top: 62px;}.conversation-info-toggle:hover,.conversation-info-toggle.is-active {@@ -3342,6 +3532,49 @@ body.model-not-configured .main-content { flex-direction: column; }gap: 6px;flex-shrink: 0;}+.chat-file-viewer-md-actions {+ display: flex;+ align-items: center;+ gap: 6px;+}+.chat-file-viewer-md-actions:empty { display: none; }+.chat-file-viewer-md-actions .btn {+ min-height: 28px;+ white-space: nowrap;+}+.chat-file-viewer-md-actions .ctx-viewer-action-icon-btn {+ width: 28px;+ height: 28px;+ min-height: 28px;+ padding: 0;+ border-radius: 6px;+ border: none;+ background: transparent;+ color: #475569;+ display: inline-flex;+ align-items: center;+ justify-content: center;+}+.chat-file-viewer-md-actions .ctx-viewer-action-icon-btn:hover {+ background: #e2e8f0;+ color: #0f172a;+}+.chat-file-viewer-md-actions .ctx-viewer-action-icon-btn.btn-primary {+ background: transparent;+ color: var(--primary);+}+.chat-file-viewer-md-actions .ctx-viewer-action-icon-btn.btn-primary:hover {+ background: rgba(59, 130, 246, 0.10);+ color: var(--primary-hover);+}+.chat-file-viewer-md-actions .ctx-viewer-action-icon-btn.btn-danger {+ color: var(--danger);+}+.chat-file-viewer-md-actions .ctx-viewer-action-icon {+ width: 15px;+ height: 15px;+ display: block;+}.chat-file-viewer-reveal,.chat-file-viewer-close {width: 28px;@@ -3368,6 +3601,11 @@ body.model-not-configured .main-content { flex-direction: column; }overflow: auto;background: #fff;}+.chat-file-viewer.is-markdown .chat-file-viewer-body {+ display: flex;+ flex-direction: column;+ overflow: hidden;+}/* iframe-based body (pdf / html) fills the body slot. The body itselfhandles scroll for non-iframe bodies (md / text). */.chat-file-viewer-pdf,@@ -3398,6 +3636,53 @@ body.model-not-configured .main-content { flex-direction: column; }max-width: 880px;margin: 0 auto;}+.chat-file-viewer.is-markdown .chat-file-viewer-body > .ctx-viewer-md {+ flex: 1 1 auto;+ width: 100%;+ max-width: 880px;+ min-height: 0;+ margin: 0 auto;+ padding: 24px 32px;+ box-sizing: border-box;+ overflow: auto;+ color: #0f172a;+ font-size: 14px;+ line-height: 1.7;+}+.chat-file-viewer.is-markdown .ctx-editor-toolbar {+ flex: 0 0 auto;+ margin: 0;+ padding: 8px 12px;+ border: 0;+ border-bottom: 1px solid var(--border);+ border-radius: 0;+}+.chat-file-viewer.is-markdown .ctx-editor-body {+ flex: 1 1 auto;+ min-height: 0;+ display: flex;+}+.chat-file-viewer.is-markdown .ctx-viewer-editor {+ flex: 1 1 auto;+ min-height: 0;+ padding: 16px 20px;+ border: 0;+ border-radius: 0;+ outline: 0;+ resize: none;+}+.chat-file-viewer.is-markdown .ctx-editor-preview {+ flex: 1 1 auto;+ width: 100%;+ max-width: 880px;+ min-height: 0;+ margin: 0 auto;+ padding: 24px 32px;+ border: 0;+ border-radius: 0;+ box-sizing: border-box;+ overflow: auto;+}.chat-file-viewer-text {padding: 20px 24px;margin: 0;@@ -3411,6 +3696,28 @@ body.model-not-configured .main-content { flex-direction: column; }min-height: 100%;box-sizing: border-box;}+/* Mirrors .is-markdown's flex layout: body becomes a flex column so the+ <pre> view or <textarea> editor (both direct children of the body) can+ fill the available height and own their own scroll. */+.chat-file-viewer.is-text .chat-file-viewer-body {+ display: flex;+ flex-direction: column;+ overflow: hidden;+}+.chat-file-viewer.is-text .chat-file-viewer-body > .chat-file-viewer-text {+ flex: 1 1 auto;+ min-height: 0;+ overflow: auto;+}+.chat-file-viewer.is-text .chat-file-viewer-body > .ctx-viewer-editor {+ flex: 1 1 auto;+ min-height: 0;+ padding: 16px 20px;+ border: 0;+ border-radius: 0;+ outline: 0;+ resize: none;+}.chat-file-viewer-loading {padding: 40px;text-align: center;@@ -7056,10 +7363,9 @@ body.model-not-configured .main-content { flex-direction: column; }right: 0;/* Popovers portal to <body> at open time (see _aiSelectMount) sothey can escape parent overflow:auto. They must therefore beat- every overlay they could appear inside. `.modal-overlay` is 100,- `.ui-dialog-overlay` is 200, the avatar picker is 300, common- toasts top out at 1000 — pick a value above all of them. */- z-index: 1200;+ every overlay they could appear inside, including the login gate+ at z-index 10000. */+ z-index: 12000;background: #fff;border: 1px solid var(--border, #e5e7eb);border-radius: 8px;diff --git a/test/main/conversation-files.test.ts b/test/main/conversation-files.test.tsnew file mode 100644index 00000000..d9aa862b--- /dev/null+++ b/test/main/conversation-files.test.ts@@ -0,0 +1,47 @@+import { describe, it, expect } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++import { listWorkspaceFiles } from '../../src/main/features/conversation_files';++describe('conversation workspace file listing', () => {+ it('returns a relative tree snapshot from the current workspace on disk', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-conv-files-'));+ try {+ fs.mkdirSync(path.join(dir, 'agent_skill_review'), { recursive: true });+ fs.writeFileSync(path.join(dir, '处理索引.md'), 'index');+ fs.writeFileSync(path.join(dir, 'agent_skill_review', 'skill_batch.md'), 'skill');+ fs.writeFileSync(path.join(dir, '.hidden.md'), 'hidden');++ const result = listWorkspaceFiles(dir);++ expect(result.root).toBe(path.resolve(dir));+ expect(result.rootExists).toBe(true);+ expect(result.truncated).toBe(false);+ expect(result.items.map((f) => f.relPath)).toEqual([+ 'agent_skill_review/skill_batch.md',+ '处理索引.md',+ ]);+ expect(result.items[0].path).toBe(path.join(dir, 'agent_skill_review', 'skill_batch.md'));+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ });++ it('reports truncation instead of walking forever on huge workspaces', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-conv-files-'));+ try {+ fs.writeFileSync(path.join(dir, 'a.md'), 'a');+ fs.writeFileSync(path.join(dir, 'b.md'), 'b');++ const result = listWorkspaceFiles(dir, { maxFiles: 1 });++ expect(result.items).toHaveLength(1);+ expect(result.truncated).toBe(true);+ expect(result.count).toBe(1);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/test/main/features/agents.test.ts b/test/main/features/agents.test.tsindex 2d7a516e..a025abf6 100644--- a/test/main/features/agents.test.ts+++ b/test/main/features/agents.test.ts@@ -104,12 +104,12 @@ describe('agents › normalizeAgent', () => {const norm = a.normalizeAgent({agent_id: 'x', name: 'N', description: 'D', workflow: 'W',created_at: 't1', updated_at: 't2',- }, 'builtin');+ }, 'marketplace');expect(norm).toEqual({agent_id: 'x', name: 'N',description_zh: '', description_en: 'D',workflow: 'W',- source: 'builtin', created_at: 't1', updated_at: 't2',+ source: 'marketplace', created_at: 't1', updated_at: 't2',category: '',// computed-at-load default; overridden by listAgents/getAgent at the boundaryenabled: true,@@ -766,7 +766,7 @@ describe('agents › listAgents', () => {const a = await loadAgents();const list = await a.listAgents();const sources = Object.fromEntries(list.map((x) => [x.agent_id, x.source]));- expect(sources).toEqual({ c1: 'custom', b1: 'builtin' });+ expect(sources).toEqual({ c1: 'custom', b1: 'marketplace' });});it('custom wins when builtin has same id', async () => {diff --git a/test/main/features/chat_attachments.test.ts b/test/main/features/chat_attachments.test.tsindex 5b146e7f..4e3540a9 100644--- a/test/main/features/chat_attachments.test.ts+++ b/test/main/features/chat_attachments.test.ts@@ -34,9 +34,9 @@ async function loadMod() {return import('../../../src/main/features/chat_attachments');}-async function makePng(): Promise<Buffer> {+async function makePng(color = 0xAACCEEFF): Promise<Buffer> {const { Jimp } = await import('jimp' as any);- const img: any = new Jimp({ width: 200, height: 200, color: 0xAACCEEFF });+ const img: any = new Jimp({ width: 200, height: 200, color });return await img.getBuffer('image/png');}@@ -142,6 +142,92 @@ describe('chat_attachments › uploadAttachment', () => {expect(r2.info.name).not.toBe('dup.txt');expect(r2.info.name.endsWith('.txt')).toBe(true);});++ it('reuses an existing attachment when upload content hash matches', async () => {+ const m = await loadMod();+ const r1 = await m.uploadAttachment(UID, CID, 'first.txt', Buffer.from('same bytes'));+ const r2 = await m.uploadAttachment(UID, CID, 'second.txt', Buffer.from('same bytes'));++ expect(r1.ok && r2.ok).toBe(true);+ if (!(r1.ok && r2.ok)) return;+ expect(r2.info.name).toBe(r1.info.name);+ expect(r2.reused).toBe(true);+ expect(fs.readdirSync(attDir()).filter((n) => !n.startsWith('.'))).toEqual(['first.txt']);+ });++ it('reuses a single attachment when matching uploads arrive concurrently', async () => {+ const m = await loadMod();+ const results = await Promise.all([+ m.uploadAttachment(UID, CID, 'parallel-a.txt', Buffer.from('same parallel bytes')),+ m.uploadAttachment(UID, CID, 'parallel-b.txt', Buffer.from('same parallel bytes')),+ m.uploadAttachment(UID, CID, 'parallel-c.txt', Buffer.from('same parallel bytes')),+ ]);++ expect(results.every((r) => r.ok)).toBe(true);+ if (!results.every((r) => r.ok)) return;+ expect(new Set(results.map((r) => r.info.name)).size).toBe(1);+ expect(results.filter((r) => r.reused).length).toBe(2);+ expect(fs.readdirSync(attDir()).filter((n) => !n.startsWith('.'))).toEqual(['parallel-a.txt']);+ });++ it('imports a workspace file by path into the attachment pool', async () => {+ const m = await loadMod();+ const source = path.join(tmpDir, 'workspace-note.md');+ fs.writeFileSync(source, '# hello\n', 'utf8');++ const r = await m.importAttachmentFromPath(UID, CID, source);++ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.info.name).toBe('workspace-note.md');+ expect(r.info.kind).toBe('text');+ expect(fs.readFileSync(path.join(attDir(), 'workspace-note.md'), 'utf8')).toBe('# hello\n');+ });++ it('reuses an existing attachment when imported file hash matches', async () => {+ const m = await loadMod();+ const r1 = await m.uploadAttachment(UID, CID, 'kept.md', Buffer.from('same body'));+ const source = path.join(tmpDir, 'copy.md');+ fs.writeFileSync(source, 'same body', 'utf8');++ const r2 = await m.importAttachmentFromPath(UID, CID, source);++ expect(r1.ok && r2.ok).toBe(true);+ if (!(r1.ok && r2.ok)) return;+ expect(r2.info.name).toBe('kept.md');+ expect(r2.reused).toBe(true);+ expect(fs.readdirSync(attDir()).filter((n) => !n.startsWith('.'))).toEqual(['kept.md']);+ });++ it('reuses a single attachment when matching imports arrive concurrently', async () => {+ const m = await loadMod();+ const sourceA = path.join(tmpDir, 'source-a.md');+ const sourceB = path.join(tmpDir, 'source-b.md');+ fs.writeFileSync(sourceA, 'same imported body', 'utf8');+ fs.writeFileSync(sourceB, 'same imported body', 'utf8');++ const results = await Promise.all([+ m.importAttachmentFromPath(UID, CID, sourceA),+ m.importAttachmentFromPath(UID, CID, sourceB),+ ]);++ expect(results.every((r) => r.ok)).toBe(true);+ if (!results.every((r) => r.ok)) return;+ expect(new Set(results.map((r) => r.info.name)).size).toBe(1);+ expect(results.filter((r) => r.reused).length).toBe(1);+ expect(fs.readdirSync(attDir()).filter((n) => !n.startsWith('.'))).toEqual(['source-a.md']);+ });++ it('validates text encoding when importing by path', async () => {+ const m = await loadMod();+ const source = path.join(tmpDir, 'bad.txt');+ fs.writeFileSync(source, Buffer.from([0xFF, 0xFE]));++ const r = await m.importAttachmentFromPath(UID, CID, source);++ expect(r.ok).toBe(false);+ expect(fs.existsSync(path.join(attDir(), 'bad.txt'))).toBe(false);+ });});describe('chat_attachments › listAttachments', () => {@@ -640,7 +726,7 @@ describe('chat_attachments › buildAttachmentManifest', () => {it('caps images per message: inlined ones appear in manifest, over-cap ones go to skipped[] only', async () => {const m = await loadMod();for (let i = 0; i < 7; i++) {- await m.uploadAttachment(UID, CID, `img${i}.png`, await makePng());+ await m.uploadAttachment(UID, CID, `img${i}.png`, await makePng(0x11223300 + i));}const r = await m.buildAttachmentManifest(UID, CID,diff --git a/test/main/features/connectors/dedupe-google-workspace.test.ts b/test/main/features/connectors/dedupe-google-workspace.test.tsnew file mode 100644index 00000000..f6f142a3--- /dev/null+++ b/test/main/features/connectors/dedupe-google-workspace.test.ts@@ -0,0 +1,149 @@+/**+ * `_dedupeGoogleWorkspaceTools` is the gate that prevents the model from+ * seeing two routes to the same Gmail / Calendar / Docs / Sheets / Tasks+ * tool when a user has both the all-in-one `google-workspace` connector+ * AND a standalone single-service connector installed.+ *+ * Why this fixture exists: the dedup criterion was historically a+ * `description.startsWith('[Gmail]')` match — fragile because the+ * `[Gmail]` / `[Calendar]` / … prefix is added at runtime in+ * `bin/google-workspace-mcp-server.cjs` and could be dropped in a future+ * UI polish. Migrating to a tool-name-set match (the strict invariant —+ * both backends preserve the underlying adapter's `name`) requires+ * locking down BOTH directions:+ *+ * - set A: a workspace tool whose `name` matches a visible+ * standalone-service tool MUST be filtered out (regardless+ * of whether the description still carries a `[Gmail]`+ * prefix).+ * - set B: a workspace tool whose `name` does NOT match any+ * visible standalone tool MUST be preserved — even if its+ * description happens to start with `[Gmail]` for cosmetic+ * reasons (the old dedup would have eaten this; the new one+ * must not).+ */++import { describe, it, expect } from 'vitest';++import { _dedupeGoogleWorkspaceToolsForTest as dedupe } from '../../../../src/main/features/connectors/tools-adapter';++type FakeInstance = { id: string };+type FakeTool = { name: string; description: string; inputSchema: object };++function visible(+ entries: Array<{ id: string; tools: Array<{ name: string; description?: string }> }>,+): Array<{ instance: any; tools: any[] }> {+ return entries.map((e) => ({+ instance: { id: e.id } as FakeInstance,+ tools: e.tools.map((t) => ({+ name: t.name,+ description: t.description || '',+ inputSchema: { type: 'object', properties: {} },+ })) as FakeTool[],+ }));+}++describe('dedupeGoogleWorkspaceTools › set A (shadowed by name — MUST be filtered)', () => {+ it('shadows workspace tools whose name matches a visible standalone gmail tool', () => {+ const input = visible([+ {+ id: 'google-workspace',+ tools: [+ { name: 'gmail_search', description: '[Gmail] Search messages' },+ { name: 'gmail_send', description: '[Gmail] Send message' },+ { name: 'gcal_list', description: '[Calendar] List events' },+ ],+ },+ {+ id: 'gmail',+ tools: [+ { name: 'gmail_search', description: 'Search messages' },+ { name: 'gmail_send', description: 'Send message' },+ ],+ },+ ]);+ const out = dedupe(input);+ const workspace = out.find((v: any) => v.instance.id === 'google-workspace');+ expect(workspace?.tools.map((t: any) => t.name)).toEqual(['gcal_list']);+ // standalone gmail untouched+ const gmail = out.find((v: any) => v.instance.id === 'gmail');+ expect(gmail?.tools.map((t: any) => t.name)).toEqual(['gmail_search', 'gmail_send']);+ });++ it('hides the workspace entry entirely when every workspace tool is shadowed', () => {+ const input = visible([+ {+ id: 'google-workspace',+ tools: [+ { name: 'gmail_search', description: '[Gmail] Search' },+ { name: 'gcal_list', description: '[Calendar] List' },+ ],+ },+ { id: 'gmail', tools: [{ name: 'gmail_search', description: 'Search' }] },+ { id: 'gcal', tools: [{ name: 'gcal_list', description: 'List events' }] },+ ]);+ const out = dedupe(input);+ expect(out.find((v: any) => v.instance.id === 'google-workspace')).toBeUndefined();+ expect(out.map((v: any) => v.instance.id).sort()).toEqual(['gcal', 'gmail']);+ });++ it('matches name regardless of description prefix presence (robust to future UI polish that drops [Gmail])', () => {+ // The workspace tool no longer carries the `[Gmail]` description prefix+ // (simulating a future UI change). With name-based dedup, the standalone+ // gmail tool still shadows it.+ const input = visible([+ {+ id: 'google-workspace',+ tools: [+ // NB: no `[Gmail]` prefix+ { name: 'gmail_search', description: 'Search messages' },+ ],+ },+ { id: 'gmail', tools: [{ name: 'gmail_search', description: 'Search' }] },+ ]);+ const out = dedupe(input);+ expect(out.find((v: any) => v.instance.id === 'google-workspace')).toBeUndefined();+ });+});++describe('dedupeGoogleWorkspaceTools › set B (NOT shadowed — MUST be preserved)', () => {+ it('preserves a workspace tool whose description starts with [Gmail] when no standalone gmail connector is visible', () => {+ // The old description-prefix dedup would have eaten this entry just+ // because of the cosmetic prefix. The name-based dedup correctly leaves+ // it alone: no standalone gmail connector → no name shadow → keep.+ const input = visible([+ {+ id: 'google-workspace',+ tools: [+ { name: 'gmail_search', description: '[Gmail] Search messages' },+ { name: 'gcal_list', description: '[Calendar] List events' },+ ],+ },+ // No standalone gmail / gcal visible — workspace is the only route.+ ]);+ const out = dedupe(input);+ const workspace = out.find((v: any) => v.instance.id === 'google-workspace');+ expect(workspace?.tools.map((t: any) => t.name)).toEqual(['gmail_search', 'gcal_list']);+ });++ it('does not shadow tools from unrelated visible connectors (e.g. Notion)', () => {+ const input = visible([+ {+ id: 'google-workspace',+ tools: [{ name: 'gmail_search', description: '[Gmail] Search' }],+ },+ // Unrelated connector with a coincidentally-named tool — must NOT+ // shadow the workspace's tool.+ { id: 'notion', tools: [{ name: 'gmail_search', description: 'Notion gmail-named tool' }] },+ ]);+ const out = dedupe(input);+ const workspace = out.find((v: any) => v.instance.id === 'google-workspace');+ expect(workspace?.tools.map((t: any) => t.name)).toEqual(['gmail_search']);+ });++ it('no-ops when google-workspace is not visible', () => {+ const input = visible([{ id: 'gmail', tools: [{ name: 'gmail_search' }] }]);+ const out = dedupe(input);+ expect(out).toEqual(input);+ });+});diff --git a/test/main/features/group_chat/agents-index.test.ts b/test/main/features/group_chat/agents-index.test.tsindex a97764a7..8275fd17 100644--- a/test/main/features/group_chat/agents-index.test.ts+++ b/test/main/features/group_chat/agents-index.test.ts@@ -75,7 +75,7 @@ describe('agents_index block — header + per-entry shape', () => {const text = await buildBlock(TEST_UID);expect(text).toContain('`read_file(<ROOT>/<id>/agent.json)`');expect(text).toContain(`- custom: ${path.resolve(customAgentsDir())}`);- expect(text).toContain(`- builtin: ${path.resolve(builtinAgentsDir())}`);+ expect(text).toContain(`- marketplace: ${path.resolve(builtinAgentsDir())}`);expect(text).toContain('Use these ROOT values verbatim');expect(text).toContain('@<name>');});diff --git a/test/main/features/group_chat/bus-integration.test.ts b/test/main/features/group_chat/bus-integration.test.tsindex 6879a320..82fbd276 100644--- a/test/main/features/group_chat/bus-integration.test.ts+++ b/test/main/features/group_chat/bus-integration.test.ts@@ -25,16 +25,30 @@ function _setScript(sessionId: string, events: any[]) {}function _resetScripts() { _scripts.clear(); }+const modelAbortMock = vi.hoisted(() => vi.fn(() => 0));+vi.mock('../../../../src/main/model/client', () => ({async *streamChatWithModel(opts: any) {const sid = opts.sessionId || '';const queue = _scripts.get(sid) || [];const events = queue.shift() || [{ type: 'final', text: '' }];_scripts.set(sid, queue);- for (const ev of events) yield ev;+ for (const ev of events) {+ if (ev?.type === '__wait_for_abort__') {+ if (!opts.abortSignal?.aborted) {+ await new Promise<void>((resolve) => {+ opts.abortSignal?.addEventListener('abort', () => resolve(), { once: true });+ });+ }+ yield { type: 'error', text: 'aborted', aborted: true };+ continue;+ }+ yield ev;+ }yield { type: 'done' };},async chatWithModel() { return { ok: true, text: '', error: '', aborted: false }; },+ abortActiveSessionsForConversation: modelAbortMock,}));let tmpDir: string;@@ -52,6 +66,8 @@ beforeEach(async () => {prevWs = process.env.ORKAS_WORKSPACE_ROOT;process.env.ORKAS_WORKSPACE_ROOT = tmpDir;_resetScripts();+ modelAbortMock.mockClear();+ modelAbortMock.mockReturnValue(0);vi.resetModules();const users = await import('../../../../src/main/features/users');users.activateUser(TEST_UID);@@ -211,6 +227,15 @@ describe.skip('group_chat bus integration › multi-recipient parallel dispatch'});describe('group_chat bus integration › abort sticky across worker post-cleanup', () => {+ it('abort also targets active core-agent sessions by conversation id', async () => {+ const cid = newCid();+ const bus = await import('../../../../src/main/features/group_chat/bus');++ await bus.abort(TEST_UID, cid);++ expect(modelAbortMock).toHaveBeenCalledWith(cid);+ });+it('abort during a turn keeps state.aborted; subsequent worker reply does NOT un-stick', async () => {const cid = newCid();const state = await import('../../../../src/main/features/group_chat/state');@@ -236,6 +261,44 @@ describe('group_chat bus integration › abort sticky across worker post-cleanupexpect(st.status).toBe('aborted');});+ it('abort during a live agent turn propagates to the worker AbortSignal', async () => {+ const cid = newCid();+ const state = await import('../../../../src/main/features/group_chat/state');+ const bus = await import('../../../../src/main/features/group_chat/bus');++ bus.subscribe(TEST_UID, cid, () => {});+ _setScript(state.buildGmemberSessionId(TEST_UID, cid, AGENT_ID), [+ { type: '__wait_for_abort__' },+ { type: 'final', text: 'should not appear after abort' },+ ]);++ await bus.enqueue({+ uid: TEST_UID,+ cid,+ fromActorId: 'user',+ text: `@${AGENT_NAME} long task`,+ });++ const start = Date.now();+ while (Date.now() - start < 1000) {+ const live = bus._cidStateForTest(TEST_UID, cid);+ const worker = live?.workers.get(AGENT_ID);+ if (worker?.running && worker.abortController) break;+ await new Promise((r) => setTimeout(r, 10));+ }+ expect(bus._cidStateForTest(TEST_UID, cid)?.workers.get(AGENT_ID)?.abortController).toBeTruthy();++ await bus.abort(TEST_UID, cid);+ await waitForQuiescent(TEST_UID, cid, 2000);++ const paths = await import('../../../../src/main/paths');+ const storage = await import('../../../../src/main/storage');+ const messages = await storage.readJsonl<any>(path.join(paths.userChatsDir(TEST_UID), `${cid}.jsonl`));+ expect(messages.some((m: any) => m.text.includes('should not appear after abort'))).toBe(false);+ const st = await state.readState(TEST_UID, cid);+ expect(st.status).toBe('aborted');+ });+it('a NEW user message after abort clears the sticky aborted flag', async () => {const cid = newCid();const state = await import('../../../../src/main/features/group_chat/state');diff --git a/test/main/features/group_chat/bus.test.ts b/test/main/features/group_chat/bus.test.tsindex ca10a636..b9f63319 100644--- a/test/main/features/group_chat/bus.test.ts+++ b/test/main/features/group_chat/bus.test.ts@@ -18,6 +18,7 @@ vi.mock('../../../../src/main/model/client', () => ({yield { type: 'done' };},async chatWithModel() { return { ok: true, text: '', error: '', aborted: false }; },+ abortActiveSessionsForConversation: vi.fn(() => 0),}));const cliRunMock = vi.hoisted(() => ({ calls: [] as any[] }));diff --git a/test/main/features/group_chat/conv_title.test.ts b/test/main/features/group_chat/conv_title.test.tsnew file mode 100644index 00000000..03751ecb--- /dev/null+++ b/test/main/features/group_chat/conv_title.test.ts@@ -0,0 +1,66 @@+/**+ * conv_title.ts — fixture-lock the placeholder-title detection set so that+ * adding a new UI language without updating `chat.default_title` in its+ * locale file (or, worse, forgetting that the placeholder-set even exists)+ * regresses noisily instead of silently. The bug this guards against+ * shipped once in 2026-05 when Japanese landed `chat.default_title="新しい会話"`+ * but the placeholder set was hardcoded to zh+en only — every new Japanese+ * UI conversation lost its auto-title trigger.+ *+ * Set A: every supported language's `chat.default_title` MUST be detected,+ * plus the historical capitalization aliases.+ * Set B: a non-placeholder user-named title MUST NOT be detected.+ */++import { describe, it, expect } from 'vitest';++import { SUPPORTED_LANGS, t } from '../../../../src/main/i18n';+import { isPlaceholderTitle, PLACEHOLDER_TITLES } from '../../../../src/main/features/group_chat/conv_title';++describe('conv_title › PLACEHOLDER_TITLES set membership', () => {+ it('contains every supported language\'s chat.default_title (set A: locale-driven)', () => {+ // Locked: zh / en / ja each have their default title pinned. If a new+ // language is added but its locale file is missing this key, this test+ // fails loudly instead of silently degrading auto-title for that UI.+ for (const lang of SUPPORTED_LANGS) {+ const value = t('chat.default_title', undefined, lang);+ expect(value, `chat.default_title missing in ${lang}.json`).not.toBe('chat.default_title');+ expect(+ PLACEHOLDER_TITLES.has(value),+ `${lang} default title "${value}" not recognised as placeholder`,+ ).toBe(true);+ expect(isPlaceholderTitle(value)).toBe(true);+ }+ });++ it('contains the legacy capitalization aliases "New Conversation" / "New Chat"', () => {+ expect(PLACEHOLDER_TITLES.has('New Conversation')).toBe(true);+ expect(PLACEHOLDER_TITLES.has('New Chat')).toBe(true);+ expect(isPlaceholderTitle('New Conversation')).toBe(true);+ expect(isPlaceholderTitle('New Chat')).toBe(true);+ });+});++describe('conv_title › isPlaceholderTitle (set B: real user-named titles must pass through)', () => {+ it('returns false for an English user-named title', () => {+ expect(isPlaceholderTitle('Quarterly review notes')).toBe(false);+ });++ it('returns false for a Chinese user-named title that is not the default', () => {+ expect(isPlaceholderTitle('季度复盘')).toBe(false);+ });++ it('returns false for a Japanese user-named title that is not the default', () => {+ expect(isPlaceholderTitle('週次レビューのメモ')).toBe(false);+ });++ it('returns false for a title that contains but does not equal the default ("新对话补充")', () => {+ expect(isPlaceholderTitle('新对话补充')).toBe(false);+ });++ it('returns true for empty string / undefined / null (treat as unnamed)', () => {+ expect(isPlaceholderTitle('')).toBe(true);+ expect(isPlaceholderTitle(undefined)).toBe(true);+ expect(isPlaceholderTitle(null)).toBe(true);+ });+});diff --git a/test/main/features/group_chat/plan-recovery.test.ts b/test/main/features/group_chat/plan-recovery.test.tsindex 0d2a8216..04137b91 100644--- a/test/main/features/group_chat/plan-recovery.test.ts+++ b/test/main/features/group_chat/plan-recovery.test.ts@@ -137,37 +137,78 @@ describe('plan recovery › retryStep', () => {expect(r.error).toMatch(/not in failed state/);});- it('treats repeated retry after recovery starts as idempotent', async () => {+ it('treats repeated retry after recovery starts as idempotent for mid-recovery states (pending / in_progress / blocked)', async () => {const cid = newCid();await seedPlan(TEST_UID, cid, {steps: [{ title: 'Step 1', assignee: A_NAME, wait_for: [] },{ title: 'Step 2', assignee: A_NAME },{ title: 'Step 3', assignee: A_NAME },- { title: 'Step 4', assignee: A_NAME },],});const plan = await import('../../../../src/main/features/group_chat/plan');await plan.updateStep(TEST_UID, cid, 1, 'in_progress');await plan.updateStep(TEST_UID, cid, 2, 'pending');await plan.updateStep(TEST_UID, cid, 3, 'blocked');- await plan.updateStep(TEST_UID, cid, 4, 'done');const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');const inProgress = await planExecutor.retryStep(TEST_UID, cid, 1);const pending = await planExecutor.retryStep(TEST_UID, cid, 2);const blocked = await planExecutor.retryStep(TEST_UID, cid, 3);- const done = await planExecutor.retryStep(TEST_UID, cid, 4);expect(inProgress.ok).toBe(true);expect(pending.ok).toBe(true);expect(blocked.ok).toBe(true);- expect(done.ok).toBe(true);const fresh = await plan.readPlan(TEST_UID, cid);expect(fresh?.steps[0].status).toBe('in_progress');expect(fresh?.steps[1].status).toBe('pending');expect(fresh?.steps[2].status).toBe('blocked');- expect(fresh?.steps[3].status).toBe('done');+ });++ it('clears pending_form_id when a failed user step is retried (so the re-dispatch stamps a fresh form_id)', async () => {+ const cid = newCid();+ await seedPlan(TEST_UID, cid, {+ steps: [{ title: 'ask user', assignee: 'user', input: 'pick one', wait_for: [] }],+ });+ const plan = await import('../../../../src/main/features/group_chat/plan');+ // Simulate a previously-dispatched-then-failed user step: pending_form_id+ // is set (from the original dispatch), status is failed.+ await plan.updateStep(TEST_UID, cid, 1, 'failed', {+ failure_reason: 'user replied with an unrelated message',+ pending_form_id: 'a1b2c3d4e5f60001',+ });+ let fresh = await plan.readPlan(TEST_UID, cid);+ expect(fresh?.steps[0].pending_form_id).toBe('a1b2c3d4e5f60001');++ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');+ const r = await planExecutor.retryStep(TEST_UID, cid, 1);+ expect(r.ok).toBe(true);++ fresh = await plan.readPlan(TEST_UID, cid);+ // Retry re-arms the step and reconcile may have re-dispatched it (which+ // would stamp a NEW pending_form_id). What we lock here is the+ // invariant: the stale form_id from the failed run must NOT survive.+ // Either the field is absent (no re-dispatch yet) OR it differs from+ // the old one (re-dispatched with a fresh id) — never the old value.+ expect(fresh?.steps[0].pending_form_id).not.toBe('a1b2c3d4e5f60001');+ });++ it('rejects retry on a done step (rail never shows retry button on done; reaching here would mis-attribute a retry signal)', async () => {+ const cid = newCid();+ await seedPlan(TEST_UID, cid, {+ steps: [{ title: 'Step 1', assignee: A_NAME, wait_for: [] }],+ });+ const plan = await import('../../../../src/main/features/group_chat/plan');+ await plan.updateStep(TEST_UID, cid, 1, 'done');++ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');+ const r = await planExecutor.retryStep(TEST_UID, cid, 1);+ expect(r.ok).toBe(false);+ expect(r.error).toMatch(/not in failed state/);++ // Step remains done — retry must NOT silently mutate a completed step.+ const fresh = await plan.readPlan(TEST_UID, cid);+ expect(fresh?.steps[0].status).toBe('done');});it('cascade-unblocks downstream skipped via `aborted by step N failure` reason', async () => {diff --git a/test/main/features/group_chat/plan_executor.test.ts b/test/main/features/group_chat/plan_executor.test.tsindex fe48228c..69b9862f 100644--- a/test/main/features/group_chat/plan_executor.test.ts+++ b/test/main/features/group_chat/plan_executor.test.ts@@ -446,6 +446,11 @@ describe('plan_executor › user-assignee step', () => {}),],});+ // Dispatch must stamp `pending_form_id` on the step itself so that+ // `acceptsUserStepCompletion` can match the user reply in O(1) instead+ // of re-scanning the conversation jsonl. If this regresses, the gate+ // silently falls back to "accept any user reply" (legacy mode).+ expect(snapshot?.steps[0].pending_form_id).toBe(question.form.form_id);// A regular chat message is allowed to start a commander discussion,// but it must not be mistaken for the pending user-form answer.diff --git a/test/main/features/reflection-digest.test.ts b/test/main/features/reflection-digest.test.tsdeleted file mode 100644index f9504bcc..00000000--- a/test/main/features/reflection-digest.test.ts+++ /dev/null@@ -1,259 +0,0 @@-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-import * as fs from 'node:fs';-import * as os from 'node:os';-import * as path from 'node:path';--let tmpDir: string;-let prevWs: string | undefined;-const TEST_UID = 'u1';--beforeEach(async () => {- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-digest-'));- prevWs = process.env.ORKAS_WORKSPACE_ROOT;- process.env.ORKAS_WORKSPACE_ROOT = tmpDir;- vi.resetModules();- const users = await import('../../../src/main/features/users');- users.activateUser(TEST_UID);-});--afterEach(() => {- process.env.ORKAS_WORKSPACE_ROOT = prevWs;- fs.rmSync(tmpDir, { recursive: true, force: true });-});--async function loadModule() {- return import('../../../src/main/features/reflection-digest');-}--// ── aggregateSession (pure) ─────────────────────────────────────────────--describe('reflection-digest › aggregateSession', () => {- it('counts tool_use blocks by name', async () => {- const mod = await loadModule();- const m = mod.emptyMetrics();- mod.aggregateSession([- { role: 'assistant', content: [{ type: 'tool_use', name: 'web_search', input: {} }], ts: 1 },- { role: 'assistant', content: [{ type: 'tool_use', name: 'web_search', input: {} }], ts: 2 },- { role: 'assistant', content: [{ type: 'tool_use', name: 'bash', input: {} }], ts: 3 },- ], m);- expect(m.toolCalls).toEqual({ web_search: 2, bash: 1 });- expect(m.sessionsAnalyzed).toBe(1);- });-- it('counts tool_result errors and captures up to 3 samples', async () => {- const mod = await loadModule();- const m = mod.emptyMetrics();- mod.aggregateSession([- { role: 'user', content: [{ type: 'tool_result', toolUseId: 'a', content: 'ENETUNREACH connection refused', isError: true }] },- { role: 'user', content: [{ type: 'tool_result', toolUseId: 'b', content: 'rate limit', isError: true }] },- { role: 'user', content: [{ type: 'tool_result', toolUseId: 'c', content: 'timeout', isError: true }] },- { role: 'user', content: [{ type: 'tool_result', toolUseId: 'd', content: 'fourth — should be capped', isError: true }] },- { role: 'user', content: [{ type: 'tool_result', toolUseId: 'e', content: 'success', isError: false }] },- ], m);- expect(m.errorCount).toBe(4);- expect(m.errorSamples.length).toBe(3); // capped at 3- expect(m.errorSamples[0]).toContain('ENETUNREACH');- });-- it('truncates long error samples', async () => {- const mod = await loadModule();- const m = mod.emptyMetrics();- const longErr = 'X'.repeat(500);- mod.aggregateSession([- { role: 'user', content: [{ type: 'tool_result', toolUseId: 'a', content: longErr, isError: true }] },- ], m);- expect(m.errorSamples[0].length).toBeLessThanOrEqual(160);- });-- it('tracks skill_manage(read) skill ids in skillsLoaded', async () => {- const mod = await loadModule();- const m = mod.emptyMetrics();- mod.aggregateSession([- { role: 'assistant', content: [{ type: 'tool_use', name: 'skill_manage', input: { action: 'read', id: 'foo' } }] },- { role: 'assistant', content: [{ type: 'tool_use', name: 'skill_manage', input: { action: 'read', id: 'foo' } }] },- { role: 'assistant', content: [{ type: 'tool_use', name: 'skill_manage', input: { action: 'create', id: 'bar' } }] },- ], m);- expect(m.skillsLoaded).toEqual({ foo: 2 }); // create not tracked, only read- expect(m.toolCalls.skill_manage).toBe(3);- });-- it('tracks earliestTs and latestTs from message ts fields', async () => {- const mod = await loadModule();- const m = mod.emptyMetrics();- mod.aggregateSession([- { role: 'user', content: [{ type: 'text', text: 'a' }], ts: 100 },- { role: 'assistant', content: [{ type: 'text', text: 'b' }], ts: 200 },- { role: 'user', content: [{ type: 'text', text: 'c' }], ts: 50 },- ], m);- expect(m.earliestTs).toBe(50);- expect(m.latestTs).toBe(200);- });-- it('does not increment sessionsAnalyzed for empty messages array', async () => {- const mod = await loadModule();- const m = mod.emptyMetrics();- mod.aggregateSession([], m);- expect(m.sessionsAnalyzed).toBe(0);- });-- it('accumulates across multiple aggregate calls (multi-session)', async () => {- const mod = await loadModule();- const m = mod.emptyMetrics();- mod.aggregateSession([{ role: 'assistant', content: [{ type: 'tool_use', name: 'bash' }] }], m);- mod.aggregateSession([{ role: 'assistant', content: [{ type: 'tool_use', name: 'bash' }] }], m);- expect(m.sessionsAnalyzed).toBe(2);- expect(m.toolCalls.bash).toBe(2);- });-- it('handles malformed content blocks defensively', async () => {- const mod = await loadModule();- const m = mod.emptyMetrics();- mod.aggregateSession([- { role: 'assistant' }, // missing content- { role: 'assistant', content: 'not an array' },- { role: 'assistant', content: [null, undefined, { type: 'tool_use' /* no name */ }] },- ], m);- expect(m.sessionsAnalyzed).toBe(1);- expect(m.toolCalls).toEqual({});- });-});--// ── formatDigest (pure) ─────────────────────────────────────────────────--describe('reflection-digest › formatDigest', () => {- it('returns "no activity" when nothing was analyzed', async () => {- const mod = await loadModule();- const out = mod.formatDigest(mod.emptyMetrics(), Date.parse('2026-04-21'), Date.parse('2026-04-23'));- expect(out).toMatch(/No new conversation activity/);- });-- it('formats a populated digest with all sections', async () => {- const mod = await loadModule();- const m = mod.emptyMetrics();- m.sessionsAnalyzed = 3;- m.toolCalls = { bash: 5, web_search: 2 };- m.errorCount = 2;- m.errorSamples = ['rate limit', 'timeout'];- m.skillsLoaded = { 'recover-foo': 3 };- m.earliestTs = Date.parse('2026-04-21T10:00:00Z');- m.latestTs = Date.parse('2026-04-23T10:00:00Z');-- const out = mod.formatDigest(m, m.earliestTs, Date.now());- expect(out).toContain('3 session');- expect(out).toContain('bash: 5');- expect(out).toContain('web_search: 2');- expect(out).toContain('Total errors**: 2');- expect(out).toContain('rate limit');- expect(out).toContain('recover-foo (3x)');- });-- it('omits error section when no errors', async () => {- const mod = await loadModule();- const m = mod.emptyMetrics();- m.sessionsAnalyzed = 1;- m.toolCalls = { bash: 1 };- const out = mod.formatDigest(m, Date.now() - 1000, Date.now());- expect(out).not.toContain('Total errors');- expect(out).not.toContain('Error samples');- });-- it('caps tool list at top-N most-called', async () => {- const mod = await loadModule();- const m = mod.emptyMetrics();- m.sessionsAnalyzed = 1;- // 12 different tools — should only show top 8- for (let i = 0; i < 12; i++) m.toolCalls[`tool${i}`] = 100 - i;- const out = mod.formatDigest(m, Date.now() - 1000, Date.now());- expect(out).toContain('tool0');- expect(out).toContain('tool7');- expect(out).not.toContain('tool8');- });-});--// ── buildAgentReflectionDigest (I/O) ────────────────────────────────────--describe('reflection-digest › buildAgentReflectionDigest', () => {- function writeConv(uid: string, cid: string, agentId: string): string {- // Write to chats/_index.json (newest-first list).- const idxPath = path.join(tmpDir, uid, 'cloud', 'chats', '_index.json');- fs.mkdirSync(path.dirname(idxPath), { recursive: true });- let list: any[] = [];- if (fs.existsSync(idxPath)) list = JSON.parse(fs.readFileSync(idxPath, 'utf8'));- const sessionId = `${uid}-gconv-${cid}`;- list.unshift({- conversation_id: cid,- title: `t-${cid}`,- kind: agentId ? 'agent_run' : 'normal',- agent_id: agentId,- skill_id: '',- session_id: sessionId,- created_at: new Date().toISOString(),- updated_at: new Date().toISOString(),- });- fs.writeFileSync(idxPath, JSON.stringify(list));- return sessionId;- }-- function writeSessionJsonl(uid: string, sessionId: string, lines: any[], mtime?: number): void {- const file = path.join(tmpDir, uid, 'cloud', 'sessions', `${sessionId}.jsonl`);- fs.mkdirSync(path.dirname(file), { recursive: true });- fs.writeFileSync(file, lines.map((l) => JSON.stringify(l)).join('\n') + '\n');- if (mtime !== undefined) fs.utimesSync(file, mtime / 1000, mtime / 1000);- }-- it('returns "no activity" when no matching conversations exist', async () => {- const mod = await loadModule();- const out = await mod.buildAgentReflectionDigest(TEST_UID, '_default', Date.now() - 86400000);- expect(out).toMatch(/No new conversation activity/);- });-- it('aggregates only conversations matching the target agent_id', async () => {- const sid1 = writeConv(TEST_UID, 'c1', ''); // normal → _default- const sid2 = writeConv(TEST_UID, 'c2', 'agent-x'); // agent-x- writeSessionJsonl(TEST_UID, sid1, [- { role: 'assistant', content: [{ type: 'tool_use', name: 'bash' }], ts: Date.now() },- ]);- writeSessionJsonl(TEST_UID, sid2, [- { role: 'assistant', content: [{ type: 'tool_use', name: 'web_search' }], ts: Date.now() },- ]);-- const mod = await loadModule();- const since = Date.now() - 86400000;-- const defaultDigest = await mod.buildAgentReflectionDigest(TEST_UID, '_default', since);- expect(defaultDigest).toContain('bash');- expect(defaultDigest).not.toContain('web_search');-- const xDigest = await mod.buildAgentReflectionDigest(TEST_UID, 'agent-x', since);- expect(xDigest).toContain('web_search');- expect(xDigest).not.toContain('bash');- });-- it('skips session jsonls with mtime older than sinceMs', async () => {- const sid = writeConv(TEST_UID, 'cold', '');- const ancient = Date.now() - 30 * 86400000; // 30 days ago- writeSessionJsonl(TEST_UID, sid, [- { role: 'assistant', content: [{ type: 'tool_use', name: 'bash' }] },- ], ancient);-- const mod = await loadModule();- const since = Date.now() - 86400000; // last 24h- const digest = await mod.buildAgentReflectionDigest(TEST_UID, '_default', since);- expect(digest).toMatch(/No new conversation activity/);- });-- it('tolerates malformed jsonl lines and missing files', async () => {- const sid = writeConv(TEST_UID, 'malformed', '');- const file = path.join(tmpDir, TEST_UID, 'cloud', 'sessions', `${sid}.jsonl`);- fs.mkdirSync(path.dirname(file), { recursive: true });- fs.writeFileSync(file, 'not json\n{"role":"assistant","content":[{"type":"tool_use","name":"ok"}]}\n}}}\n');-- // Also reference a conversation whose session file doesn't exist- writeConv(TEST_UID, 'ghost', '');-- const mod = await loadModule();- const digest = await mod.buildAgentReflectionDigest(TEST_UID, '_default', 0);- expect(digest).toContain('ok'); // valid line still parsed- // Ghost session simply skipped — no throw, and the malformed-but-valid one accounted for.- });-});diff --git a/test/main/features/reflection-orchestrator.test.ts b/test/main/features/reflection-orchestrator.test.tsnew file mode 100644index 00000000..cde1d50e--- /dev/null+++ b/test/main/features/reflection-orchestrator.test.ts@@ -0,0 +1,216 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++// Same race as in reflection-transcript.test.ts: activateUser fires+// sweepSessions fire-and-forget and would wipe our test session files.+vi.mock('../../../src/main/features/sessions_sweep', () => ({+ sweepSessions: vi.fn(async () => ({+ scanned: 0, orphan_cid: 0, ephemeral_on_cloud: 0, legacy: 0,+ local_aged_out: 0, errors: 0,+ })),+}));++let tmpDir: string;+let prevWs: string | undefined;+const TEST_UID = 'u1';++beforeEach(async () => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-orchestrator-'));+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;+ vi.resetModules();+ const users = await import('../../../src/main/features/users');+ users.activateUser(TEST_UID);+});++afterEach(() => {+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++async function loadModule() {+ return import('../../../src/main/features/reflection-orchestrator');+}++function writeReflectionState(uid: string, lastReflectedAt: Record<string, string>): void {+ const dir = path.join(tmpDir, uid, 'local', 'config');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'reflection-state.json'), JSON.stringify({ lastReflectedAt }));+}++// ── pickAgentsForCycle ──────────────────────────────────────────────────++describe('reflection-orchestrator › pickAgentsForCycle', () => {+ const NOW = Date.parse('2026-05-21T12:00:00Z');++ it('skips agents within cooldown (< 4h since lastReflectedAt)', async () => {+ const mod = await loadModule();+ const state = { lastReflectedAt: { 'agent-x': new Date(NOW - 2 * 3600 * 1000).toISOString() } };+ const picked = await mod.pickAgentsForCycle(TEST_UID, ['agent-x'], state, NOW, async () => true);+ expect(picked.length).toBe(0);+ });++ it('picks dirty agents past cooldown', async () => {+ const mod = await loadModule();+ const state = { lastReflectedAt: { 'agent-x': new Date(NOW - 6 * 3600 * 1000).toISOString() } };+ const picked = await mod.pickAgentsForCycle(TEST_UID, ['agent-x'], state, NOW, async () => true);+ expect(picked.length).toBe(1);+ expect(picked[0].reason).toBe('dirty');+ });++ it('forces reflection when past 7-day max gap regardless of dirty', async () => {+ const mod = await loadModule();+ const stale = new Date(NOW - 10 * 24 * 3600 * 1000).toISOString();+ const state = { lastReflectedAt: { 'agent-x': stale } };+ const picked = await mod.pickAgentsForCycle(TEST_UID, ['agent-x'], state, NOW, async () => false);+ expect(picked.length).toBe(1);+ expect(picked[0].reason).toBe('max_gap');+ });++ it('treats never-reflected agents as eligible when dirty (default lookback)', async () => {+ const mod = await loadModule();+ const state = { lastReflectedAt: {} };+ const picked = await mod.pickAgentsForCycle(TEST_UID, ['agent-x'], state, NOW, async () => true);+ expect(picked.length).toBe(1);+ expect(picked[0].reason).toBe('never_reflected');+ // sinceMs should be ~48h before now (DEFAULT_LOOKBACK_MS)+ expect(NOW - picked[0].sinceMs).toBeCloseTo(48 * 3600 * 1000, -5);+ });++ it('skips never-reflected agents when not dirty', async () => {+ const mod = await loadModule();+ const state = { lastReflectedAt: {} };+ const picked = await mod.pickAgentsForCycle(TEST_UID, ['agent-x'], state, NOW, async () => false);+ expect(picked.length).toBe(0);+ });++ it('caps at MAX_AGENTS_PER_CYCLE, picking earliest lastReflectedAt first', async () => {+ const mod = await loadModule();+ const lastReflectedAt: Record<string, string> = {};+ for (let i = 0; i < 8; i++) {+ // agent-0 oldest (NOW - 8h), agent-7 newest just past cooldown (NOW - 4.1h)+ lastReflectedAt[`agent-${i}`] = new Date(NOW - (8 - i * 0.5) * 3600 * 1000).toISOString();+ }+ const ids = Object.keys(lastReflectedAt);+ const picked = await mod.pickAgentsForCycle(TEST_UID, ids, { lastReflectedAt }, NOW, async () => true);+ expect(picked.length).toBe(mod.MAX_AGENTS_PER_CYCLE);+ // First in result should be the oldest (agent-0)+ expect(picked[0].agentId).toBe('agent-0');+ });++ it('processes a mix: cooldown / dirty / max_gap correctly', async () => {+ const mod = await loadModule();+ const state = {+ lastReflectedAt: {+ 'cool': new Date(NOW - 1 * 3600 * 1000).toISOString(), // within cooldown+ 'dirty': new Date(NOW - 6 * 3600 * 1000).toISOString(), // past cooldown, dirty+ 'stale': new Date(NOW - 10 * 24 * 3600 * 1000).toISOString(), // max_gap+ 'idle': new Date(NOW - 6 * 3600 * 1000).toISOString(), // past cooldown, not dirty+ },+ };+ const isDirty = async (_u: string, id: string) => id === 'dirty';+ const picked = await mod.pickAgentsForCycle(TEST_UID, ['cool', 'dirty', 'stale', 'idle'], state, NOW, isDirty);+ const ids = picked.map((p) => p.agentId).sort();+ expect(ids).toEqual(['dirty', 'stale']);+ });+});++// ── runOneCycle ──────────────────────────────────────────────────────────++describe('reflection-orchestrator › runOneCycle', () => {+ const NOW = Date.parse('2026-05-21T12:00:00Z');++ it('returns 0 when no agents are eligible', async () => {+ const mod = await loadModule();+ const reflect = vi.fn(async () => { /* never called */ });+ const completed = await mod.runOneCycle(TEST_UID, {+ now: () => NOW,+ reflect,+ isDirty: async () => false,+ });+ expect(completed).toBe(0);+ expect(reflect).not.toHaveBeenCalled();+ });++ it('failed reflection does not stamp lastReflectedAt (retry next cycle)', async () => {+ const mod = await loadModule();+ const reflect = vi.fn(async () => { throw new Error('provider down'); });+ const completed = await mod.runOneCycle(TEST_UID, {+ now: () => NOW,+ reflect,+ isDirty: async () => true,+ });+ expect(reflect).toHaveBeenCalled();+ expect(completed).toBe(0);+ const state = mod.readReflectionState(TEST_UID);+ expect(state.lastReflectedAt).toEqual({}); // no stamp on failure+ });++ it('successful reflection stamps lastReflectedAt with `now`', async () => {+ const mod = await loadModule();+ const reflect = vi.fn(async () => { /* succeed */ });+ const completed = await mod.runOneCycle(TEST_UID, {+ now: () => NOW,+ reflect,+ isDirty: async () => true,+ });+ expect(completed).toBeGreaterThanOrEqual(1);+ const state = mod.readReflectionState(TEST_UID);+ expect(state.lastReflectedAt[mod.DEFAULT_AGENT_ID]).toBe(new Date(NOW).toISOString());+ });++ it('skips with debug log when feature flag is off', async () => {+ process.env.ORKAS_METACOGNITION = '0';+ try {+ const mod = await loadModule();+ const reflect = vi.fn();+ const completed = await mod.runOneCycle(TEST_UID, { now: () => NOW, reflect, isDirty: async () => true });+ expect(completed).toBe(0);+ expect(reflect).not.toHaveBeenCalled();+ } finally {+ delete process.env.ORKAS_METACOGNITION;+ }+ });++ it('skips with debug log when uid is empty', async () => {+ const mod = await loadModule();+ const reflect = vi.fn();+ const completed = await mod.runOneCycle('', { now: () => NOW, reflect, isDirty: async () => true });+ expect(completed).toBe(0);+ expect(reflect).not.toHaveBeenCalled();+ });+});++// ── readReflectionState / writeReflectionState round-trip ───────────────++describe('reflection-orchestrator › state persistence', () => {+ it('round-trips lastReflectedAt through disk', async () => {+ const mod = await loadModule();+ fs.mkdirSync(path.join(tmpDir, TEST_UID, 'local', 'config'), { recursive: true });+ mod.writeReflectionState(TEST_UID, { lastReflectedAt: { 'agent-x': '2026-05-21T10:00:00Z' } });+ const read = mod.readReflectionState(TEST_UID);+ expect(read.lastReflectedAt['agent-x']).toBe('2026-05-21T10:00:00Z');+ });++ it('returns empty state when file is missing', async () => {+ const mod = await loadModule();+ expect(mod.readReflectionState(TEST_UID)).toEqual({ lastReflectedAt: {} });+ });++ it('returns empty state when file is malformed (defensive)', async () => {+ const mod = await loadModule();+ const dir = path.join(tmpDir, TEST_UID, 'local', 'config');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'reflection-state.json'), '{not json');+ expect(mod.readReflectionState(TEST_UID)).toEqual({ lastReflectedAt: {} });+ });++ it('filters out non-string values defensively', async () => {+ const mod = await loadModule();+ writeReflectionState(TEST_UID, { 'a': 'iso', /* @ts-expect-error */ 'b': 123 as any });+ const read = mod.readReflectionState(TEST_UID);+ expect(read.lastReflectedAt).toEqual({ a: 'iso' });+ });+});diff --git a/test/main/features/reflection-transcript.test.ts b/test/main/features/reflection-transcript.test.tsnew file mode 100644index 00000000..6a9afe50--- /dev/null+++ b/test/main/features/reflection-transcript.test.ts@@ -0,0 +1,417 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++// activateUser fires sweepSessions fire-and-forget; in real boot it races+// safely with subsequent writes, but in unit tests the sweep can wipe the+// gmember-*.jsonl files we just created (cid not yet in _index.json when+// the sweep snapshots cids). Stub it out for the whole file.+vi.mock('../../../src/main/features/sessions_sweep', () => ({+ sweepSessions: vi.fn(async () => ({+ scanned: 0, orphan_cid: 0, ephemeral_on_cloud: 0, legacy: 0,+ local_aged_out: 0, errors: 0,+ })),+}));++let tmpDir: string;+let prevWs: string | undefined;+const TEST_UID = 'u1';++beforeEach(async () => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-transcript-'));+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;+ vi.resetModules();+ const users = await import('../../../src/main/features/users');+ users.activateUser(TEST_UID);+});++afterEach(() => {+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++async function loadModule() {+ return import('../../../src/main/features/reflection-transcript');+}++// ── Test helpers ────────────────────────────────────────────────────────++interface ConvSpec {+ cid: string;+ agentId: string;+ title?: string;+ createdAt?: string;+}++function writeConv(uid: string, spec: ConvSpec): { sessionId: string; gmemberSessionId: string } {+ const idxPath = path.join(tmpDir, uid, 'cloud', 'chats', '_index.json');+ fs.mkdirSync(path.dirname(idxPath), { recursive: true });+ let list: any[] = [];+ if (fs.existsSync(idxPath)) list = JSON.parse(fs.readFileSync(idxPath, 'utf8'));+ const sessionId = `gconv-${spec.cid}`;+ list.unshift({+ conversation_id: spec.cid,+ title: spec.title || `t-${spec.cid}`,+ kind: spec.agentId ? 'agent_run' : 'normal',+ agent_id: spec.agentId,+ skill_id: '',+ session_id: sessionId,+ created_at: spec.createdAt || new Date().toISOString(),+ updated_at: new Date().toISOString(),+ });+ fs.writeFileSync(idxPath, JSON.stringify(list));+ return {+ sessionId,+ gmemberSessionId: `gmember-${spec.cid}-${spec.agentId}`,+ };+}++function writeSessionJsonl(uid: string, sessionId: string, lines: any[]): void {+ const file = path.join(tmpDir, uid, 'cloud', 'sessions', `${sessionId}.jsonl`);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, lines.map((l) => JSON.stringify(l)).join('\n') + '\n');+}++function userMsg(text: string, ts: number, from = 'user', to = 'commander'): any {+ return {+ role: 'user',+ content: [{ type: 'text', text: `<msg from="${from}" to="${to}">\n${text}\n</msg>` }],+ ts,+ };+}++function agentMsg(text: string, ts: number): any {+ return {+ role: 'assistant',+ content: [{ type: 'text', text }],+ ts,+ };+}++function writeSignalsJsonl(uid: string, signals: any[], date?: Date): void {+ const ymd = (date || new Date()).toISOString().slice(0, 10);+ const file = path.join(tmpDir, uid, 'local', 'signals', `${ymd}.jsonl`);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, signals.map((s) => JSON.stringify(s)).join('\n') + '\n');+}++function sig(overrides: any): any {+ return {+ id: `sig_${Math.random().toString(36).slice(2)}`,+ ts: new Date().toISOString(),+ source: 'event',+ cid: 'c1',+ aid: 'agent-x',+ turn_id: 't1',+ context_ref: { msg_ids: [] },+ extractor_version: '[email protected]',+ ...overrides,+ };+}++// ── estimateTokens ──────────────────────────────────────────────────────++describe('reflection-transcript › estimateTokens', () => {+ it('uses ~4 chars/token for English text', async () => {+ const mod = await loadModule();+ // "hello world" = 11 chars / 4 ≈ 3 tokens+ expect(mod.estimateTokens('hello world')).toBe(3);+ });++ it('uses ~0.7 token/char for CJK text', async () => {+ const mod = await loadModule();+ // "你好世界" 4 chars * 0.7 = 2.8 → 3+ expect(mod.estimateTokens('你好世界')).toBe(3);+ });++ it('handles mixed Chinese / English correctly', async () => {+ const mod = await loadModule();+ // "hello 世界" = 6 ASCII chars / 4 + 2 CJK * 0.7 = 1.5 + 1.4 = 2.9 → 3+ expect(mod.estimateTokens('hello 世界')).toBe(3);+ });++ it('returns 0 for empty string', async () => {+ const mod = await loadModule();+ expect(mod.estimateTokens('')).toBe(0);+ });+});++// ── parseMsgWrapper / extractors (pure) ─────────────────────────────────++describe('reflection-transcript › parseMsgWrapper', () => {+ it('extracts from + inner text from a well-formed wrapper', async () => {+ const { _internals } = await loadModule();+ const r = _internals.parseMsgWrapper('<msg from="user" to="commander">\nhello\n</msg>');+ expect(r).toEqual({ from: 'user', inner: 'hello' });+ });++ it('treats unwrapped text as user (defensive default)', async () => {+ const { _internals } = await loadModule();+ const r = _internals.parseMsgWrapper('raw legacy text');+ expect(r.from).toBe('user');+ expect(r.inner).toBe('raw legacy text');+ });++ it('extracts non-user from (e.g. commander dispatch)', async () => {+ const { _internals } = await loadModule();+ const r = _internals.parseMsgWrapper('<msg from="commander" to="agent-x">dispatch payload</msg>');+ expect(r.from).toBe('commander');+ });+});++describe('reflection-transcript › extractUserEntries', () => {+ it('keeps role=user text messages where from=user', async () => {+ const { _internals } = await loadModule();+ const entries = _internals.extractUserEntries([+ userMsg('hello', 100, 'user', 'commander'),+ userMsg('dispatched payload', 200, 'commander', 'agent-x'), // not user+ ]);+ expect(entries.length).toBe(1);+ expect(entries[0].text).toBe('hello');+ expect(entries[0].kind).toBe('user');+ });++ it('skips messages without ts', async () => {+ const { _internals } = await loadModule();+ const entries = _internals.extractUserEntries([+ { role: 'user', content: [{ type: 'text', text: '<msg from="user" to="commander">x</msg>' }] },+ ]);+ expect(entries.length).toBe(0);+ });++ it('drops tool_result content blocks (no false positives)', async () => {+ const { _internals } = await loadModule();+ const entries = _internals.extractUserEntries([+ {+ role: 'user',+ content: [{ type: 'tool_result', toolUseId: 'a', content: 'output', isError: false }],+ ts: 100,+ },+ ]);+ expect(entries.length).toBe(0);+ });+});++describe('reflection-transcript › extractAgentEntries', () => {+ it('keeps role=assistant text only, skipping thinking/tool_use', async () => {+ const { _internals } = await loadModule();+ const entries = _internals.extractAgentEntries([+ {+ role: 'assistant',+ ts: 100,+ content: [+ { type: 'thinking', thinking: 'noise' },+ { type: 'tool_use', name: 'bash', input: {} },+ { type: 'text', text: 'the actual reply' },+ ],+ },+ ]);+ expect(entries.length).toBe(1);+ expect(entries[0].text).toBe('the actual reply');+ });++ it('truncates agent reply to MAX_AGENT_REPLY_CHARS', async () => {+ const mod = await loadModule();+ const long = 'X'.repeat(2000);+ const entries = mod._internals.extractAgentEntries([+ { role: 'assistant', ts: 100, content: [{ type: 'text', text: long }] },+ ]);+ expect(entries.length).toBe(1);+ expect(entries[0].text.length).toBeLessThanOrEqual(mod.MAX_AGENT_REPLY_CHARS + 20);+ expect(entries[0].text).toContain('truncated');+ });++ it('skips messages with only tool_use / thinking (no text)', async () => {+ const { _internals } = await loadModule();+ const entries = _internals.extractAgentEntries([+ { role: 'assistant', ts: 100, content: [{ type: 'tool_use', name: 'bash' }] },+ ]);+ expect(entries.length).toBe(0);+ });+});++// ── renderSignalEntry ───────────────────────────────────────────────────++describe('reflection-transcript › renderSignalEntry', () => {+ it('renders retry with step_index', async () => {+ const { _internals } = await loadModule();+ const e = _internals.renderSignalEntry(sig({ type: 'retry', metadata: { step_index: 3 } }));+ expect(e?.kind).toBe('system');+ expect(e?.text).toContain('retry');+ expect(e?.text).toContain('step #3');+ });++ it('renders form_left_blank distinguishing required field', async () => {+ const { _internals } = await loadModule();+ const required = _internals.renderSignalEntry(sig({+ type: 'form_left_blank',+ metadata: { input_id: 'budget', was_required: true },+ }));+ expect(required?.text).toContain('required field');+ expect(required?.text).toContain('budget');++ const optional = _internals.renderSignalEntry(sig({+ type: 'form_left_blank',+ metadata: { input_id: 'note', was_required: false },+ }));+ expect(optional?.text).not.toContain('required');+ });++ it('returns null for non-system signal types', async () => {+ const { _internals } = await loadModule();+ expect(_internals.renderSignalEntry(sig({ type: 'correction' as any }))).toBeNull();+ expect(_internals.renderSignalEntry(sig({ type: 'tool_failure' as any }))).toBeNull();+ });+});++// ── buildTranscript (I/O) ───────────────────────────────────────────────++describe('reflection-transcript › buildTranscript', () => {+ it('returns empty when no matching conversations exist', async () => {+ const mod = await loadModule();+ const r = await mod.buildTranscript(TEST_UID, '_default', Date.now() - 86400000);+ expect(r.text).toBe('');+ expect(r.stats.convsIncluded).toBe(0);+ });++ it('joins gconv user msgs with gmember agent replies in time order', async () => {+ const { sessionId, gmemberSessionId } = writeConv(TEST_UID, { cid: 'c1', agentId: 'agent-x' });+ writeSessionJsonl(TEST_UID, sessionId, [+ userMsg('first question', 100, 'user', 'commander'),+ userMsg('follow up', 300, 'user', 'commander'),+ ]);+ writeSessionJsonl(TEST_UID, gmemberSessionId, [+ agentMsg('first answer', 200),+ agentMsg('second answer', 400),+ ]);++ const mod = await loadModule();+ const r = await mod.buildTranscript(TEST_UID, 'agent-x', 0);++ expect(r.stats.convsIncluded).toBe(1);+ // Order: 100 user, 200 agent, 300 user, 400 agent+ const i1 = r.text.indexOf('first question');+ const i2 = r.text.indexOf('first answer');+ const i3 = r.text.indexOf('follow up');+ const i4 = r.text.indexOf('second answer');+ expect(i1).toBeGreaterThan(0);+ expect(i1).toBeLessThan(i2);+ expect(i2).toBeLessThan(i3);+ expect(i3).toBeLessThan(i4);+ });++ it('uses gconv assistant for _default agent (no gmember)', async () => {+ const { sessionId } = writeConv(TEST_UID, { cid: 'c-default', agentId: '' });+ writeSessionJsonl(TEST_UID, sessionId, [+ userMsg('q', 100, 'user', 'commander'),+ agentMsg('commander reply (no gmember)', 200),+ ]);+ // Deliberately do NOT write a gmember file.++ const mod = await loadModule();+ const r = await mod.buildTranscript(TEST_UID, '_default', 0);++ expect(r.stats.convsIncluded).toBe(1);+ expect(r.text).toContain('commander reply');+ });++ it('drops conversations whose newest msg predates sinceMs', async () => {+ const { sessionId, gmemberSessionId } = writeConv(TEST_UID, { cid: 'c-old', agentId: 'agent-x' });+ writeSessionJsonl(TEST_UID, sessionId, [+ userMsg('old', 100, 'user', 'commander'),+ ]);+ writeSessionJsonl(TEST_UID, gmemberSessionId, [+ agentMsg('old reply', 200),+ ]);++ const mod = await loadModule();+ const r = await mod.buildTranscript(TEST_UID, 'agent-x', 10_000); // sinceMs > all msg ts++ expect(r.stats.convsIncluded).toBe(0);+ });++ it('caps at MAX_CONVS and drops older convs first', async () => {+ const mod = await loadModule();+ // Create 7 convs all for agent-x+ for (let i = 0; i < 7; i++) {+ const cid = `c${i}`;+ const { sessionId, gmemberSessionId } = writeConv(TEST_UID, { cid, agentId: 'agent-x' });+ const baseTs = 1_000 + i * 1_000; // ascending by index+ writeSessionJsonl(TEST_UID, sessionId, [userMsg(`q${i}`, baseTs, 'user', 'commander')]);+ writeSessionJsonl(TEST_UID, gmemberSessionId, [agentMsg(`a${i}`, baseTs + 100)]);+ }++ const r = await mod.buildTranscript(TEST_UID, 'agent-x', 0);+ expect(r.stats.convsConsidered).toBe(7);+ expect(r.stats.convsIncluded).toBe(mod.MAX_CONVS);+ expect(r.stats.convsTruncated).toBeGreaterThanOrEqual(2);++ // Should have the most recent 5 (c2..c6), drop c0/c1+ expect(r.text).not.toContain('q0');+ expect(r.text).not.toContain('q1');+ expect(r.text).toContain('q6');+ });++ it('injects retry / skip system events at the right cid + ts', async () => {+ const { sessionId, gmemberSessionId } = writeConv(TEST_UID, { cid: 'c1', agentId: 'agent-x' });+ writeSessionJsonl(TEST_UID, sessionId, [userMsg('q', 100, 'user', 'commander')]);+ writeSessionJsonl(TEST_UID, gmemberSessionId, [agentMsg('a', 200)]);++ const retryTs = new Date(150).toISOString();+ const skipTs = new Date(250).toISOString();+ writeSignalsJsonl(TEST_UID, [+ sig({ type: 'retry', cid: 'c1', aid: 'agent-x', ts: retryTs, metadata: { step_index: 2 } }),+ sig({ type: 'skip', cid: 'c1', aid: 'agent-x', ts: skipTs, metadata: { step_index: 3 } }),+ sig({ type: 'correction', cid: 'c1', aid: 'agent-x', ts: retryTs }), // NOT inlined+ ]);++ const mod = await loadModule();+ const r = await mod.buildTranscript(TEST_UID, 'agent-x', 0);++ expect(r.text).toContain('retry on step #2');+ expect(r.text).toContain('skip on step #3');+ // Correction signal must NOT be inlined (deferred to future critic / weekly review).+ expect(r.text).not.toMatch(/system event.*correction/);+ // Time order: q(100) → retry(150) → a(200) → skip(250)+ const iQ = r.text.indexOf('q\n') >= 0 ? r.text.indexOf('q\n') : r.text.indexOf('q');+ const iRetry = r.text.indexOf('retry');+ const iA = r.text.indexOf('a\n') >= 0 ? r.text.indexOf('a\n') : r.text.indexOf(']\na');+ const iSkip = r.text.indexOf('skip');+ expect(iQ).toBeLessThan(iRetry);+ expect(iRetry).toBeLessThan(iA);+ expect(iA).toBeLessThan(iSkip);+ });++ it('filters convs by agent_id (different agent gets nothing)', async () => {+ const a = writeConv(TEST_UID, { cid: 'c1', agentId: 'agent-x' });+ const b = writeConv(TEST_UID, { cid: 'c2', agentId: 'agent-y' });+ writeSessionJsonl(TEST_UID, a.sessionId, [userMsg('for x', 100, 'user', 'commander')]);+ writeSessionJsonl(TEST_UID, a.gmemberSessionId, [agentMsg('x reply', 200)]);+ writeSessionJsonl(TEST_UID, b.sessionId, [userMsg('for y', 300, 'user', 'commander')]);+ writeSessionJsonl(TEST_UID, b.gmemberSessionId, [agentMsg('y reply', 400)]);++ const mod = await loadModule();+ const rx = await mod.buildTranscript(TEST_UID, 'agent-x', 0);+ expect(rx.text).toContain('for x');+ expect(rx.text).not.toContain('for y');++ const ry = await mod.buildTranscript(TEST_UID, 'agent-y', 0);+ expect(ry.text).toContain('for y');+ expect(ry.text).not.toContain('for x');+ });++ it('tolerates missing gmember session file (defensive)', async () => {+ const { sessionId } = writeConv(TEST_UID, { cid: 'c1', agentId: 'agent-x' });+ writeSessionJsonl(TEST_UID, sessionId, [userMsg('lone q', 100, 'user', 'commander')]);+ // No gmember file written — agent never responded yet.++ const mod = await loadModule();+ const r = await mod.buildTranscript(TEST_UID, 'agent-x', 0);++ // User entry still produces a section.+ expect(r.stats.convsIncluded).toBe(1);+ expect(r.text).toContain('lone q');+ });+});diff --git a/test/main/features/reflection-trigger.test.ts b/test/main/features/reflection-trigger.test.tsdeleted file mode 100644index dd4ab949..00000000--- a/test/main/features/reflection-trigger.test.ts+++ /dev/null@@ -1,310 +0,0 @@-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-import * as fs from 'node:fs';-import * as os from 'node:os';-import * as path from 'node:path';--let tmpDir: string;-let prevWs: string | undefined;-const TEST_UID = 'u1';--function stateFile(uid: string): string {- return path.join(tmpDir, uid, 'local', 'config', 'reflection-state.json');-}--function customAgentsDir(uid: string): string {- return path.join(tmpDir, uid, 'cloud', 'agents');-}--function writeAgent(uid: string, agentId: string): void {- // Agent 目录形态:agents/<aid>/agent.json (详见 docs/plans/agent-as-directory.md)- const aDir = path.join(customAgentsDir(uid), agentId);- fs.mkdirSync(aDir, { recursive: true });- fs.writeFileSync(- path.join(aDir, 'agent.json'),- JSON.stringify({ agent_id: agentId, name: agentId, description: '', workflow: '', updated_at: new Date().toISOString() }),- );-}--beforeEach(async () => {- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-reflect-'));- prevWs = process.env.ORKAS_WORKSPACE_ROOT;- process.env.ORKAS_WORKSPACE_ROOT = tmpDir;- vi.resetModules();- const users = await import('../../../src/main/features/users');- users.activateUser(TEST_UID);-});--afterEach(() => {- process.env.ORKAS_WORKSPACE_ROOT = prevWs;- fs.rmSync(tmpDir, { recursive: true, force: true });-});--async function loadModule() {- return import('../../../src/main/features/reflection-trigger');-}--// ── pickEligibleAgents (pure) ──────────────────────────────────────────--describe('reflection-trigger › pickEligibleAgents', () => {- it('returns all agents when state is empty', async () => {- const mod = await loadModule();- const eligible = mod.pickEligibleAgents(['a', 'b', '_default'], { lastReflectedAt: {} }, Date.now());- expect(eligible).toEqual(['a', 'b', '_default']);- });-- it('filters out agents within cooldown', async () => {- const mod = await loadModule();- const now = new Date('2026-04-23T12:00:00Z').getTime();- const oneHourAgo = new Date('2026-04-23T11:00:00Z').toISOString();- const eligible = mod.pickEligibleAgents(- ['recent', 'old'],- { lastReflectedAt: { recent: oneHourAgo } },- now,- );- expect(eligible).toEqual(['old']);- });-- it('keeps agents past cooldown', async () => {- const mod = await loadModule();- const now = new Date('2026-04-23T12:00:00Z').getTime();- const fiftyHoursAgo = new Date('2026-04-21T10:00:00Z').toISOString();- const eligible = mod.pickEligibleAgents(- ['ancient'],- { lastReflectedAt: { ancient: fiftyHoursAgo } },- now,- );- expect(eligible).toEqual(['ancient']);- });-- it('treats invalid timestamps as "never reflected" (defensive)', async () => {- const mod = await loadModule();- const eligible = mod.pickEligibleAgents(- ['broken'],- { lastReflectedAt: { broken: 'not-a-date' } },- Date.now(),- );- expect(eligible).toEqual(['broken']);- });-- it('honors custom cooldownHours', async () => {- const mod = await loadModule();- const now = new Date('2026-04-23T12:00:00Z').getTime();- const twoHoursAgo = new Date('2026-04-23T10:00:00Z').toISOString();- // 1-hour cooldown → eligible; 3-hour cooldown → not eligible- expect(mod.pickEligibleAgents(['x'], { lastReflectedAt: { x: twoHoursAgo } }, now, 1)).toEqual(['x']);- expect(mod.pickEligibleAgents(['x'], { lastReflectedAt: { x: twoHoursAgo } }, now, 3)).toEqual([]);- });-- it('exact boundary: now - lastReflectedAt === cooldown is eligible', async () => {- const mod = await loadModule();- const now = new Date('2026-04-23T12:00:00Z').getTime();- const exactlyAtCooldown = new Date(now - 48 * 3600 * 1000).toISOString();- expect(mod.pickEligibleAgents(['x'], { lastReflectedAt: { x: exactlyAtCooldown } }, now)).toEqual(['x']);- });-});--// ── readReflectionState / writeReflectionState ─────────────────────────--describe('reflection-trigger › state IO', () => {- it('reads empty state when file missing', async () => {- const mod = await loadModule();- const state = mod.readReflectionState(TEST_UID);- expect(state).toEqual({ lastReflectedAt: {} });- });-- it('round-trips state through write+read', async () => {- const mod = await loadModule();- mod.writeReflectionState(TEST_UID, { lastReflectedAt: { foo: '2026-04-23T00:00:00Z' } });- expect(fs.existsSync(stateFile(TEST_UID))).toBe(true);- const state = mod.readReflectionState(TEST_UID);- expect(state).toEqual({ lastReflectedAt: { foo: '2026-04-23T00:00:00Z' } });- });-- it('treats malformed JSON as empty state (no throw)', async () => {- const mod = await loadModule();- // Pre-create the dir then write garbage.- fs.mkdirSync(path.dirname(stateFile(TEST_UID)), { recursive: true });- fs.writeFileSync(stateFile(TEST_UID), 'not json {{{');- const state = mod.readReflectionState(TEST_UID);- expect(state).toEqual({ lastReflectedAt: {} });- });-- it('treats valid JSON without lastReflectedAt as empty state', async () => {- const mod = await loadModule();- fs.mkdirSync(path.dirname(stateFile(TEST_UID)), { recursive: true });- fs.writeFileSync(stateFile(TEST_UID), JSON.stringify({ random: true }));- const state = mod.readReflectionState(TEST_UID);- expect(state).toEqual({ lastReflectedAt: {} });- });-- it('filters non-string timestamp values', async () => {- const mod = await loadModule();- fs.mkdirSync(path.dirname(stateFile(TEST_UID)), { recursive: true });- fs.writeFileSync(stateFile(TEST_UID), JSON.stringify({- lastReflectedAt: { good: '2026-04-23T00:00:00Z', bad: 12345, also_bad: null },- }));- const state = mod.readReflectionState(TEST_UID);- expect(state.lastReflectedAt).toEqual({ good: '2026-04-23T00:00:00Z' });- });-});--// ── runStartupReflections (orchestrator with mocked reflect) ───────────--describe('reflection-trigger › runStartupReflections', () => {- it('no-ops when uid is empty', async () => {- const mod = await loadModule();- const reflect = vi.fn().mockResolvedValue(undefined);- await mod.runStartupReflections('', { reflect });- expect(reflect).not.toHaveBeenCalled();- });-- it('reflects for _default plus every custom agent and stamps state', async () => {- writeAgent(TEST_UID, 'agent-foo');- writeAgent(TEST_UID, 'agent-bar');- const mod = await loadModule();- const reflect = vi.fn().mockResolvedValue(undefined);- const now = new Date('2026-04-23T12:00:00Z').getTime();- await mod.runStartupReflections(TEST_UID, { reflect, now: () => now });-- // Called for each agent (order: _default first, then customs sorted).- const calls = reflect.mock.calls.map((c) => c[1] as string);- expect(calls).toContain('_default');- expect(calls).toContain('agent-foo');- expect(calls).toContain('agent-bar');- expect(calls.length).toBe(3);-- // State file stamped for each.- const state = mod.readReflectionState(TEST_UID);- expect(state.lastReflectedAt['_default']).toBe(new Date(now).toISOString());- expect(state.lastReflectedAt['agent-foo']).toBe(new Date(now).toISOString());- expect(state.lastReflectedAt['agent-bar']).toBe(new Date(now).toISOString());- });-- it('skips agents within cooldown', async () => {- writeAgent(TEST_UID, 'agent-recent');- writeAgent(TEST_UID, 'agent-old');- const mod = await loadModule();- const now = new Date('2026-04-23T12:00:00Z').getTime();- // Pre-stamp agent-recent within cooldown, agent-old long ago, _default never.- mod.writeReflectionState(TEST_UID, {- lastReflectedAt: {- 'agent-recent': new Date(now - 1 * 3600 * 1000).toISOString(),- 'agent-old': new Date(now - 100 * 3600 * 1000).toISOString(),- },- });-- const reflect = vi.fn().mockResolvedValue(undefined);- await mod.runStartupReflections(TEST_UID, { reflect, now: () => now });-- const calls = reflect.mock.calls.map((c) => c[1]).sort();- expect(calls).toEqual(['_default', 'agent-old']);- // recent's timestamp untouched- const state = mod.readReflectionState(TEST_UID);- expect(state.lastReflectedAt['agent-recent']).toBe(new Date(now - 1 * 3600 * 1000).toISOString());- expect(state.lastReflectedAt['agent-old']).toBe(new Date(now).toISOString());- });-- it('does NOT stamp state when reflection throws', async () => {- writeAgent(TEST_UID, 'agent-fail');- const mod = await loadModule();- const reflect = vi.fn(async (_uid: string, agentId: string) => {- if (agentId === 'agent-fail') throw new Error('llm down');- });- const now = new Date('2026-04-23T12:00:00Z').getTime();- await mod.runStartupReflections(TEST_UID, { reflect, now: () => now });-- const state = mod.readReflectionState(TEST_UID);- expect(state.lastReflectedAt['_default']).toBe(new Date(now).toISOString());- // Failure → not stamped → eligible again next time.- expect(state.lastReflectedAt['agent-fail']).toBeUndefined();- });-- it('does not abort the batch when one agent fails', async () => {- writeAgent(TEST_UID, 'agent-1');- writeAgent(TEST_UID, 'agent-fail');- writeAgent(TEST_UID, 'agent-2');- const mod = await loadModule();- const reflect = vi.fn(async (_uid: string, agentId: string) => {- if (agentId === 'agent-fail') throw new Error('boom');- });- await mod.runStartupReflections(TEST_UID, { reflect });- const calls = reflect.mock.calls.map((c) => c[1] as string);- // All four (including the failing one) attempted.- expect(calls.length).toBe(4);- expect(calls).toContain('agent-1');- expect(calls).toContain('agent-2');- expect(calls).toContain('agent-fail');- });-- it('per-uid state isolation', async () => {- const otherUid = 'u2';- writeAgent(TEST_UID, 'agent-shared-name');- const mod = await loadModule();- const now = new Date('2026-04-23T12:00:00Z').getTime();- // Stamp uid u2 (would skip everything if state were shared).- mod.writeReflectionState(otherUid, {- lastReflectedAt: { '_default': new Date(now).toISOString(), 'agent-shared-name': new Date(now).toISOString() },- });-- const reflect = vi.fn().mockResolvedValue(undefined);- await mod.runStartupReflections(TEST_UID, { reflect, now: () => now });- // u1 never reflected → all eligible regardless of u2 state.- expect(reflect.mock.calls.map((c) => c[1])).toContain('_default');- expect(reflect.mock.calls.map((c) => c[1])).toContain('agent-shared-name');-- // u1 state stamped, u2 state untouched at 12:00:00Z (we wrote it ourselves above).- const u1State = mod.readReflectionState(TEST_UID);- const u2State = mod.readReflectionState(otherUid);- expect(u1State.lastReflectedAt['_default']).toBe(new Date(now).toISOString());- expect(u2State.lastReflectedAt['_default']).toBe(new Date(now).toISOString());- expect(stateFile(TEST_UID)).not.toBe(stateFile(otherUid));- });-- it('passes sinceMs from prior lastReflectedAt to reflect()', async () => {- writeAgent(TEST_UID, 'agent-x');- const mod = await loadModule();- const now = new Date('2026-04-23T12:00:00Z').getTime();- const lastIso = new Date(now - 100 * 3600 * 1000).toISOString(); // outside cooldown- mod.writeReflectionState(TEST_UID, { lastReflectedAt: { 'agent-x': lastIso } });-- const reflect = vi.fn().mockResolvedValue(undefined);- await mod.runStartupReflections(TEST_UID, { reflect, now: () => now });-- const agentXCall = reflect.mock.calls.find((c) => c[1] === 'agent-x');- expect(agentXCall).toBeDefined();- // Third arg should be the parsed lastIso, NOT the default lookback.- expect(agentXCall![2]).toBe(Date.parse(lastIso));- });-- it('falls back to default lookback when no prior lastReflectedAt', async () => {- const mod = await loadModule();- const now = new Date('2026-04-23T12:00:00Z').getTime();- const reflect = vi.fn().mockResolvedValue(undefined);- await mod.runStartupReflections(TEST_UID, { reflect, now: () => now });-- const defaultCall = reflect.mock.calls.find((c) => c[1] === '_default');- expect(defaultCall).toBeDefined();- // First-ever reflection → 7 day lookback.- const expectedSince = now - 7 * 24 * 3600 * 1000;- expect(defaultCall![2]).toBe(expectedSince);- });-- it('runs sequentially (next reflect awaited before previous returns)', async () => {- writeAgent(TEST_UID, 'a1');- writeAgent(TEST_UID, 'a2');- const mod = await loadModule();-- const order: string[] = [];- const reflect = vi.fn(async (_uid: string, agentId: string) => {- order.push(`start:${agentId}`);- await new Promise((r) => setTimeout(r, 10));- order.push(`end:${agentId}`);- });-- await mod.runStartupReflections(TEST_UID, { reflect });- // Each agent's start/end pair must not interleave with another agent's pair.- for (let i = 0; i < order.length; i += 2) {- expect(order[i].replace('start:', '')).toBe(order[i + 1].replace('end:', ''));- }- });-});diff --git a/test/main/features/skills.test.ts b/test/main/features/skills.test.tsindex 3b23499a..be02443e 100644--- a/test/main/features/skills.test.ts+++ b/test/main/features/skills.test.ts@@ -476,7 +476,7 @@ describe('skills › applySkillContainerFromCommander › edit', () => {files: [{ path: 'SKILL.md', content: '---\nname: "shipped"\n---\n\ntampered\n' }],});expect(r.ok).toBe(false);- expect(r.error).toMatch(/built-in|内置/i);+ expect(r.error).toMatch(/marketplace|平台技能|マーケットプレイス/i);// Original body preserved.expect(fs.readFileSync(path.join(builtinSkillsDir(), 'shipped', 'SKILL.md'), 'utf8')).toContain('body');@@ -646,7 +646,7 @@ describe('skills › createCustomSkill', () => {const builtinDir = path.join(builtinSkillsDir(), 'fixed');fs.mkdirSync(builtinDir, { recursive: true });const s = await loadSkills();- await expect(s.createCustomSkill('fixed', '')).rejects.toThrow(/conflicts with a built-in|内置技能冲突/);+ await expect(s.createCustomSkill('fixed', '')).rejects.toThrow(/conflicts with a marketplace|与平台技能冲突|マーケットプレイスのスキルと競合/);});});diff --git a/test/main/ipc/conversations-send-stream.test.ts b/test/main/ipc/conversations-send-stream.test.tsnew file mode 100644index 00000000..11a432a0--- /dev/null+++ b/test/main/ipc/conversations-send-stream.test.ts@@ -0,0 +1,162 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';++type StreamStartFn = (+ event: { sender: { isDestroyed: () => boolean; send: (channel: string, payload: unknown) => void } },+ req: { requestId: string; channel: string; payload?: unknown },+) => Promise<void>;++let streamStartHandler: StreamStartFn | null = null;++const groupChatMock = vi.hoisted(() => ({+ subscribers: new Set<(ev: unknown) => void>(),+ quiescent: false,+ releaseSend: null as null | (() => void),+ resolveSendStarted: null as null | (() => void),+ resolveSendFinished: null as null | (() => void),+ sendStarted: Promise.resolve(),+ sendFinished: Promise.resolve(),+}));++vi.mock('electron', () => ({+ ipcMain: {+ handle: vi.fn(),+ on: (channel: string, fn: StreamStartFn) => {+ if (channel === 'orkas.streamStart') streamStartHandler = fn;+ },+ },+ shell: { openExternal: vi.fn(async () => undefined), showItemInFolder: vi.fn() },+ BrowserWindow: { getAllWindows: vi.fn(() => []), getFocusedWindow: vi.fn(() => null) },+ dialog: { showOpenDialog: vi.fn(async () => ({ canceled: true, filePaths: [] })) },+}));++vi.mock('../../../src/main/features/group_chat', () => ({+ subscribeBus: vi.fn((_userId: string, _cid: string, cb: (ev: unknown) => void) => {+ groupChatMock.subscribers.add(cb);+ return () => groupChatMock.subscribers.delete(cb);+ }),+ send: vi.fn(async () => {+ groupChatMock.resolveSendStarted?.();+ await new Promise<void>((resolve) => { groupChatMock.releaseSend = resolve; });+ groupChatMock.resolveSendFinished?.();+ return { ok: true };+ }),+ busIsQuiescent: vi.fn(() => groupChatMock.quiescent),+ streamEvents: vi.fn(async function* () {}),+}));++let tmpDir: string;+let prevWs: string | undefined;+const TEST_UID = 'u1';++beforeEach(async () => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-send-stream-ipc-'));+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;+ streamStartHandler = null;+ groupChatMock.subscribers.clear();+ groupChatMock.quiescent = false;+ groupChatMock.releaseSend = null;+ groupChatMock.sendStarted = new Promise<void>((resolve) => { groupChatMock.resolveSendStarted = resolve; });+ groupChatMock.sendFinished = new Promise<void>((resolve) => { groupChatMock.resolveSendFinished = resolve; });+ vi.resetModules();++ const users = await import('../../../src/main/features/users');+ users.activateUser(TEST_UID);+ const ipc = await import('../../../src/main/ipc/index');+ ipc.register();+});++afterEach(() => {+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++async function waitFor(predicate: () => boolean, timeoutMs = 500): Promise<void> {+ const started = Date.now();+ while (Date.now() - started < timeoutMs) {+ if (predicate()) return;+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+ expect(predicate()).toBe(true);+}++describe('ipc › conversations.sendStream', () => {+ it('relays group bus events before groupChat.send resolves', async () => {+ if (!streamStartHandler) throw new Error('stream handler not registered');+ const sent: Array<{ channel: string; payload: any }> = [];+ const sender = {+ isDestroyed: () => false,+ send: (channel: string, payload: unknown) => sent.push({ channel, payload }),+ };++ const run = streamStartHandler(+ { sender },+ {+ requestId: 'req1',+ channel: 'conversations.sendStream',+ payload: { cid: 'c123abc', content: 'go' },+ },+ );+ await groupChatMock.sendStarted;++ const liveEvent = {+ type: 'process',+ cid: 'c123abc',+ actor: 'agent1',+ data: { type: 'delta', text: 'live' },+ };+ for (const cb of groupChatMock.subscribers) cb(liveEvent);++ await waitFor(() => sent.some((item) => item.channel === 'stream:req1' && item.payload?.event?.data === liveEvent));+ expect(sent.some((item) => item.payload?.type === 'done')).toBe(false);++ groupChatMock.quiescent = true;+ groupChatMock.releaseSend?.();+ await run;++ expect(sent.at(-1)).toEqual({ channel: 'stream:req1', payload: { type: 'done' } });+ });++ it('keeps relaying group bus events after groupChat.send resolves while the bus is still active', async () => {+ if (!streamStartHandler) throw new Error('stream handler not registered');+ const sent: Array<{ channel: string; payload: any }> = [];+ const sender = {+ isDestroyed: () => false,+ send: (channel: string, payload: unknown) => sent.push({ channel, payload }),+ };++ const run = streamStartHandler(+ { sender },+ {+ requestId: 'req2',+ channel: 'conversations.sendStream',+ payload: { cid: 'c123abc', content: 'go' },+ },+ );+ await groupChatMock.sendStarted;+ groupChatMock.quiescent = false;+ groupChatMock.releaseSend?.();+ await groupChatMock.sendFinished;++ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(sent.some((item) => item.payload?.type === 'done')).toBe(false);++ const liveEvent = {+ type: 'process',+ cid: 'c123abc',+ actor: 'agent1',+ data: { type: 'event', event: { stream: 'tool', data: { phase: 'start', id: 't1', name: 'web_search' } } },+ };+ for (const cb of groupChatMock.subscribers) cb(liveEvent);++ await waitFor(() => sent.some((item) => item.channel === 'stream:req2' && item.payload?.event?.data === liveEvent));+ groupChatMock.quiescent = true;+ for (const cb of groupChatMock.subscribers) cb({ type: 'state_changed', cid: 'c123abc', state: { status: 'idle', in_flight: [] } });+ await run;++ expect(sent.at(-1)).toEqual({ channel: 'stream:req2', payload: { type: 'done' } });+ });+});diff --git a/test/main/ipc/produced-readText.test.ts b/test/main/ipc/produced-readText.test.tsindex ff65ff5b..bca22e79 100644--- a/test/main/ipc/produced-readText.test.ts+++ b/test/main/ipc/produced-readText.test.ts@@ -39,20 +39,22 @@ async function callReadText(const userWorkspace = await import('../../../src/main/features/user_workspace');const { chatAttachmentDir } = await import('../../../src/main/paths');const { safeId } = await import('../../../src/main/storage');+ const { isPathAllowed } = await import('../../../src/main/util/path-sandbox');const target = input?.path;if (typeof target !== 'string' || !target) return { ok: false, error: 'missing path' };const ws = userWorkspace.getWorkspacePath(userId);const norm = path.resolve(target);- const wsNorm = path.resolve(ws);const cidRaw = input?.cid;const attachmentScope = (typeof cidRaw === 'string' && cidRaw && safeId(cidRaw))? path.resolve(chatAttachmentDir(userId, cidRaw)): null;- const inAttachment = !!attachmentScope &&- (norm === attachmentScope || norm.startsWith(attachmentScope + path.sep));- const inWorkspace = norm === wsNorm || norm.startsWith(wsNorm + path.sep);- if (!inWorkspace && !inAttachment) {+ // Mirrors `ipc/index.ts::produced.readText`: delegate the symlink-safe+ // sandbox check to `util/path-sandbox.isPathAllowed`. Drift here = drift+ // from the real handler.+ const allowedRoots: string[] = [path.resolve(ws)];+ if (attachmentScope) allowedRoots.push(attachmentScope);+ if (!isPathAllowed(norm, allowedRoots)) {return { ok: false, error: 'path is outside the user workspace' };}let st: fs.Stats;diff --git a/test/main/ipc/workspace-reveal.test.ts b/test/main/ipc/workspace-reveal.test.tsindex 8b881ee6..58b8ebed 100644--- a/test/main/ipc/workspace-reveal.test.ts+++ b/test/main/ipc/workspace-reveal.test.ts@@ -42,16 +42,19 @@ afterEach(() => {async function callRevealPath(userId: string, input: unknown): Promise<{ ok: boolean; error?: string; path?: string }> {// Bypass the full IPC runtime — call the feature directly with the same- // guard logic the handler uses. This mirrors the handler body in ipc/index.ts.+ // guard logic the handler uses. Mirrors `ipc/index.ts::workspace.revealPath`:+ // it delegates the symlink-safe sandbox check to `util/path-sandbox.isPathAllowed`+ // (via the `_ipcFileSandboxAllowedRoots` helper); the test reproduction tracks+ // that — drift here = drift from the real handler.const userWorkspace = await import('../../../src/main/features/user_workspace');+ const { isPathAllowed } = await import('../../../src/main/util/path-sandbox');const { shell } = await import('electron');const p = (input as { path?: unknown })?.path;if (!p || typeof p !== 'string') return { ok: false, error: 'missing path' };const abs = path.resolve(p);const wsRoot = path.resolve(userWorkspace.getWorkspacePath(userId));- const rel = path.relative(wsRoot, abs);- if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {+ if (!isPathAllowed(abs, [wsRoot])) {return { ok: false, error: 'path is outside the current workspace' };}if (!fs.existsSync(abs)) return { ok: false, error: 'file not found' };@@ -107,6 +110,50 @@ describe('workspace.revealPath › validation', () => {expect(showItemInFolder).not.toHaveBeenCalled();});+ it('rejects a symlink inside the workspace that points outside (symlink-escape)', async () => {+ // The bug class the isPathAllowed migration closes: a symlink planted+ // inside an allowed root (here, the user's workspace) that resolves to+ // a target OUTSIDE the allowed root. The previous lexical+ // `startsWith(wsRoot + sep)` check would let this through because the+ // symlink's textual path IS inside the workspace; `isPathAllowed` calls+ // `fs.realpathSync` on both sides and the rejection happens because the+ // resolved target sits outside the root.+ const ws = await import('../../../src/main/features/user_workspace');+ const wsDir = path.join(tmpDir, 'ws-sym');+ fs.mkdirSync(wsDir, { recursive: true });+ ws.setWorkspacePath('u-sym', wsDir);++ const outside = path.join(tmpDir, 'outside-target.txt');+ fs.writeFileSync(outside, 'attacker-controlled');++ const trap = path.join(wsDir, 'looks-inside.txt');+ fs.symlinkSync(outside, trap);++ const res = await callRevealPath('u-sym', { path: trap });+ expect(res.ok).toBe(false);+ expect(res.error).toMatch(/outside/);+ expect(showItemInFolder).not.toHaveBeenCalled();+ });++ it('accepts a symlink inside the workspace that points to another file inside the workspace', async () => {+ // The companion preservation case: a symlink whose target is also+ // within the allowed root MUST be accepted (otherwise `isPathAllowed`+ // would break legitimate `ln -s` use inside the workspace).+ const ws = await import('../../../src/main/features/user_workspace');+ const wsDir = path.join(tmpDir, 'ws-sym-ok');+ fs.mkdirSync(wsDir, { recursive: true });+ ws.setWorkspacePath('u-sym-ok', wsDir);++ const target = path.join(wsDir, 'real.pdf');+ fs.writeFileSync(target, '%PDF');+ const link = path.join(wsDir, 'link.pdf');+ fs.symlinkSync(target, link);++ const res = await callRevealPath('u-sym-ok', { path: link });+ expect(res.ok).toBe(true);+ expect(showItemInFolder).toHaveBeenCalledWith(link);+ });+it('rejects a non-string / missing path', async () => {const res1 = await callRevealPath('u1', {});expect(res1.ok).toBe(false);@@ -128,16 +175,20 @@ describe('workspace.revealPath › validation', () => {expect(showItemInFolder).not.toHaveBeenCalled();});- it('rejects the workspace root itself (empty relative path)', async () => {- // `path.relative(root, root)` === '' — the guard should treat this as- // "there's no file to reveal here".+ it('accepts the workspace root itself (revealing the workspace folder is a legit action)', async () => {+ // `isPathAllowed(root, [root])` returns true by design — revealing the+ // workspace root in Finder/Explorer is a legitimate "open my workspace"+ // request. The pre-refactor lexical guard also allowed this+ // (`norm === wsNorm` short-circuits the `&& norm !== wsNorm` arm in the+ // OR chain), so the behaviour is preserved across the isPathAllowed+ // migration.const ws = await import('../../../src/main/features/user_workspace');const dir = path.join(tmpDir, 'ws');fs.mkdirSync(dir, { recursive: true });ws.setWorkspacePath('u5', dir);const res = await callRevealPath('u5', { path: dir });- expect(res.ok).toBe(false);- expect(res.error).toMatch(/outside/);+ expect(res.ok).toBe(true);+ expect(showItemInFolder).toHaveBeenCalledWith(dir);});});diff --git a/test/main/logger.test.ts b/test/main/logger.test.tsindex b022e85a..a0884254 100644--- a/test/main/logger.test.ts+++ b/test/main/logger.test.ts@@ -58,6 +58,27 @@ describe('logger › redact', () => {expect(out.list[1].token).toBe('***REDACTED***');});+ it('masks PII field names (phone / mobile / email / username) but leaves name passthrough', async () => {+ const { redact } = await import('../../src/main/logger');+ const out = redact({+ phone: '13800138000',+ mobile: '+8613800138000',+ email: '[email protected]',+ username: 'alice',+ // `name` is intentionally NOT a redact key — too broad (agent.name etc).+ name: 'Alpha Agent',+ // PII-shaped fields nested in an array.+ contacts: [{ email: '[email protected]', phone: '13900139000' }],+ }) as any;+ expect(out.phone).toBe('***REDACTED***');+ expect(out.mobile).toBe('***REDACTED***');+ expect(out.email).toBe('***REDACTED***');+ expect(out.username).toBe('***REDACTED***');+ expect(out.name).toBe('Alpha Agent');+ expect(out.contacts[0].email).toBe('***REDACTED***');+ expect(out.contacts[0].phone).toBe('***REDACTED***');+ });+it('is case-insensitive on the key name', async () => {const { redact } = await import('../../src/main/logger');const out = redact({diff --git a/test/main/util/log-sanitize.test.ts b/test/main/util/log-sanitize.test.tsnew file mode 100644index 00000000..a7ed6846--- /dev/null+++ b/test/main/util/log-sanitize.test.ts@@ -0,0 +1,110 @@+/**+ * `sanitizeLogTextForUpload` — fixtures pin both the shapes that MUST be+ * masked (set A) and the look-alike shapes that MUST be preserved (set B).+ * Follows PC/CLAUDE.md §9 "Hard rule for LLM-output text munging" — the+ * same rule applies to any text-processing util whose accepted-input matrix+ * could be widened over time.+ */++import { describe, it, expect } from 'vitest';+import { sanitizeLogTextForUpload } from '../../../src/main/util/log-sanitize';++describe('sanitizeLogTextForUpload › set A (must be masked)', () => {+ it('masks Bearer token from raw Authorization header', () => {+ const out = sanitizeLogTextForUpload('Authorization: Bearer abc.def-123_XYZ');+ expect(out).toBe('Authorization: Bearer ***');+ });++ it('masks Bearer token inside a JSON-stringified blob', () => {+ const out = sanitizeLogTextForUpload('{"authorization":"Bearer eyJhbGc"}');+ expect(out).toBe('{"authorization":"Bearer ***"}');+ });++ it('is case-insensitive on the Bearer scheme name (RFC 6750)', () => {+ const out = sanitizeLogTextForUpload('Cookie: bearer x.y.z');+ expect(out).toBe('Cookie: Bearer ***');+ });++ it('masks a JWT-shaped 3-segment token', () => {+ const jwt = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjMifQ.signature-part';+ const out = sanitizeLogTextForUpload(`token=${jwt} expired`);+ expect(out).toBe('token=***JWT*** expired');+ });++ it('masks email to first-char + domain (Server mask_email parity)', () => {+ const out = sanitizeLogTextForUpload('user contacted [email protected] today');+ expect(out).toBe('user contacted a***@orkas.ai today');+ });++ it('masks CN mobile to 138****8000 (Server mask_phone parity)', () => {+ const out = sanitizeLogTextForUpload('phone reported as 13800138000 in audit');+ expect(out).toBe('phone reported as 138****8000 in audit');+ });++ it('applies multiple patterns in a single pass', () => {+ const out = sanitizeLogTextForUpload(+ 'Authorization: Bearer X; contact: [email protected]; phone 13800138000',+ );+ expect(out).toBe('Authorization: Bearer ***; contact: a***@b.io; phone 138****8000');+ });+});++describe('sanitizeLogTextForUpload › set B (must be preserved)', () => {+ it('leaves "BearerWord" (no whitespace after Bearer) untouched', () => {+ // word-boundary follower required — "Bearer" without trailing whitespace+ // is just a word in prose, not an auth header.+ const out = sanitizeLogTextForUpload('class BearerWord extends Auth');+ expect(out).toBe('class BearerWord extends Auth');+ });++ it('leaves a single base64url-looking segment (no JWT structure) untouched', () => {+ // "eyJfoo" by itself is not a JWT — needs three dot-separated segments.+ const out = sanitizeLogTextForUpload('payload prefix eyJfooBar after');+ expect(out).toBe('payload prefix eyJfooBar after');+ });++ it('leaves a malformed email (1-char TLD) untouched', () => {+ const out = sanitizeLogTextForUpload('placeholder [email protected] user note');+ expect(out).toBe('placeholder [email protected] user note');+ });++ it('leaves a 10-digit number (not a CN mobile) untouched', () => {+ const out = sanitizeLogTextForUpload('order id 1380013800 retrieved');+ expect(out).toBe('order id 1380013800 retrieved');+ });++ it('leaves a 12-digit number (too long for a CN mobile) untouched', () => {+ const out = sanitizeLogTextForUpload('measurement 138001380001 ms');+ expect(out).toBe('measurement 138001380001 ms');+ });++ it('leaves a SHA-like 40-hex string untouched (avoids commit-sha false positives)', () => {+ const sha = 'd24a12b33252f4c2f0b8c4c8cb790b610268bce7104dc531';+ const out = sanitizeLogTextForUpload(`merge base ${sha} resolved`);+ expect(out).toBe(`merge base ${sha} resolved`);+ });++ it('leaves the word "phone" or "email" in prose untouched (positional value-only matchers)', () => {+ // The redact() layer handles named field MASKING for keys phone/email/+ // username via REDACT_KEYS; this util only matches value-shaped text.+ const out = sanitizeLogTextForUpload('field "phone" missing in payload');+ expect(out).toBe('field "phone" missing in payload');+ });+});++describe('sanitizeLogTextForUpload › edge cases', () => {+ it('returns empty input unchanged', () => {+ expect(sanitizeLogTextForUpload('')).toBe('');+ });++ it('handles multi-line text', () => {+ const input = 'line 1: Bearer XYZ\nline 2: [email protected]\nline 3: 13800138000';+ const out = sanitizeLogTextForUpload(input);+ expect(out).toBe('line 1: Bearer ***\nline 2: a***@b.io\nline 3: 138****8000');+ });++ it('masks every occurrence in a single string (global flag)', () => {+ const out = sanitizeLogTextForUpload('Bearer A then Bearer B');+ expect(out).toBe('Bearer *** then Bearer ***');+ });+});diff --git a/test/renderer/auto-title-parity.test.ts b/test/renderer/auto-title-parity.test.tsnew file mode 100644index 00000000..a01dea4f--- /dev/null+++ b/test/renderer/auto-title-parity.test.ts@@ -0,0 +1,89 @@+/**+ * Lock the regex/constant parity between+ * `src/main/util/auto-title.ts` (backend persistence path —+ * imported by features/chats.ts)+ * `src/renderer/modules/auto-title.js` (renderer optimistic title path —+ * loaded as a `<script>` and+ * consumed via the `_autoTitle`+ * global by agents.js /+ * conversation.js / project-detail.js)+ *+ * The two copies exist because PC/CLAUDE.md §8 forbids `import` / `export`+ * in renderer files — they have to mirror by hand. This fixture is the+ * machinery that turns drift into a loud CI failure: adding a filler word+ * to one side without the other immediately fails the test.+ *+ * Also includes a functional fixture set that runs the renderer+ * `_autoTitle` on the same inputs `chats-autotitle.test.ts` pins for the+ * backend `autoTitle`, asserting both surfaces produce the same stripped+ * output. (The backend wraps the empty-result fall-through with+ * `t('chat.default_title')`; the renderer returns '' and lets the caller+ * fall back. The functional comparison runs on the pre-fallback transform+ * only — we slice the comparison to inputs whose stripped form is+ * non-empty, since the empty-input fallback is locale-dependent on the+ * backend side and out of scope for the parity check.)+ */++import { describe, it, expect } from 'vitest';++import * as mainAutoTitle from '../../src/main/util/auto-title';+// eslint-disable-next-line @typescript-eslint/no-var-requires+const rendererAutoTitle = require('../../src/renderer/modules/auto-title.js');+import { autoTitle as backendAutoTitle } from '../../src/main/features/chats';++const renderer: {+ _autoTitle: (text: string) => string;+ _AUTO_TITLE_ZH_FILLER: RegExp;+ _AUTO_TITLE_EN_FILLER: RegExp;+ _AUTO_TITLE_CLAUSE: RegExp;+ _AUTO_TITLE_MAX: number;+} = rendererAutoTitle;++describe('auto-title parity › regex source / flags match across main + renderer', () => {+ it('ZH_FILLER_RE.source matches', () => {+ expect(renderer._AUTO_TITLE_ZH_FILLER.source).toBe(mainAutoTitle.ZH_FILLER_RE.source);+ });++ it('ZH_FILLER_RE.flags match', () => {+ expect(renderer._AUTO_TITLE_ZH_FILLER.flags).toBe(mainAutoTitle.ZH_FILLER_RE.flags);+ });++ it('EN_FILLER_RE.source matches', () => {+ expect(renderer._AUTO_TITLE_EN_FILLER.source).toBe(mainAutoTitle.EN_FILLER_RE.source);+ });++ it('EN_FILLER_RE.flags match (case-insensitive on the EN list)', () => {+ expect(renderer._AUTO_TITLE_EN_FILLER.flags).toBe(mainAutoTitle.EN_FILLER_RE.flags);+ });++ it('CLAUSE_RE.source matches', () => {+ expect(renderer._AUTO_TITLE_CLAUSE.source).toBe(mainAutoTitle.CLAUSE_RE.source);+ });++ it('TITLE_MAX matches', () => {+ expect(renderer._AUTO_TITLE_MAX).toBe(mainAutoTitle.TITLE_MAX);+ });+});++describe('auto-title parity › functional equivalence on representative inputs', () => {+ // Shared inputs whose stripped form is non-empty (so the renderer ''+ // fallback and the backend `t()` fallback don't diverge by design).+ const cases = [+ '看下本地还有哪些修改没提交',+ '请帮我修复一下这个 bug',+ '想问问这个怎么实现',+ '请帮我看下数据库连接',+ 'Can you help me debug this?',+ 'Please review this PR',+ 'I want to refactor the auth flow',+ '帮我写一段 TypeScript 来解析 csv,谢谢',+ '这是一个很长的对话标题,应该会被三十字符的上限截断到刚好显示',+ 'AI,怎么样', // < 4-char clause floor; first clause not used+ ];++ for (const input of cases) {+ it(`backend autoTitle and renderer _autoTitle agree on: ${JSON.stringify(input.slice(0, 30))}`, () => {+ expect(backendAutoTitle(input)).toBe(renderer._autoTitle(input));+ });+ }+});diff --git a/test/renderer/conversation-info.test.ts b/test/renderer/conversation-info.test.tsnew file mode 100644index 00000000..512c8791--- /dev/null+++ b/test/renderer/conversation-info.test.ts@@ -0,0 +1,243 @@+import { describe, it, expect } from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as vm from 'node:vm';++function renderTaskHtml(snapshot: {+ history: any[];+ plan: any;+ members: any[];+}): Promise<string> {+ const elements = new Map<string, any>();+ const getEl = (id: string) => {+ if (!elements.has(id)) {+ elements.set(id, {+ id,+ hidden: false,+ innerHTML: '',+ dataset: {},+ classList: { toggle() {}, add() {}, remove() {} },+ setAttribute() {},+ addEventListener(type: string, fn: () => void) { this[`on${type}`] = fn; },+ });+ }+ return elements.get(id);+ };++ const context: any = {+ console,+ setTimeout,+ clearTimeout,+ encodeURIComponent,+ Date,+ Map,+ Array,+ String,+ Number,+ RegExp,+ createLogger: () => ({ warn() {}, info() {}, error() {} }),+ t: (key: string) => ({+ 'conversation_info.status.pending': 'Pending',+ 'conversation_info.status.in_progress': 'Running',+ 'conversation_info.status.done': 'Done',+ 'chat.recipient_commander': 'Commander',+ 'chat.from_user': 'User',+ }[key] || key),+ escapeHtml: (s: unknown) => String(s ?? '').replace(/[&<>"]/g, (c) => ({+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ }[c] || c)),+ conversations: [{ conversation_id: 'c1', title: 'Current title' }],+ apiFetch: async (url: string) => ({+ json: async () => {+ if (url.includes('/history')) return { ok: true, conversation: { title: 'Current title' }, history: snapshot.history };+ if (url.includes('/plan')) return { ok: true, plan: snapshot.plan };+ if (url.includes('/members')) return { ok: true, actors: snapshot.members };+ if (url.includes('/attachments')) return { ok: true, items: [] };+ return { ok: false, error: 'unknown' };+ },+ }),+ document: {+ readyState: 'complete',+ getElementById: getEl,+ querySelectorAll: () => [],+ addEventListener() {},+ },+ window: {+ addEventListener() {},+ uiIconHtml: (name: string) => `[${name}]`,+ fileKindIconHtml: () => '',+ },+ };+ context.window.window = context.window;+ vm.createContext(context);+ const source = fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/conversation-info.js'), 'utf8');+ vm.runInContext(source, context);+ context.window.ConversationInfo.bind('c1');+ getEl('conversation-info-toggle').onclick();+ return new Promise((resolve) => setTimeout(() => resolve(getEl('conversation-info-body').innerHTML), 0));+}++function statusTexts(html: string): string[] {+ return Array.from(html.matchAll(/conversation-info-status[^>]*>([^<]+)/g)).map((m) => m[1]);+}++function renderFilesHtml(snapshot: {+ history: any[];+ plan?: any;+ files: any;+}): Promise<string> {+ const elements = new Map<string, any>();+ const getEl = (id: string) => {+ if (!elements.has(id)) {+ elements.set(id, {+ id,+ hidden: false,+ innerHTML: '',+ dataset: {},+ classList: { toggle() {}, add() {}, remove() {} },+ setAttribute() {},+ addEventListener(type: string, fn: () => void) { this[`on${type}`] = fn; },+ });+ }+ return elements.get(id);+ };+ const tabs = [+ { dataset: { infoTab: 'tasks' }, classList: { toggle() {} }, addEventListener(type: string, fn: () => void) { (this as any)[`on${type}`] = fn; } },+ { dataset: { infoTab: 'files' }, classList: { toggle() {} }, addEventListener(type: string, fn: () => void) { (this as any)[`on${type}`] = fn; } },+ { dataset: { infoTab: 'attachments' }, classList: { toggle() {} }, addEventListener(type: string, fn: () => void) { (this as any)[`on${type}`] = fn; } },+ ];++ const context: any = {+ console,+ setTimeout,+ clearTimeout,+ encodeURIComponent,+ Date,+ Map,+ Array,+ String,+ Number,+ RegExp,+ createLogger: () => ({ warn() {}, info() {}, error() {} }),+ t: (key: string) => key,+ escapeHtml: (s: unknown) => String(s ?? '').replace(/[&<>"]/g, (c) => ({+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ }[c] || c)),+ conversations: [{ conversation_id: 'c1', title: 'Current title' }],+ apiFetch: async (url: string) => ({+ json: async () => {+ if (url.includes('/history')) return { ok: true, conversation: { title: 'Current title' }, history: snapshot.history };+ if (url.includes('/plan')) return { ok: true, plan: snapshot.plan || null };+ if (url.includes('/members')) return { ok: true, actors: [] };+ if (url.includes('/files')) return { ok: true, ...snapshot.files };+ if (url.includes('/attachments')) return { ok: true, items: [] };+ return { ok: false, error: 'unknown' };+ },+ }),+ document: {+ readyState: 'complete',+ getElementById: getEl,+ querySelectorAll: () => tabs,+ addEventListener() {},+ },+ window: {+ addEventListener() {},+ uiIconHtml: (name: string) => `[${name}]`,+ fileKindIconHtml: () => '',+ },+ };+ context.window.window = context.window;+ vm.createContext(context);+ const source = fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/conversation-info.js'), 'utf8');+ vm.runInContext(source, context);+ context.window.ConversationInfo.bind('c1');+ (tabs[1] as any).onclick();+ getEl('conversation-info-toggle').onclick();+ return new Promise((resolve) => setTimeout(() => resolve(getEl('conversation-info-body').innerHTML), 0));+}++describe('ConversationInfo task status recovery', () => {+ it('infers completed statuses for older plan-announcement cards after a re-plan', async () => {+ const history = [+ { id: 'u1', from: 'user', text: 'old request' },+ {+ id: 'p1',+ from: 'commander',+ to: ['user'],+ plan_announcement: true,+ ts: '2026-01-01T00:00:00',+ text: 'Plan\n\n1. Collect candidates(@Researcher)\n2. Analyze candidates(@Analyst)\n3. Summarize(我自己)',+ },+ { id: 'd1', from: 'commander', to: ['a1'], dispatch: true, text: '@Researcher go' },+ { id: 'd2', from: 'commander', to: ['a2'], dispatch: true, text: '@Analyst go' },+ { id: 'a1out', from: 'a1', to: ['user'], text: 'collected' },+ { id: 'a2out', from: 'a2', to: ['user'], text: 'analyzed' },+ { id: 'cmdout', from: 'commander', to: ['user'], text: 'summary' },+ { id: 'u2', from: 'user', text: 'new request' },+ {+ id: 'p2',+ from: 'commander',+ to: ['user'],+ plan_announcement: true,+ ts: '2026-01-02T00:00:00',+ text: 'Plan\n\n1. New first(我自己)\n2. New second(@Analyst)',+ },+ ];+ const plan = {+ initial_message: 'new request',+ updated_at: '2026-01-02T00:10:00',+ steps: [+ { index: 1, title: 'New first', assignee: 'commander', status: 'done' },+ { index: 2, title: 'New second', assignee: 'Analyst', status: 'in_progress' },+ ],+ };+ const members = [+ { id: 'commander', name: 'Commander', kind: 'commander' },+ { id: 'user', name: 'User', kind: 'user' },+ { id: 'a1', name: 'Researcher', kind: 'agent' },+ { id: 'a2', name: 'Analyst', kind: 'agent' },+ ];++ const html = await renderTaskHtml({ history, plan, members });++ expect(statusTexts(html)).toEqual(['Done', 'Running', 'Done', 'Done', 'Done']);+ });+});++describe('ConversationInfo files tab', () => {+ it('renders the live workspace file listing and drops stale produced files under that root', async () => {+ const html = await renderFilesHtml({+ history: [+ { produced: ['/tmp/workspace/deleted.md', '/tmp/outside.md'] },+ ],+ files: {+ root: '/tmp/workspace',+ rootExists: true,+ truncated: false,+ count: 1,+ items: [+ {+ path: '/tmp/workspace/batch/skill_large-batch.md',+ relPath: 'batch/skill_large-batch.md',+ name: 'skill_large-batch.md',+ bytes: 12,+ mtime: 1700000000000,+ },+ ],+ },+ });++ expect(html).toContain('batch');+ expect(html).toContain('skill_large-batch.md');+ expect(html).toContain('/tmp/outside.md');+ expect(html).not.toContain('deleted.md');+ expect(html).toContain('draggable="true"');+ expect(html).not.toMatch(/<details[^>]*\sopen(?:\s|>|=)/);+ });+});diff --git a/test/renderer/strip-structural-blocks.test.ts b/test/renderer/strip-structural-blocks.test.tsindex c284dd45..1078c111 100644--- a/test/renderer/strip-structural-blocks.test.ts+++ b/test/renderer/strip-structural-blocks.test.ts@@ -26,6 +26,15 @@// Mixed: real container + literal mention coexisting in one buffer — only// the real container goes, the literal mention stays put.//+// Note on ```xml fences: starting `bc6e0156`, ```xml is treated as a+// **structural** fence (its body IS the LLM's actual tag emission), not as+// a preservation marker. The earlier set B1 wording "inside a ```xml block+// must be preserved" is intentionally retired — the positive coverage for+// the new semantic lives in the "explicit XML fences are treated as+// structural blocks" describe blocks further down. ```xml as an example+// container preservation marker is not coming back; LLM teaching surfaces+// should use plain ``` for examples.+//// Adding a new guard / branch to any of these strippers? Add a fixture// for the motivating shape AND keep the existing fixtures green. Don't// rely on "I checked it manually" — that's the loop these tests exist@@ -48,6 +57,7 @@ const {_replaceKnownSkillIdsForDisplay,_simplifyKnownSkillFollowPhrasesForDisplay,_normalizeKnownSkillRefsForDisplay,+ _collapseRepeatedStructuralPlaceholders,} = strip as {_splitMarkdownProseCode: (text: string) => Array<{ kind: 'prose' | 'code'; text: string; xmlFence?: boolean }>;_findOuterTagRanges: (text: string, tagName: string) => Array<[number, number]>;@@ -62,6 +72,7 @@ const {_replaceKnownSkillIdsForDisplay: (text: string, skills: Array<{ id: string; name?: string }>) => string;_simplifyKnownSkillFollowPhrasesForDisplay: (text: string, skills: Array<{ id: string; name?: string }>) => string;_normalizeKnownSkillRefsForDisplay: (text: string, skills: Array<{ id: string; name?: string }>) => string;+ _collapseRepeatedStructuralPlaceholders: (buf: string, placeholder: string) => string;};const PH = '⟨PLACEHOLDER⟩';@@ -347,14 +358,15 @@ describe('<agent-input-submission> — explicit XML fences are structural', () =describe('main-chat creation stream stripping', () => {function streamDisplay(buf: string): string {- return _stripSkillCreateContainer(+ const skillPh = '[organizing skill config]';+ return _collapseRepeatedStructuralPlaceholders(_stripSkillCreateContainer(_replaceOuterTagBlocks(- strip._replaceOuterSkillFileBlocks(buf, (path: string) => `\n[writing ${path || 'file'}]\n`),+ strip._replaceOuterSkillFileBlocks(buf, () => `\n${skillPh}\n`),'agent',PH,),- PH,- );+ `\n${skillPh}\n`,+ ), `\n${skillPh}\n`);}it('does not leak skill frontmatter or agent XML while bulk create output streams', () => {@@ -387,7 +399,32 @@ describe('main-chat creation stream stripping', () => {const display = streamDisplay(raw.slice(0, i));expect(display).not.toMatch(/name: leio|description_zh|description_en|把研发工作组织|Organize engineering|# leio-sdlc-adapter|<workflow>|Plandex研发助手/);}- expect(streamDisplay(raw)).toContain('[writing SKILL.md]');+ expect(streamDisplay(raw)).toContain('[organizing skill config]');+ });++ it('shows one skill placeholder for consecutive skill-file blocks', () => {+ const raw = [+ '<skill>',+ '<<<skill-file path=SKILL.md',+ '---',+ 'name: first',+ '>>>',+ '<<<skill-file path=scripts/a.py',+ 'print("a")',+ '>>>',+ '</skill>',+ ].join('\n');+ const display = streamDisplay(raw);+ expect(display.split('[organizing skill config]').length - 1).toBe(1);+ });+});++describe('stream placeholders', () => {+ it('collapses consecutive repeated structural placeholders', () => {+ expect(_collapseRepeatedStructuralPlaceholders(`lead\n${PH}\n\n${PH}\ntrail`, PH))+ .toBe(`lead\n${PH}\ntrail`);+ expect(_collapseRepeatedStructuralPlaceholders(`lead\n${PH}\nkeep\n${PH}`, PH))+ .toBe(`lead\n${PH}\nkeep\n${PH}`);});});@@ -478,6 +515,69 @@ describe('<artifact-result> — explicit XML fences are structural', () => {});});+// `<marketplace-install-result>` — the machine tag the commander composes+// when an install request resolves (accepted / declined / failed). Carried+// in a user message so the next commander turn can read it; stripped from+// the user bubble's display via `_stripUserStructuralBlocksForDisplay`.+// Same whack-a-mole class as `<agent-input-submission>` / `<artifact-result>`+// — added to `_stripSurvivingStructuralBlocks` allow-list in `2f325f90`+// without fixtures, retroactively pinned here. Real shape (from+// `group_chat/index.ts::resolveMarketplaceInstallRequest`):+// `<marketplace-install-result request_id="..." kind="..." id="..." status="..."> body </marketplace-install-result>`+describe('<marketplace-install-result> — set A (real result tags stripped from display)', () => {+ it('A1. result tag with the 4 standard attributes + body', () => {+ const buf = 'Confirming install:\n\n<marketplace-install-result request_id="r-1" kind="agent" id="abcd1234" status="accepted">\nuser approved\n</marketplace-install-result>';+ expect(_stripOuterTagBlocks(buf, 'marketplace-install-result')).toBe('Confirming install:\n\n');+ });++ it('A2. body contains backticks / angle brackets — still atomic', () => {+ const buf = 'pre\n\n<marketplace-install-result request_id="r" kind="skill" id="x" status="declined">\nreason: user said "use `<existing>` instead"\n</marketplace-install-result>\npost';+ const out = _stripOuterTagBlocks(buf, 'marketplace-install-result');+ expect(out).not.toContain('marketplace-install-result');+ expect(out).not.toContain('`<existing>`');+ expect(out).toBe('pre\n\n\npost');+ });+});++describe('<marketplace-install-result> — set B (literal mentions survive)', () => {+ it('B1. inside a fenced non-XML code block (e.g. docs quoting the protocol)', () => {+ const buf = 'Wire format:\n```\n<marketplace-install-result request_id="X" kind="agent" id="Y" status="accepted">\n...\n</marketplace-install-result>\n```';+ expect(_stripOuterTagBlocks(buf, 'marketplace-install-result')).toBe(buf);+ });++ it('B2. inside an inline backtick span', () => {+ const buf = 'The commander posts a `<marketplace-install-result ...>` tag when the install resolves.';+ expect(_stripOuterTagBlocks(buf, 'marketplace-install-result')).toBe(buf);+ });++ it('B3. UNCLOSED inline backtick (mid-stream code-explanation)', () => {+ const buf = 'see `<marketplace-install-result';+ expect(_stripOuterTagBlocks(buf, 'marketplace-install-result')).toBe(buf);+ });+});++describe('<marketplace-install-result> — explicit XML fences are structural', () => {+ it('strips a result block inside ```xml (parity with <artifact-result>)', () => {+ const buf = 'Reply:\n```xml\n<marketplace-install-result request_id="X" kind="agent" id="Y" status="accepted">\nok\n</marketplace-install-result>\n```';+ expect(_stripOuterTagBlocks(buf, 'marketplace-install-result')).toBe('Reply:\n```xml\n\n```');+ });+});++describe('<marketplace-install-result> — round-trip through the two strip callers', () => {+ it('_stripSurvivingStructuralBlocks removes assistant-text hallucinations of the tag', () => {+ const buf = 'Sure, here is the install reply you asked for: <marketplace-install-result request_id="r" kind="skill" id="x" status="accepted">echo</marketplace-install-result> done.';+ const out = _stripSurvivingStructuralBlocks(buf);+ expect(out).not.toContain('marketplace-install-result');+ expect(out).toContain('Sure, here is the install reply you asked for:');+ expect(out).toContain('done.');+ });++ it('_stripUserStructuralBlocksForDisplay removes the user-emitted tag from the bubble', () => {+ const buf = 'I accept.\n\n<marketplace-install-result request_id="r" kind="agent" id="x" status="accepted">ok</marketplace-install-result>';+ expect(_stripUserStructuralBlocksForDisplay(buf)).toBe('I accept.');+ });+});+// --- Boundary check: tagName lookup must not bleed across siblings -------describe('boundary check — `<agent>` lookup must not match `<agent-input-form>`', () => {