Skip to content

armgit / Orkas

Public Imported from GitHub
0

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

feat(chat picker for skills + connectors + agent enabled_connectors + signals polish)

wytf1071fd945ae
diff --git a/CLAUDE.md b/CLAUDE.md
index c67ecb23..4d889d37 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -87,7 +87,7 @@ Exception: env-var names with the project prefix (`ORKAS_NODE` / `ORKAS_PC_DIR`)
**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 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. **When changing authoring semantics**: update `agent-creator/SKILL.md` or `skill-creator/SKILL.md` in your local install and republish through the marketplace upload flow; `grep -E "<agent>|<<<skill-file>>>|agent-creator|skill-creator" src/main/prompts/*.md` to confirm the four chat prompts still just point at the skill (no copy-back drift). The loader does not do template composition (only `$variable` substitution), so the on-demand read is the natural sync mechanism — every fresh authoring session re-reads the skill body.
+**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.
@@ -150,6 +150,8 @@ 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 / 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).
+
**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.
**User-account login (Google / Apple OAuth)** — all main-side code lives under `features/account/`, all renderer UI under `renderer/views/login/`; `index.ts` only hooks `account.registerProtocol()` + `account.bootstrap()`. Login state is a single sliding `SessionMgr` session — **no separate access/refresh token, no client-side refresh**: the provider handshake (`/account/oauth/{start,callback}` → one-time `exchange_code` → `/account/oauth/exchange`) returns `{user_id, session_id, user_info, subscription}` (subscription added by the membership-and-billing batch — see Server/docs/plans/membership-and-billing.md), and `user_id` + `session_id` (+ the cached `user_info` profile + `subscription` snapshot) are persisted **plaintext** to `<uid>/local/config/account.json` — same convention as `auth-profiles.json` and the rest of `<uid>/local/config/` (machine-private, never synced; protected by filesystem permissions, not in-file encryption). Authenticated requests carry `user_id` + `session_id` headers; the server renews the session on each one. At boot, a stored session → optimistic status `ready` from the disk cache immediately (no network wait), then one background authed call (`GET /account/me`, replacing the older `POST /account/points`) re-validates it AND refreshes the user_info + subscription snapshot in one round trip — a 401 there flips to `needed` and re-shows the login gate; a transient failure keeps the optimistic `ready`. **This whole feature — `features/account/`, `ipc/account.ts`, `views/login/`, the `window.orkas.account` namespace + `account:changed` push, the `orkas://` scheme, the `account.*` i18n keys, the `#settings-account-group` + `#settings-subscription-group` blocks — is stripped from the OrkasOpen build** (open-source client has no account backend); the strip list is single-sourced in `OpenSource/SyncCode/strip-rules.json`.
@@ -219,6 +221,15 @@ Stored at `<uid>/cloud/chat_attachments/<cid>/<file>`, **zero pre-processing**;
`bash / write_file / edit_file / markdown_to_pdf / html_to_pdf / generate_image / create_artifact` share the `localExec.granted` permission gate (grant/revoke from the settings page, re-read on every `execute()` so it takes effect mid-conversation); unauthorized → `isError=true`. `web_search` goes through `searchProfiles[0]` → paid API → fallback built-in. Outputs are collected via `ChatOptions.onFileWritten` (also fires for `edit_file` so in-place modifications surface as green chips); the renderer shows green chips → IPC `workspace.revealPath` (strictly validated to stay inside the workspace). See `model/core-agent/{local-tools, image-gen-tool, search-tools}.ts`.
+### Structured-output rendering — three layers
+
+Three orthogonal carriers for agent output, ordered by weight:
+1. **Markdown** (default) — `renderMarkdown` in `src/renderer/modules/utils.js` (PC + iOS copy share the same renderer).
+2. **`:::dashboard` directive** — fenced JSON component tree parsed in-place by `renderDashboard` in the same file. ~12 components (Stack / Grid / Card / Separator / Metric / Chart / Table / Alert / Timeline / Code / Markdown / Image). **Renderer-level only — no tool plumbing**, the directive lives next to `:::chart-bar`. Schema reference for the LLM is inline in `prompts/chat_shared_rules.md` "Output formats"; adding a component or enum value requires updating both the renderer switch AND the shared-rules schema in the same patch. Fixture coverage: `test/renderer/utils-dashboard.test.ts` (per PC/CLAUDE.md §9 LLM-output text munging rule). **iOS works the same** — `:::dashboard` is pure renderer code; no `chat-app://` dependency.
+3. **`create_artifact`** — multi-file web-app artifact (heavy; see below). Use when behavior actually matters (forms / dynamic charts / interactive pages); static structured snapshots stay in `:::dashboard`.
+
+**Per-agent output-format preference**: `Agent.output_format` — three user-facing values, progressive capability disclosure: `'markdown_only'` (blocks `:::dashboard` + `create_artifact`; create-modal default for new agents); `'dashboard'` (allows `:::dashboard`, still blocks `create_artifact`); `'artifact'` (allows both). Two legacy on-disk values accepted as aliases by `bus.ts::buildOutputFormatHint`: `'allow_artifacts'` is the pre-rename `'artifact'`; `'auto'` is the pre-redesign default and maps to an empty hint. Missing field = same as `'auto'` (empty hint, no constraint) — agents authored before the redesign keep unconstrained behavior until the user explicitly picks a value, at which point `agents.update({ output_format })` persists the choice. Authored via the create modal (`modules/agents.js::_mountAgentOutputFormatCreateSelect`, default `markdown_only`) and the detail dropdown (`_renderAgentOutputFormatSection`, same 3-option set plus legacy-value mapping), NOT by the agent-edit LLM. Injected into the worker prompt's `## Runtime injection` tail. **Don't** move the injection point into the static prompt prefix (volatile field discipline, §3) — keep `'auto'` / missing producing an empty string so the cache prefix stays stable for unconstrained agents.
+
### Interactive web-app artifacts (`create_artifact` + `chat-app://`)
`create_artifact({title, files:[{path,content,encoding?}]})` writes a self-contained multi-file web app into `<uid>/cloud/chat_artifacts/<cid>/<artifactId>/` (the **only** place artifact files live; `features/chat_artifacts.ts` validates the set — must include a top-level `index.html`, ≤20 files / 256 KB·file / 1 MB total, served-extension allowlist, base64 for binary). The renderer embeds it as a sandboxed `<iframe>` (`sandbox="allow-scripts allow-same-origin allow-forms"`, cross-origin to the renderer so `parent.*` is blocked by SOP) at the bottom of the assistant bubble (`modules/chat-artifact.js`); the card header also has an "open in browser" button → `conversations.artifacts.openExternal` IPC → `shell.openPath(<artifactDir>/index.html)` (a `file://` view, so the `__orkas/bridge.js` virtual path and cross-origin sibling `fetch` don't work there — the iframe stays the primary surface; the path is still routed through `chatArtifacts.resolveArtifactFilePath`). It's served read-only by the privileged `chat-app://cid/<encCid>/<encArtifactId>/<relpath>` protocol handler in `index.ts` (every request → `chatArtifacts.resolveArtifactFilePath`, same traversal guards as `resolveAttachmentAbsPath`; reserved virtual path `__orkas/bridge.js` → in-memory `BRIDGE_JS`). The **only** artifact→app channel is `postMessage({__orkasArtifact:true, type:'submit'|'resize'|'open-external', ...}, '*')`, which the renderer validates by `event.source` identity (not origin string) before composing a `@`-routed user message (`<artifact-result artifact_id agent_id>` tag, stripped from display, opaque to bus). Never inject `window.orkas` or any privileged handle into the iframe. Flow: `create_artifact` fires `LocalToolsOpts.onArtifactCreated` → `bus.ts::runTurn` collects per-turn + attaches `GroupMessage.artifacts[{id,title,agent_id}]` on the end-of-turn enqueue (`agent_id` = the producing actor, the result-routing target); `chats.deleteConversation → chatArtifacts.purgeByCid`. `create_artifact` is only offered when the runner has both `cid` and an `onArtifactCreated` sink (group chat) — edit chats / ad-hoc runs don't get it. Orphaned artifact dirs (single-message edit/delete) are not GC'd yet.
@@ -233,7 +244,7 @@ The artifact card's header collapses into one `⋯` popover: **reload** / **open
Sources = `<uid>/cloud/skills/` (custom, cloud-synced) + `<uid>/local/marketplace/skills/` (platform, per-machine; reconciled from the cloud-synced `<uid>/cloud/marketplace/installs.json` manifest — see §4 constraint 2). `SkillLoader` scans `[custom, platform]` and injects them into the system prompt; **custom takes precedence over a platform install with the same id**. The same per-machine + cloud-manifest split applies to agents (`<uid>/local/marketplace/agents/<id>/agent.json`). `category` is part of the spec itself (SKILL.md frontmatter / agent.json field) — same shape as custom; downstream readers (`listAgents` / `listSkills`) read it from one place. **Why:** earlier the dev upload tool didn't write category back into the spec, so platform installs lacked the field on disk; that's been fixed (`marketplace_dev.ts::uploadCustom*` rewrites the spec before zipping). `version` and `published_at` stay in `_install.json` + `installs.json` — they are install-state metadata, not spec content.
-**Authoring rules are themselves platform skills** (installed from the marketplace under `agent-creator` / `skill-creator` ids): they carry the canonical authoring rules for `<agent>` and `<skill>` containers. The four chat prompts (`chat_commander.md` + the three inline edit chats) point at them via `read_file <ROOT>/agent-creator/SKILL.md`. When changing authoring semantics — field shapes, validation rules, similarity-check protocol, edit-loop, prose forbidden words — update **only** the matching `*-creator/SKILL.md` and republish through the marketplace upload flow; the chat prompts already reference it on demand. See §3 "Authoring rules live in builtin skills" for the cross-prompt sync convention.
+**Authoring rules are themselves platform skills** (installed from the marketplace under `agent-creator` / `skill-creator` ids): they carry the canonical authoring rules for `<agent>` and `<skill>` containers. The four chat prompts (`chat_commander.md` + the three inline edit chats) point at them via `read_file <ROOT>/agent-creator/SKILL.md`. When changing authoring semantics — field shapes, validation rules, category candidates, similarity-check protocol, edit-loop, prose forbidden words — update the matching `*-creator/SKILL.md` and republish through the marketplace upload flow. See §3 "Authoring rules live in builtin skills" for the cross-prompt sync convention.
**Dev-mode only**: platform skills + agents become editable through the existing inline edit chat (the `source !== 'custom'` guard is lifted when `false`); the ⋯ menu also exposes "delete" and "promote to platform" entries. Writes target the local install dir (`<uid>/local/marketplace/{agents,skills}/<id>/`) only — there is no shipped src tree to dual-write into. Server-side publishing is a separate flow through `marketplace_dev.upload*`. Two-layer protection: (1) runtime `false` gate on every entry; (2) physical exclusion at packaging time via `package.json::build.files` `!src/main/features/*_dev.ts` + `!src/main/ipc/dev_handlers.ts` (the dev modules are never present in asar). The setup prompt for platform editing uses `i18n.ts::buildBuiltinEditingConstraint()` (English-only output except `description_zh`) instead of the user-language directive — see §3.
@@ -241,7 +252,7 @@ Sources = `<uid>/cloud/skills/` (custom, cloud-synced) + `<uid>/local/marketplac
**Exception: `description` must be bilingual** — SKILL.md frontmatter uses both `description_zh` + `description_en` (the legacy single `description` field is migrated by CJK heuristic in the loader / normalizeAgent buckets, but **new entries always use both fields**); agent spec JSON likewise uses `description_zh` + `description_en`. **Why:** the description is the selection signal seen by the commander / main-conversation LLM (`chat_commander.md:91/96/325`); built-in skills / agents are distributed globally, and an English-only description means a Chinese UI user sees an English description in the list, leading to mis-matches. At runtime, `getSystemPromptBlock` / `_buildAgentsIndexBlock` / UI rendering all pick the right one based on `getCurrentLang()` (the `pickDescription` resolver lives in core-agent + renderer utils, kept in sync). **Pre-translated, not at runtime** — description quality must be controllable, and runtime translation has both quality variance and latency cost.
-**SKILL.md frontmatter — allowed fields**: `name` / `description_zh` / `description_en` / `category` (legacy single `description` is migrated by CJK heuristic in the loader). **No** `requires` / `external_deps` / `tags` / `version` / any other field. Skills have no hard inter-dependencies (no transitive closure, no cross-skill writes); external deps are stated in the body's "External dependencies" section as plain text — runtime does not pre-check or auto-install. **`category`** holds a marketplace category code (`marketplace_categories.code` — `education` / `ecommerce` / `rnd` / `writing` / `data` / `general`); required for marketplace publication, optional for user-created skills (defaults to empty string = "uncategorized" in `listSkills` output). The `_install.json` sidecar at the root of a platform-installed skill (`{version, published_at}`) is NOT consumed by SKILL parsing — it's read only by `marketplace_reconcile` to detect manifest/disk drift; `skills.ts::IMPORT_FILTER_NAMES` filters it (plus the legacy clawhub `_meta.json`) on import.
+**SKILL.md frontmatter — allowed fields**: `name` / `description_zh` / `description_en` / `category` (legacy single `description` is migrated by CJK heuristic in the loader). **No** `requires` / `external_deps` / `tags` / `version` / any other field. Skills have no hard inter-dependencies (no transitive closure, no cross-skill writes); external deps are stated in the body's "External dependencies" section as plain text — runtime does not pre-check or auto-install. **`category`** holds a marketplace category code; the current candidate list is authored in `agent-creator` / `skill-creator`, not in the chat prompt shells. Model-authored agent/skill create or SKILL.md rewrite should choose exactly one current code; missing/unsafe values are repaired to the default category instead of blocking the whole write. Legacy/manual specs without it still load as empty string = "uncategorized" in `listSkills` / `listAgents`. The `_install.json` sidecar at the root of a platform-installed skill (`{version, published_at}`) is NOT consumed by SKILL parsing — it's read only by `marketplace_reconcile` to detect manifest/disk drift; `skills.ts::IMPORT_FILTER_NAMES` filters it (plus the legacy clawhub `_meta.json`) on import.
**id ≠ name (loader decouples them)**: `SkillSpec.id = path.basename(dir)` (always the directory name, used as the `read_file <ROOT>/<id>/SKILL.md` path component); `SkillSpec.name = frontmatter name || id` (display label, what the LLM picks from). For **custom** skills they happen to coincide (`features/skills.ts::createCustomSkill` keeps `dir name = frontmatter name`). For **marketplace installs** they diverge — dir is the 12-hex `server_id` (catalog uniqueness), name is the authored human label. **Why:** allows multi-author same-name uploads (server dedup on `(name, create_uid)`); LLM still picks by readable name, reads by id. `skill-registry::renderSkillLines` emits both forms — `**<name>** (id: <id>)` when they differ, `**<id>**` when they don't — and the prompt warning line spells out "use `<id>` in the path even when it differs from the display name". Do NOT re-couple them in the loader (the early invariant was a mistake fixed 2026-05-12).
@@ -337,7 +348,7 @@ Vanilla HTML/CSS/JS, classic `<script>` multi-file (no ESM, no build). Cross-fil
**Key constraints**:
- Adding a new file → also insert it into `index.html`'s `<script>` list (most additions go after `ipc-shim`).
- Adding `window.orkas.*` API → must add a handler in `ipc/index.ts`; new `/api/*` → only added to `modules/ipc-shim.js::_IPC_ROUTES` (no real HTTP).
-- Markdown rendering has a single interface, `renderMarkdown(str)` (`modules/utils.js`); **don't write a "lite version"**. LaTeX is typeset asynchronously by `modules/math.js::typesetMath`; **no typesetting of streaming deltas** (avoids half-formed LaTeX flickering). Placeholder/regex specifics live in those two files' headers.
+- Markdown rendering has a single interface, `renderMarkdown(str)` (`modules/utils.js`); **don't write a "lite version"**. LaTeX is typeset asynchronously by `modules/math.js::typesetMath`; **no typesetting of streaming deltas** (avoids half-formed LaTeX flickering). The same file carries the `:::dashboard` directive renderer (`renderDashboard` + ~12 components) — same fenced-directive shape as `:::chart-bar`; never fork either into a parallel implementation. Placeholder/regex specifics live in those two files' headers; component schema reference lives in `prompts/chat_shared_rules.md` "Output formats" (renderer + schema must change together).
- `index.html` resources **don't carry `?v=`**: dev `Cmd/Ctrl+R` goes through `reloadIgnoringCache()`; reload is disabled in prod.
- `src/renderer/` **does not participate in typecheck** (vanilla + DOM gives too many checkJs false positives); main/ stays at `checkJs: true`.
- Renderer icons MUST be inline SVG centralized in the single platform icon module `modules/icons.js` (both UI chrome and file-type icons live there). **Do not hardcode SVG paths at call sites, and do not use emoji as icons** in HTML, JS-rendered controls, process rows, plan rails, menus, or locale strings. Plain shortcut text such as `Ctrl+K` is fine; if a reusable UI/file symbol is used as an icon, add/reuse a named SVG in `modules/icons.js` and render it via the helper or `data-ui-icon`.
@@ -488,6 +499,8 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t
- Wire the rail's "重试" button to "send the user message again" — that double-writes user history; the action must go through the dedicated IPC (`groupChat.retryStep`) which only mutates plan state.
- Add `aborted` / `cancelled` / `Run aborted` to `TRANSIENT_ERR_PATTERNS` — silently retrying user-initiated abort is the wrong behavior. Net new patterns must come from the network layer (undici / fetch / DNS / socket), not from intent layers.
- Duplicate the plan rail status icon set (`plan-rail.js::STATUS_ICON`) into prompts / locales / backend. Single source of truth; downstream surfaces just read the rendered output.
+- Call `features/expert_signals/emitSignal` from anywhere but the chokepoints listed in §4 constraint 9 (bus.ts turn-end / `_enqueueBody` USER_ID branch / retryStep / skipStep / markFormSubmittedAndDispatch / plan_executor.dispatchReady). New signal kinds extend the extractor registry; never spread emit calls across `features/*`. **`model/` layer never imports `emitSignal`** — surface a `ChatOptions` callback instead (e.g. `onSkillAdvertised` / `onSkillInvoked` are bridged by `bus.ts` into the per-turn buffer drained at turn-end, per §4 constraint 9). Reusing the callback pattern matches existing `onFileWritten` / `onArtifactCreated` / `onSkillCreated` plumbing.
+- Reintroduce a synthetic `turn_id` for retry/skip (the old `<cid>:plan:<step>` shape) "so multiple retries on the same step share an id". Same-step retry grouping goes via `metadata.step_index`; sharing `turn_id` blocks the retry × skill_invoked / tool_failure JOIN that quality-setup §5 needs and is the bug `expert-signals-skill-attribution.md` was written to fix.
---
diff --git a/scripts/observe-skill-attribution.sh b/scripts/observe-skill-attribution.sh
new file mode 100755
index 00000000..52fa42d0
--- /dev/null
+++ b/scripts/observe-skill-attribution.sh
@@ -0,0 +1,143 @@
+#!/usr/bin/env bash
+# observe-skill-attribution.sh
+#
+# One-shot e2e verifier for the skill-attribution signals
+# (skill_advertised / skill_invoked / agent_dispatched + the turn_id JOIN
+# guarantee from docs/plans/expert-signals-skill-attribution.md §3.4).
+#
+# Usage:
+# PC/scripts/observe-skill-attribution.sh [<expected-skill-id>] [<timeout-seconds>]
+#
+# Defaults: skill_id = e2e-test-skill, timeout = 180s.
+# Exits 0 on PASS (both expected signals seen with matching turn_id),
+# 1 on FAIL (timeout / mismatch). Designed for manual run: print every
+# matched signal as it lands so the operator can see the wire is alive.
+#
+# Requires: jq. macOS / Linux. Reads $ORKAS_DATA_ROOT or defaults to
+# ~/.orkas/data.
+
+set -u
+
+EXPECTED_SKILL="${1:-e2e-test-skill}"
+TIMEOUT_SEC="${2:-180}"
+DATA="${ORKAS_DATA_ROOT:-$HOME/.orkas/data}"
+
+if ! command -v jq >/dev/null 2>&1; then
+ echo "❌ jq not on PATH — install jq first." >&2
+ exit 2
+fi
+
+USERS_FILE="$DATA/users.json"
+if [[ ! -f "$USERS_FILE" ]]; then
+ echo "❌ users.json not found at $USERS_FILE — is the app installed?" >&2
+ exit 2
+fi
+
+UID_VAL=$(jq -r .current_user_id "$USERS_FILE")
+TODAY=$(date +%Y-%m-%d)
+SIGFILE="$DATA/$UID_VAL/local/signals/$TODAY.jsonl"
+
+mkdir -p "$(dirname "$SIGFILE")"
+touch "$SIGFILE"
+
+# Snapshot current line count so we ignore historical signals — `tail -n +N`
+# starts streaming from line N, so we want the next-after-current line.
+BASELINE=$(wc -l < "$SIGFILE" | tr -d ' ')
+NEXT_LINE=$((BASELINE + 1))
+
+echo "──────────────────────────────────────────────────────────"
+echo "Skill attribution e2e watch"
+echo " uid: $UID_VAL"
+echo " sigfile: $SIGFILE"
+echo " baseline lines: $BASELINE (will read from line $NEXT_LINE)"
+echo " expected skill: $EXPECTED_SKILL"
+echo " timeout: ${TIMEOUT_SEC}s"
+echo "──────────────────────────────────────────────────────────"
+echo "→ Send your test message in the app now."
+echo
+
+# State accumulated across the stream.
+ADVERTISED_TURN="" # turn_id of the skill_advertised matching EXPECTED
+INVOKED_TURN="" # turn_id of the skill_invoked matching EXPECTED
+
+# Pure polling — no tail / FIFO. macOS tail's `-n +N` + `-F` interaction is
+# unreliable when N is past EOF (BSD tail exits instantly), and even when
+# it works the FIFO + fd-3 dance has multiple race-condition tripwires.
+# `wc -l` + `sed -n A,B p` against an append-only jsonl is straightforward.
+LAST_LINE=$BASELINE
+DEADLINE=$(( $(date +%s) + TIMEOUT_SEC ))
+
+process_line() {
+ local line="$1"
+ [[ -z "$line" ]] && return
+ local type
+ type=$(jq -r 'try .type catch ""' <<<"$line" 2>/dev/null || echo "")
+ case "$type" in
+ skill_advertised|skill_invoked|agent_dispatched)
+ jq -c '{type, turn_id, aid, delta}' <<<"$line"
+ ;;
+ *)
+ return
+ ;;
+ esac
+
+ case "$type" in
+ skill_advertised)
+ if jq -e --arg id "$EXPECTED_SKILL" \
+ '.delta.skill_ids // [] | any(. == $id)' <<<"$line" >/dev/null; then
+ ADVERTISED_TURN=$(jq -r .turn_id <<<"$line")
+ echo " ✓ advertised matched on turn_id=$ADVERTISED_TURN"
+ fi
+ ;;
+ skill_invoked)
+ if jq -e --arg id "$EXPECTED_SKILL" \
+ '.delta.skill_id == $id' <<<"$line" >/dev/null; then
+ INVOKED_TURN=$(jq -r .turn_id <<<"$line")
+ echo " ✓ invoked matched on turn_id=$INVOKED_TURN"
+ fi
+ ;;
+ esac
+}
+
+while (( $(date +%s) < DEADLINE )); do
+ CUR_LINE=$(wc -l < "$SIGFILE" 2>/dev/null | tr -d ' ')
+ CUR_LINE=${CUR_LINE:-0}
+ if (( CUR_LINE > LAST_LINE )); then
+ # Read only the new slice into the loop. `< <(sed …)` is a process
+ # substitution so the variable assignments inside survive (a piped
+ # `sed | while` would run the loop in a subshell and discard them).
+ while IFS= read -r batched_line; do
+ process_line "$batched_line"
+ # PASS condition: both seen on the SAME turn_id. This proves the
+ # JOIN guarantee (plan §3.4): advertising + invocation come from the
+ # same agent turn, so the patch suggester can group-by turn_id and
+ # correctly attribute the LLM's behaviour.
+ if [[ -n "$ADVERTISED_TURN" && -n "$INVOKED_TURN" ]]; then
+ if [[ "$ADVERTISED_TURN" == "$INVOKED_TURN" ]]; then
+ echo
+ echo "✅ PASS — both signals on turn_id=$ADVERTISED_TURN"
+ echo " • skill_advertised system=A.custom contains '$EXPECTED_SKILL'"
+ echo " • skill_invoked system=A.custom skill_id='$EXPECTED_SKILL'"
+ echo " • turn_id matches → cross-signal JOIN works."
+ exit 0
+ else
+ echo
+ echo "❌ FAIL — turn_id mismatch."
+ echo " advertised.turn_id = $ADVERTISED_TURN"
+ echo " invoked.turn_id = $INVOKED_TURN"
+ echo " Possible cause: buffer drained twice, or drain ran on the"
+ echo " wrong actor's msg id (check bus.ts persistedMsg capture)."
+ exit 1
+ fi
+ fi
+ done < <(sed -n "$((LAST_LINE + 1)),${CUR_LINE}p" "$SIGFILE")
+ LAST_LINE=$CUR_LINE
+ fi
+ sleep 0.5
+done
+
+echo
+echo "❌ TIMEOUT — neither expected signal arrived in ${TIMEOUT_SEC}s."
+[[ -n "$ADVERTISED_TURN" ]] && echo " (saw advertised, missing invoked)"
+[[ -n "$INVOKED_TURN" ]] && echo " (saw invoked, missing advertised)"
+exit 1
diff --git a/scripts/watch-signals.sh b/scripts/watch-signals.sh
new file mode 100755
index 00000000..b698f6ff
--- /dev/null
+++ b/scripts/watch-signals.sh
@@ -0,0 +1,76 @@
+#!/usr/bin/env bash
+#
+# watch-signals.sh — tail today's expert-signals jsonl in real time.
+#
+# Usage:
+# ./scripts/watch-signals.sh
+# ORKAS_DATA=/custom/path ./scripts/watch-signals.sh
+#
+# Tails `<ORKAS_DATA>/<uid>/local/signals/<yyyy-mm-dd>.jsonl` and pretty-
+# prints each new signal as a compact line. ORKAS_DATA defaults to
+# ~/.orkas/data.
+#
+# Requires: jq (brew install jq | apt install jq).
+
+set -u
+
+DATA_ROOT="${ORKAS_DATA:-$HOME/.orkas/data}"
+USERS_FILE="$DATA_ROOT/users.json"
+
+# ── Preflight ──────────────────────────────────────────────────────────
+if ! command -v jq >/dev/null 2>&1; then
+ echo "ERROR: jq is required. Install it first:" >&2
+ echo " macOS: brew install jq" >&2
+ echo " Linux: apt install jq" >&2
+ exit 1
+fi
+
+if [[ ! -f "$USERS_FILE" ]]; then
+ echo "ERROR: users.json not found at $USERS_FILE" >&2
+ echo " Launch the app at least once, or set ORKAS_DATA=<your data root>." >&2
+ exit 1
+fi
+
+ACTIVE_UID=$(jq -r .current_user_id "$USERS_FILE" 2>/dev/null)
+if [[ -z "$ACTIVE_UID" || "$ACTIVE_UID" == "null" ]]; then
+ echo "ERROR: current_user_id missing in $USERS_FILE" >&2
+ exit 1
+fi
+
+DAY=$(date +%Y-%m-%d)
+SIG_DIR="$DATA_ROOT/$ACTIVE_UID/local/signals"
+SIG_FILE="$SIG_DIR/$DAY.jsonl"
+
+mkdir -p "$SIG_DIR"
+touch "$SIG_FILE"
+
+# ── Header ─────────────────────────────────────────────────────────────
+echo "uid: $ACTIVE_UID"
+echo "signals: $SIG_FILE"
+echo "size: $(wc -c < "$SIG_FILE" | tr -d ' ') bytes"
+echo
+echo "=== streaming new signals (Ctrl+C to stop) ==="
+echo " legend: accept=GREEN correction/reject/tool_failure=RED other=YELLOW"
+echo
+
+# ── Stream + colourize by type ─────────────────────────────────────────
+# `-n 0` skips the existing file content; only NEW lines after script
+# start are printed. Use `tail -F` (capital) to follow rotation if the
+# date rolls over mid-watch.
+tail -F -n 0 "$SIG_FILE" 2>/dev/null | while IFS= read -r line; do
+ # Compact view: time, type, aid (commander when null), turn prefix, metadata
+ pretty=$(printf '%s' "$line" | jq -c '{
+ ts: .ts[11:19],
+ type,
+ aid: (.aid // "commander"),
+ turn: (.turn_id[:12]),
+ meta: (.metadata // {}),
+ }' 2>/dev/null) || pretty="$line"
+
+ case "$(printf '%s' "$line" | jq -r .type 2>/dev/null)" in
+ accept) color="32" ;; # green
+ correction|reject|tool_failure) color="31" ;; # red
+ *) color="33" ;; # yellow
+ esac
+ printf "\033[%sm%s\033[0m\n" "$color" "$pretty"
+done
diff --git a/src/core-agent/src/agent/runner.ts b/src/core-agent/src/agent/runner.ts
index 3b6992c5..60b1eba7 100644
--- a/src/core-agent/src/agent/runner.ts
+++ b/src/core-agent/src/agent/runner.ts
@@ -10,6 +10,7 @@ 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";
@@ -42,6 +43,7 @@ export class AgentRunner {
private readonly skillStore: SkillStore | null;
private readonly skillAllowlist: string[] | undefined;
private readonly onCompact: ((summary: string) => void) | null;
+ private readonly onLearnedSkillAdvertised: ((id: string) => void) | null;
constructor(opts: {
config: CoreAgentConfig;
@@ -55,6 +57,12 @@ export class AgentRunner {
/** Fires after skill_manage(create) with the new skill id — Orkas
* uses this to keep the bound agent's `skill_list` in sync. */
onSkillCreated?: (id: string) => void;
+ /** Fires once per turn for each learned-skill id rendered into the
+ * system-prompt's `## Available Learned Skills` block (System B in
+ * the host's signal-attribution vocabulary). Pure callback — exceptions
+ * are swallowed; emission is best-effort. Orkas bridges this to its
+ * `onSkillAdvertised` ChatOptions hook with `system: 'B'`. */
+ onLearnedSkillAdvertised?: (id: string) => void;
/** Called after session compaction with the generated summary text. */
onCompact?: (summary: string) => void;
}) {
@@ -63,6 +71,7 @@ export class AgentRunner {
this.session = opts.session ?? new Session();
this.onCompact = opts.onCompact ?? null;
this.skillAllowlist = opts.skillAllowlist;
+ this.onLearnedSkillAdvertised = opts.onLearnedSkillAdvertised ?? null;
// Set up evolution / skill store
const evolutionConfig = this.config.evolution;
@@ -516,6 +525,11 @@ export class AgentRunner {
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) {
@@ -523,8 +537,8 @@ export class AgentRunner {
return null;
}
- const metrics = this.buildRunMetrics(result);
- log.debug(`evaluateReflection: metrics toolCalls=${metrics.toolCalls} errors=${metrics.errorCount} errorKind=${metrics.errorKind} transient=${metrics.transientErrorCount} skills=[${metrics.skillsLoaded.join(',')}]`);
+ 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) {
@@ -623,8 +637,11 @@ export class AgentRunner {
return lines.join('\n');
}
- /** Convert AgentRunResult.meta into RunMetrics for the trigger evaluator. */
- private buildRunMetrics(result: AgentRunResult): RunMetrics {
+ /** 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;
@@ -645,7 +662,7 @@ export class AgentRunner {
hadErrors,
recovered: hadErrors && result.text.length > 0,
errorCount: totalToolErrors + (meta.error ? 1 : 0),
- userCorrections: 0,
+ userCorrections: inboundMessage && detectUserCorrection(inboundMessage) ? 1 : 0,
errorKind,
transientErrorCount: transient,
};
@@ -658,6 +675,25 @@ export class AgentRunner {
try {
const skillsIndex = await this.skillStore.buildIndex(this.skillAllowlist);
+ // Signal-attribution hook: re-list to recover the rendered id set.
+ // SkillStore.list() is mtime-cached so this is effectively free; not
+ // worth changing buildIndex's signature. Mirror the same allowlist
+ // filter so the emitted set matches what landed in the prompt.
+ if (skillsIndex && this.onLearnedSkillAdvertised) {
+ try {
+ let advertised = await this.skillStore.list();
+ if (this.skillAllowlist !== undefined) {
+ const allow = new Set(this.skillAllowlist);
+ advertised = advertised.filter((s) => allow.has(s.id));
+ }
+ for (const s of advertised) {
+ try { this.onLearnedSkillAdvertised(s.id); }
+ catch { /* best-effort */ }
+ }
+ } catch (err) {
+ log.warn(`onLearnedSkillAdvertised replay failed: ${formatError(err)}`);
+ }
+ }
const guidance = buildSkillsGuidance(skillsIndex);
return basePrompt + "\n\n" + guidance;
} catch (err) {
diff --git a/src/main/features/agents.ts b/src/main/features/agents.ts
index 8fb1f691..58ab5827 100644
--- a/src/main/features/agents.ts
+++ b/src/main/features/agents.ts
@@ -23,11 +23,15 @@ import {
userAgentsDir, userSkillsDir, userAgentChatDir, userSessionFile, WS_ROOT,
agentDir, agentDefinitionFile,
userMarketplaceAgentsDir, userMarketplaceAgentDir, userMarketplaceSkillsDir,
+ userAgentRuntimeConfigFile,
} from '../paths';
import { evictSession } from '../model/core-agent/session-store';
import { getActiveUserId } from './users';
import { createLogger } from '../logger';
import { t, buildLanguageDirective } from '../i18n';
+import { t, buildLanguageDirective, buildBuiltinEditingConstraint } from '../i18n';
+import { isDevEnv } from './devtools';
+import { getWorkspacePath } from './user_workspace';
const log = createLogger('agents');
@@ -35,16 +39,26 @@ const log = createLogger('agents');
function CUSTOM_AGENTS_DIR(): string { return userAgentsDir(getActiveUserId()); }
function CUSTOM_SKILLS_DIR(): string { return userSkillsDir(getActiveUserId()); }
import { prompts } from '../prompts/loader';
+import { findOuterTagRanges } from '../util/markdown-prose-code';
import {
nowIso, genAgentId, safeId,
readJson, writeJson,
appendJsonlAtomic, invalidateLineCount, readJsonl,
} from '../storage';
-import { listSkillSpecs } from '../model/core-agent/skill-registry';
+import {
+ listSkillSpecs,
+ normalizeKnownSkillRefsForDisplay,
+ resolveSkillAllowlistRefs,
+ type SkillAllowlistRef,
+} from '../model/core-agent/skill-registry';
import { readDisabledSets, setAgentEnabled } from './component_enabled';
import { renameAgentInMembers } from './group_chat/state';
import { validateAgentSpec, ValidationReport as QualityReport } from '../quality';
import { persistReport as persistQualityReport } from '../quality/report';
+import {
+ DEFAULT_MARKETPLACE_CATEGORY_CODE,
+ normalizeMarketplaceCategoryCode,
+} from './marketplace_biz';
export type AgentSource = 'builtin' | 'custom';
@@ -130,9 +144,8 @@ export interface Agent {
* via the dedicated `chat_agent_setup_cli.md` prompt; the LLM
* doesn't author it directly. */
runtime?: AgentRuntime;
- /** Marketplace category code (`education` / `ecommerce` / `rnd` / `writing` / `data` /
- * `general`). Empty string when uncategorized; required only when publishing to the
- * marketplace. Maintained via the create / edit dialog dropdown, NOT by the agent-edit LLM. */
+ /** Marketplace category code. Empty string only for legacy/manual specs.
+ * Maintained by hidden create defaults and by the agent-edit LLM's `<category>` sub-tag. */
category: string;
/** Connector instance ids this agent is allowed to call. Three-state intentionally **diverges**
* from `skill_list`: `undefined` and `[]` both mean "no connectors" (collapsed to empty), only
@@ -140,6 +153,21 @@ export interface Agent {
* connectors carry external side effects (sending emails, editing remote docs); a brand-new
* agent must opt in explicitly. Maintained by the agent edit UI, NOT by the agent-edit LLM. */
enabled_connectors?: string[];
+ /** Output rendering preference — agent-level hint injected into the worker
+ * system prompt at dispatch time. Three user-facing values, progressive
+ * capability disclosure:
+ * - `'markdown_only'`: blocks `:::dashboard` + `create_artifact`. The
+ * create-modal default for new agents.
+ * - `'dashboard'`: allows `:::dashboard` blocks; still blocks `create_artifact`.
+ * - `'artifact'`: allows both `:::dashboard` and `create_artifact`.
+ * Two legacy values kept for back-compat: `'auto'` (pre-redesign default,
+ * empty hint = no constraint) and `'allow_artifacts'` (the old name for
+ * `'artifact'`, treated identically by `bus.ts::buildOutputFormatHint`).
+ * Missing field = no constraint (same as `'auto'`) — old agents authored
+ * before the redesign keep their broad permissions until the user
+ * explicitly picks a value. Authored by the agent edit UI dropdown, NOT
+ * the agent-edit LLM. See `bus.ts::buildOutputFormatHint`. */
+ output_format?: OutputFormat;
source: AgentSource;
created_at: string;
updated_at: string;
@@ -177,8 +205,20 @@ interface AgentRaw {
runtime?: unknown;
category?: unknown;
enabled_connectors?: unknown;
+ output_format?: unknown;
}
+/** Agent output rendering preference. Three user-facing values
+ * (`'markdown_only' | 'dashboard' | 'artifact'`); the create modal defaults
+ * to `'markdown_only'`. Two legacy values are kept in the enum for
+ * on-disk back-compat: `'auto'` (pre-redesign default; missing-field is
+ * still equivalent) and `'allow_artifacts'` (renamed to `'artifact'` — the
+ * hint builder + detail dropdown treat them as the same). Missing field
+ * on disk = no constraint (empty hint), preserving legacy agent behavior
+ * through the redesign. See `Agent.output_format`. */
+export type OutputFormat = 'auto' | 'markdown_only' | 'dashboard' | 'artifact' | 'allow_artifacts';
+const _OUTPUT_FORMAT_VALUES = new Set<OutputFormat>(['auto', 'markdown_only', 'dashboard', 'artifact', 'allow_artifacts']);
+
/** Per-agent execution backend. See `Agent.runtime`. */
export type AgentRuntime =
| { kind: 'in_process' }
@@ -502,6 +542,12 @@ export function normalizeAgent(raw: AgentRaw | null | undefined, source: AgentSo
}
const rt = _normalizeRuntime(raw.runtime);
if (rt) agent.runtime = rt;
+ // output_format: enum-coerce; missing / unknown collapses to "no field
+ // set" (downstream reads default to 'auto'). Only the three known values
+ // round-trip to disk, so a malformed JSON can't inject a fourth state.
+ if (typeof raw.output_format === 'string' && _OUTPUT_FORMAT_VALUES.has(raw.output_format as OutputFormat)) {
+ agent.output_format = raw.output_format as OutputFormat;
+ }
return agent;
}
@@ -543,11 +589,150 @@ export function isCliAgent(agent: Pick<Agent, 'runtime'> | null | undefined): bo
return !!agent && agent.runtime?.kind === 'cli';
}
+interface AgentRuntimeLocalConfig {
+ version: 1;
+ project_dirs: Record<string, { path: string; updated_at?: string }>;
+}
+
+export interface AgentCliProjectDirInfo {
+ agent_id: string;
+ is_coding: boolean;
+ /** `workspace` means no per-agent override; `custom` means the user picked a directory. */
+ mode: 'workspace' | 'custom';
+ /** Display path. For a missing custom dir this remains the selected path. */
+ path: string;
+ /** Actual cwd used by dispatch. Falls back to workspace when a custom dir vanished. */
+ effective_path: string;
+ workspace_path: string;
+ custom_path?: string;
+ exists: boolean;
+}
+
+function _emptyAgentRuntimeConfig(): AgentRuntimeLocalConfig {
+ return { version: 1, project_dirs: {} };
+}
+
+function _readAgentRuntimeConfig(uid: string): AgentRuntimeLocalConfig {
+ const file = userAgentRuntimeConfigFile(uid);
+ try {
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
+ const out = _emptyAgentRuntimeConfig();
+ const dirs = raw && typeof raw === 'object' ? (raw as any).project_dirs : null;
+ if (dirs && typeof dirs === 'object') {
+ for (const [agentId, entry] of Object.entries(dirs)) {
+ if (!safeId(agentId) || !entry || typeof entry !== 'object') continue;
+ const p = typeof (entry as any).path === 'string' ? (entry as any).path.trim() : '';
+ if (!p) continue;
+ out.project_dirs[agentId] = {
+ path: path.resolve(p),
+ ...(typeof (entry as any).updated_at === 'string' ? { updated_at: (entry as any).updated_at } : {}),
+ };
+ }
+ }
+ return out;
+ } catch {
+ return _emptyAgentRuntimeConfig();
+ }
+}
+
+function _writeAgentRuntimeConfig(uid: string, cfg: AgentRuntimeLocalConfig): void {
+ const file = userAgentRuntimeConfigFile(uid);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ const tmp = file + '.tmp';
+ fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2), 'utf8');
+ fs.renameSync(tmp, file);
+}
+
+function _deleteAgentRuntimeConfigEntry(uid: string, agentId: string): void {
+ const cfg = _readAgentRuntimeConfig(uid);
+ if (!Object.prototype.hasOwnProperty.call(cfg.project_dirs, agentId)) return;
+ delete cfg.project_dirs[agentId];
+ _writeAgentRuntimeConfig(uid, cfg);
+}
+
+function _dirExists(dirPath: string): boolean {
+ try { return fs.statSync(dirPath).isDirectory(); }
+ catch { return false; }
+}
+
+/** Resolve the per-agent project directory shown on the detail page and
+ * used to initialise each conversation's coding cwd. Stored overrides are
+ * local-only because absolute paths are machine-specific. Missing config =
+ * effective workspace for the conversation/project scope. */
+export function getCliProjectDirInfoForAgent(
+ userId: string,
+ agent: Pick<Agent, 'agent_id' | 'runtime'>,
+ projectId?: string,
+): AgentCliProjectDirInfo {
+ const workspacePath = getWorkspacePath(userId, projectId);
+ const cli = agent.runtime?.kind === 'cli' ? agent.runtime.cli : '';
+ const isCoding = cliIsCodingAgent(cli);
+ const entry = isCoding ? _readAgentRuntimeConfig(userId).project_dirs[agent.agent_id] : undefined;
+ const customPath = entry?.path ? path.resolve(entry.path) : '';
+ const customExists = !!customPath && _dirExists(customPath);
+ return {
+ agent_id: agent.agent_id,
+ is_coding: isCoding,
+ mode: customPath ? 'custom' : 'workspace',
+ path: customPath || workspacePath,
+ effective_path: customExists ? customPath : workspacePath,
+ workspace_path: workspacePath,
+ ...(customPath ? { custom_path: customPath } : {}),
+ exists: customPath ? customExists : true,
+ };
+}
+
+export async function getAgentCliProjectDirInfo(
+ userId: string,
+ agentId: string,
+ projectId?: string,
+): Promise<AgentCliProjectDirInfo | null> {
+ if (!safeId(agentId)) return null;
+ const agent = await getAgent(agentId);
+ if (!agent) return null;
+ return getCliProjectDirInfoForAgent(userId, agent, projectId);
+}
+
+/** Set or clear the detail-page project directory for an external coding
+ * agent. `dirPath=''` clears the override and returns to workspace mode. */
+export async function setAgentCliProjectDir(
+ userId: string,
+ agentId: string,
+ dirPath: string,
+): Promise<AgentCliProjectDirInfo | null> {
+ if (!safeId(agentId)) return null;
+ const agent = await getAgent(agentId);
+ if (!agent) return null;
+ const cli = agent.runtime?.kind === 'cli' ? agent.runtime.cli : '';
+ if (!cliIsCodingAgent(cli)) {
+ const err: any = new Error('agent is not an external coding agent');
+ err.code = 'E_AGENT_NOT_CODING_CLI';
+ throw err;
+ }
+
+ const cfg = _readAgentRuntimeConfig(userId);
+ const trimmed = String(dirPath || '').trim();
+ if (!trimmed) {
+ delete cfg.project_dirs[agentId];
+ } else {
+ const resolved = path.resolve(trimmed);
+ if (!_dirExists(resolved)) {
+ const err: any = new Error(t('errors.dir_not_exists'));
+ err.code = 'E_DIR_NOT_EXISTS';
+ throw err;
+ }
+ cfg.project_dirs[agentId] = { path: resolved, updated_at: nowIso() };
+ }
+ _writeAgentRuntimeConfig(userId, cfg);
+ return getCliProjectDirInfoForAgent(userId, agent);
+}
+
interface AgentListCache { stamp: string; data: Agent[] }
let _agentListCache: AgentListCache | null = null;
-function _invalidateAgentListCache(): void {
+function _invalidateAgentListCache(opts: { markDirty?: boolean } = {}): void {
_agentListCache = null;
+ if (opts.markDirty === false) return;
// Notify the sync engine (lazy-require — stripped in OrkasOpen builds). Every cache-invalidate
// is also a disk-mutation point, so co-locating the dirty signal here covers all the
// existing call sites without sprinkling sync calls across the file. The relPath here is
@@ -566,7 +751,16 @@ function _invalidateAgentListCache(): void {
* which updates the AGENT dir's mtime but NOT the parent (`CUSTOM_AGENTS_DIR`). The parent's
* mtime stays unchanged, the cache stamp stays valid, and `listAgents` returns ghosts of the
* agents sync just deleted. The sync bridge calls this so the next `listAgents` re-scans. */
-export const invalidateAgentListCache = _invalidateAgentListCache;
+export function invalidateAgentListCache(): void {
+ _invalidateAgentListCache();
+}
+
+/** Drop only the in-memory list cache. Marketplace reconcile updates live under
+ * `<uid>/local/marketplace/agents`, not cloud-synced custom agents, so it must not mark the
+ * `agents` sync domain dirty just to make the next list call re-read disk. */
+export function clearAgentListCache(): void {
+ _invalidateAgentListCache({ markDirty: false });
+}
/** Toggle the active user's enabled override for an agent. Wrapping the
* raw setter so the IPC handler stays one-line and the per-uid resolution
@@ -635,7 +829,10 @@ export async function listAgents(): Promise<Agent[]> {
// effect immediately without busting the disk-spec cache. Cheap — one
// small JSON file read per call.
const { agents: disabledAgentIds } = readDisabledSets(getActiveUserId());
- return specs.map((a) => ({ ...a, enabled: !disabledAgentIds.has(a.agent_id) }));
+ const displaySkillSpecs = await _skillSpecsForDisplay();
+ return specs
+ .map((a) => ({ ...a, enabled: !disabledAgentIds.has(a.agent_id) }))
+ .map((a) => _withDisplaySkillRefs(a, displaySkillSpecs));
}
/**
@@ -655,7 +852,7 @@ export async function getAgent(agentId: string | null | undefined): Promise<Agen
if (norm) {
const { agents: disabledAgentIds } = readDisabledSets(getActiveUserId());
norm.enabled = !disabledAgentIds.has(norm.agent_id);
- return norm;
+ return _withDisplaySkillRefs(norm, await _skillSpecsForDisplay());
}
} catch { /* ignore */ }
}
@@ -687,9 +884,13 @@ export interface CreateAgentOptions {
/** Picked at create time from the modal's runtime selector. Stored as
* authored — `normalizeAgent` validates on read. */
runtime?: AgentRuntime;
- /** Marketplace category code (e.g. `education`). Empty string / omitted = uncategorized;
- * required only at marketplace publish time. */
+ /** Marketplace category code. Empty string / omitted remains tolerated for legacy/manual specs. */
category?: string;
+ /** Output rendering preference picked in the create-modal dropdown. Validated against
+ * `_OUTPUT_FORMAT_VALUES` before persist — unknown values silently drop the field
+ * (= old "missing = no constraint" semantics). The modal sends `'markdown_only'` by
+ * default; omitted = field stays unset on disk. */
+ output_format?: OutputFormat;
}
/** Route a legacy `description` input into the matching language slot.
@@ -711,13 +912,32 @@ function resolveBilingualDescription(
};
}
+async function _skillSpecsForDisplay(): Promise<SkillAllowlistRef[]> {
+ try { return await listSkillSpecs(); }
+ catch (err) {
+ log.warn(`skill display-name map unavailable: ${(err as Error).message}`);
+ return [];
+ }
+}
+
+async function _normalizeWorkflowSkillIds(workflow: string): Promise<string> {
+ const text = String(workflow || '');
+ if (!text) return text;
+ return normalizeKnownSkillRefsForDisplay(text, await _skillSpecsForDisplay());
+}
+
+function _withDisplaySkillRefs(agent: Agent, specs: SkillAllowlistRef[]): Agent {
+ const workflow = normalizeKnownSkillRefsForDisplay(agent.workflow || '', specs);
+ return workflow === agent.workflow ? agent : { ...agent, workflow };
+}
+
/**
* Create a custom agent. The call shape keeps historical optional fields, but
* the quality gate requires a usable name plus at least one description variant
* before the spec is written.
*/
export async function createCustomAgent(
- { name = '', description = '', description_zh, description_en, workflow = '', icon, color, interactive, runtime, category }: CreateAgentOptions = {},
+ { name = '', description = '', description_zh, description_en, workflow = '', icon, color, interactive, runtime, category, output_format }: CreateAgentOptions = {},
): Promise<Agent | null> {
assertAgentNameAllowed(name);
await assertAgentNameUnique(String(name || '').trim());
@@ -729,22 +949,33 @@ export async function createCustomAgent(
// mkdir <aid>/ first so writeJson on agent.json has a parent.
fs.mkdirSync(agentDir(getActiveUserId(), agentId), { recursive: true });
const desc = resolveBilingualDescription(description, description_zh, description_en);
+ const normalizedWorkflow = await _normalizeWorkflowSkillIds(String(workflow || ''));
const data: AgentRaw = {
agent_id: agentId,
name: String(name || '').trim() || t('agent.default_name'),
description_zh: desc.description_zh,
description_en: desc.description_en,
- workflow: String(workflow || ''),
+ workflow: normalizedWorkflow,
created_at: nowIso(),
updated_at: nowIso(),
};
// Only emit `category` to disk when supplied; empty string is omitted so existing agents
- // don't get spurious "category: ''" lines through resave.
- const cleanCategory = typeof category === 'string' ? category.trim() : '';
+ // don't get spurious "category: ''" lines through resave. Candidate membership is dynamic,
+ // so this layer only normalizes the code shape.
+ const cleanCategory = typeof category === 'string' && category.trim()
+ ? normalizeMarketplaceCategoryCode(category)
+ : '';
if (cleanCategory) data.category = cleanCategory;
if (avatars.isKnownIcon(icon)) data.icon = icon;
if (avatars.isKnownColor(color)) data.color = color;
if (typeof interactive === 'boolean') data.interactive = interactive;
+ // Persist `output_format` only when the caller supplied a value the enum recognizes. Unknown
+ // strings (e.g. a future client speaking a newer dialect at an older main) drop silently — the
+ // missing field is equivalent to "no constraint" and won't break the worker prompt, whereas a
+ // bogus stored value would survive normalizeAgent and silently turn into empty hint anyway.
+ if (typeof output_format === 'string' && _OUTPUT_FORMAT_VALUES.has(output_format as OutputFormat)) {
+ data.output_format = output_format as OutputFormat;
+ }
// Persist runtime only when it survives validation; an in_process
// selection is the implicit default and not written to disk so old
// tooling diffs cleanly.
@@ -838,8 +1069,8 @@ export interface UpdateAgentFields {
* Authored by the create modal + edit UI, not the LLM edit prompt. */
runtime?: AgentRuntime | null;
/** Marketplace category code. Empty string drops the field; omitted = untouched.
- * Authored by the create / edit dialog dropdown OR by the agent-edit LLM via the
- * `<category>` sub-tag (validated against `AGENT_CATEGORY_CODES` in `_parseAgentBlock`). */
+ * Authored by hidden create defaults or by the agent-edit LLM via the `<category>` sub-tag.
+ * Missing model output is repaired to the default category on create. */
category?: string;
/** Three-way update:
* array (possibly empty) → replace (filtered to non-empty strings)
@@ -847,6 +1078,12 @@ export interface UpdateAgentFields {
* omitted → untouched
* Authored by the agent edit UI (connectors toggle list), NOT the agent-edit LLM. */
enabled_connectors?: string[] | null;
+ /** Three-way update:
+ * OutputFormat string → set (one of the three enum values)
+ * null → drop (revert to default 'auto')
+ * omitted → untouched
+ * Authored by the agent edit UI dropdown. */
+ output_format?: OutputFormat | null;
}
/**
@@ -920,7 +1157,8 @@ async function _applyAgentUpdates(
for (const k of ['name', 'workflow'] as const) {
if (Object.prototype.hasOwnProperty.call(updates || {}, k)) {
const v = (updates as any)[k];
- (data as any)[k] = typeof v === 'string' ? v : '';
+ const next = typeof v === 'string' ? v : '';
+ (data as any)[k] = k === 'workflow' ? await _normalizeWorkflowSkillIds(next) : next;
}
}
// First migrate any persisted legacy `description` into the bilingual pair
@@ -970,13 +1208,7 @@ async function _applyAgentUpdates(
} else if (Array.isArray(v)) {
const raw = v.filter((x) => typeof x === 'string' && safeId(x));
const specs = await listSkillSpecs();
- const known = new Set(specs.map((s) => s.id));
- const ids: string[] = [];
- const unknown: string[] = [];
- for (const id of raw) {
- if (known.has(id)) ids.push(id);
- else unknown.push(id);
- }
+ const { ids, unknown } = resolveSkillAllowlistRefs(specs, raw);
if (unknown.length) {
log.warn(`agent ${agentId}: unknown skills dropped: ${unknown.join(',')}`);
}
@@ -1003,6 +1235,16 @@ async function _applyAgentUpdates(
(data as { enabled_connectors?: string[] }).enabled_connectors = ids;
}
}
+ if (Object.prototype.hasOwnProperty.call(updates || {}, 'output_format')) {
+ const v = (updates as { output_format?: OutputFormat | null }).output_format;
+ if (v === null || v === 'auto') {
+ // 'auto' is the implicit default; don't write it to disk so spec
+ // diffs stay clean and unset agents don't suddenly get a field.
+ delete (data as { output_format?: unknown }).output_format;
+ } else if (typeof v === 'string' && _OUTPUT_FORMAT_VALUES.has(v)) {
+ (data as { output_format?: OutputFormat }).output_format = v;
+ }
+ }
if (Object.prototype.hasOwnProperty.call(updates || {}, 'icon')) {
const v = (updates as any).icon;
if (avatars.isKnownIcon(v)) data.icon = v;
@@ -1019,13 +1261,13 @@ async function _applyAgentUpdates(
data.interactive = v;
}
}
- // category: explicit empty-string drops the field; any non-empty string is stored as-is
- // (no allow-list validation on this layer — caller / UI dropdown is the source of truth).
+ // category: explicit empty-string drops the field; any non-empty string is normalized to a
+ // safe code shape. Candidate membership is prompt-time dynamic, not a static backend list.
if (Object.prototype.hasOwnProperty.call(updates || {}, 'category')) {
const v = (updates as any).category;
const trimmed = typeof v === 'string' ? v.trim() : '';
if (!trimmed) delete (data as any).category;
- else (data as any).category = trimmed;
+ else (data as any).category = normalizeMarketplaceCategoryCode(trimmed);
}
if (Object.prototype.hasOwnProperty.call(updates || {}, 'runtime')) {
const v = updates.runtime;
@@ -1181,6 +1423,8 @@ export async function deleteCustomAgent(agentId: string): Promise<boolean> {
log.warn(`session unlink user=${uid} agent=${agentId}: ${(err as Error).message}`);
}
}
+ try { _deleteAgentRuntimeConfigEntry(uid, agentId); }
+ catch (err) { log.warn(`runtime config cleanup user=${uid} agent=${agentId}: ${(err as Error).message}`); }
}
}
@@ -1210,15 +1454,9 @@ export async function deleteCustomAgent(agentId: string): Promise<boolean> {
// placeholder to stream-hide. Shared between agent-edit chat and main-chat
// quick-create; see the "Create agent" section of
// `chat_agent_setup.md` / `chat_commander.md`.
-const AGENT_CONTAINER_RE = /<agent>([\s\S]*?)<\/agent>/g;
const AGENT_CHILD_RE = (tag: string) => new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`);
-/** Marketplace category codes — kept in sync with
- * `Server/biz/marketplace/marketplace_mgr.py::DEFAULT_CATEGORIES`. Single source of truth
- * for `<category>` validation in `<agent>` container parsing. */
-export const AGENT_CATEGORY_CODES: ReadonlySet<string> = new Set([
- 'education', 'ecommerce', 'rnd', 'writing', 'data', 'general',
-]);
+const AGENT_CATEGORY_CODE_RE = /^[a-z][a-z0-9_-]{0,79}$/;
export interface ExtractedFields {
/** Parsed from `<agent_id>` inside `<agent>`. Present → commander wants to
@@ -1243,10 +1481,8 @@ export interface ExtractedFields {
* `false` (case-insensitive); anything else → key omitted (leave the
* existing flag untouched). */
interactive?: boolean;
- /** Parsed from `<category>` inside `<agent>`. Body must be one of
- * `AGENT_CATEGORY_CODES`; invalid value → key omitted (existing field
- * preserved). New agents without a category fall through to whatever
- * `createCustomAgent` decides (empty string today). */
+ /** Parsed from `<category>` inside `<agent>`. Candidate membership is
+ * prompt-time dynamic; parsing only enforces a safe code shape. */
category?: string;
}
@@ -1317,9 +1553,7 @@ function _parseAgentBlock(inner: string): ExtractedFields {
const catM = inner.match(AGENT_CHILD_RE('category'));
if (catM) {
const v = catM[1].trim().toLowerCase();
- // Validate against the known code set. Unknown values are dropped silently — the existing
- // category field on the agent is preserved (don't let an LLM hallucinated code blank it).
- if (AGENT_CATEGORY_CODES.has(v)) fields.category = v;
+ if (AGENT_CATEGORY_CODE_RE.test(v)) fields.category = v;
}
return fields;
}
@@ -1332,15 +1566,26 @@ function _parseAgentBlock(inner: string): ExtractedFields {
export function extractAgentFieldBlocks(
text: string,
): { cleanText: string; blocks: ExtractedFields[] } {
- if (!text || text.indexOf('<agent>') < 0) return { cleanText: text, blocks: [] };
+ if (!text || text.indexOf('<agent') < 0) return { cleanText: text, blocks: [] };
+ const ranges = findOuterTagRanges(text, 'agent');
+ if (!ranges.length) return { cleanText: text, blocks: [] };
const blocks: ExtractedFields[] = [];
- // Iterate every container with the global-flag regex (NOT just the
- // first). `AGENT_CONTAINER_RE` carries `/g` so successive `.exec` calls
- // walk forward; we use `matchAll` for a flat collection.
- for (const m of text.matchAll(AGENT_CONTAINER_RE)) {
- blocks.push(_parseAgentBlock(m[1]));
+ let cleaned = '';
+ let cursor = 0;
+ for (const [s, e] of ranges) {
+ cleaned += text.slice(cursor, s);
+ const block = text.slice(s, e);
+ if (block.endsWith('</agent>')) {
+ const openEnd = block.indexOf('>');
+ if (openEnd >= 0) {
+ const inner = block.slice(openEnd + 1, block.length - '</agent>'.length);
+ blocks.push(_parseAgentBlock(inner));
+ }
+ }
+ cursor = e;
}
- const cleaned = text.replace(AGENT_CONTAINER_RE, '').replace(/\n{3,}/g, '\n\n').trim();
+ cleaned += text.slice(cursor);
+ cleaned = cleaned.replace(/\n{3,}/g, '\n\n').trim();
return { cleanText: cleaned, blocks };
}
@@ -1423,6 +1668,7 @@ export function buildAgentEditSystemPrompt(agent: {
description_zh?: string;
description_en?: string;
workflow?: string;
+ category?: string;
interactive?: boolean;
/** When the agent is CLI-backed, switch to `chat_agent_setup_cli.md`
* which omits workflow/skills authoring and tells the LLM not to
@@ -1579,7 +1825,7 @@ export async function* streamSendToAgentEditChat(
if (Object.keys(fields).length) {
await updateCustomAgent(agentId, fields);
Object.assign(updated, fields);
- for (const k of ['name', 'workflow'] as const) {
+ for (const k of ['name', 'workflow', 'category'] as const) {
if (fields[k] !== undefined) {
synthesizedProgress.push(t('process.agent.update_field', { field: k }));
}
@@ -1688,15 +1934,17 @@ export function isValidAgentId(id: unknown): boolean {
export async function createAgentFromBlocks(fields: ExtractedFields): Promise<Agent | null> {
const name = (fields.name || '').trim();
const workflow = (fields.workflow || '').trim();
+ const category = fields.category
+ ? normalizeMarketplaceCategoryCode(fields.category)
+ : DEFAULT_MARKETPLACE_CATEGORY_CODE;
if (!name || !workflow) return null;
const description = (fields.description || '').trim();
const description_zh = (fields.description_zh || '').trim();
const description_en = (fields.description_en || '').trim();
const created = await createCustomAgent({
- name, description, description_zh, description_en, workflow,
+ name, description, description_zh, description_en, workflow, category,
...(typeof fields.interactive === 'boolean' ? { interactive: fields.interactive } : {}),
- ...(typeof fields.category === 'string' ? { category: fields.category } : {}),
});
if (!created) return null;
// Fold optional skill_list + inputs in via updateCustomAgent so the
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index 66b94d50..e20a7aff 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -31,12 +31,15 @@ import { t } from '../i18n';
const log = createLogger('chats');
import * as search from './search';
-import * as groupChat from './group_chat';
-import { buildGconvSessionId, readState, setStatus } from './group_chat/state';
+import { purgeGroupDir, readState, setStatus } from './group_chat/state';
import type { GroupMessage } from './group_chat/visibility';
const CONVERSATION_INDEX_NAME = '_index.json';
+function buildConversationSessionId(cid: string): string {
+ return `gconv-${cid}`;
+}
+
export type ConversationKind = 'normal' | string;
export interface Conversation {
@@ -109,7 +112,8 @@ export async function listConversations(userId: string): Promise<Conversation[]>
let since: string | null = null;
try {
const s = await readState(userId, c.conversation_id);
- const busBusy = !groupChat.busIsQuiescent(userId, c.conversation_id);
+ const bus = await import('./group_chat/bus');
+ const busBusy = !bus.isQuiescent(userId, c.conversation_id);
processing = s.status === 'running' || busBusy;
since = processing ? s.last_active_at : null;
} catch { /* missing state file = idle */ }
@@ -203,7 +207,7 @@ export async function createConversation(userId: string, {
kind,
agent_id: agentId || '',
skill_id: skillId || '',
- session_id: buildGconvSessionId(cid),
+ session_id: buildConversationSessionId(cid),
...(projectId ? { project_id: projectId } : {}),
created_at: nowIso(),
updated_at: nowIso(),
@@ -244,7 +248,11 @@ export async function deleteConversation(userId: string, cid: string): Promise<b
await saveConversations(userId, kept);
// Purge group dir (members.json / state.json / plan.md / visibility/) + bus state.
- try { await groupChat.dropConv(userId, cid); }
+ try {
+ const bus = await import('./group_chat/bus');
+ bus.dropConv(userId, cid);
+ await purgeGroupDir(userId, cid);
+ }
catch (err) { log.warn(`group_chat dropConv failed user=${userId} cid=${cid}: ${(err as Error).message}`); }
// Purge main jsonl.
@@ -254,7 +262,7 @@ export async function deleteConversation(userId: string, cid: string): Promise<b
search.dropChatConversation(userId, cid);
// Purge commander session + every per-agent member session.
- purgeSession(userId, removed?.session_id || buildGconvSessionId(cid));
+ purgeSession(userId, removed?.session_id || buildConversationSessionId(cid));
// gmember sessions: glob the sessions dir for `<uid>-gmember-<cid>-*` —
// we can't rely on readMembers() because `groupChat.dropConv` above has
// already removed members.json (the historical cause of the 50+ orphan
diff --git a/src/main/features/expert_signals/extractors/event.ts b/src/main/features/expert_signals/extractors/event.ts
new file mode 100644
index 00000000..6837203f
--- /dev/null
+++ b/src/main/features/expert_signals/extractors/event.ts
@@ -0,0 +1,235 @@
+/**
+ * T0 event extractors: retry / skip / form_left_blank / tool_failure.
+ *
+ * Pure builders — each function takes the structured event payload and
+ * returns one (or more) `SignalInput`. The caller (IPC handler / bus
+ * turn-end hook) emits.
+ *
+ * Why not just inline JSON literals at the chokepoints: keeping the field
+ * shape here means schema evolution (e.g. adding `extractor_version` to
+ * every signal) is a one-file change; chokepoint callers just hand over
+ * raw payloads.
+ */
+
+import type { SignalInput, SkillSystem, SkillInvokeTrigger } from '../types';
+import { EXTRACTOR_VERSION } from '../types';
+
+// ── retry / skip ────────────────────────────────────────────────────────
+
+/** User clicked the plan rail "Retry" button on a failed step. */
+export function buildRetrySignal(args: {
+ cid: string;
+ aid: string;
+ turn_id: string;
+ step_index: number;
+ msg_ids?: string[];
+}): SignalInput {
+ return {
+ type: 'retry',
+ source: 'event',
+ cid: args.cid,
+ aid: args.aid,
+ turn_id: args.turn_id,
+ context_ref: { msg_ids: args.msg_ids || [] },
+ extractor_version: EXTRACTOR_VERSION.event,
+ metadata: { step_index: args.step_index },
+ };
+}
+
+/** User clicked plan rail "Skip" — a weaker form of retry. */
+export function buildSkipSignal(args: {
+ cid: string;
+ aid: string;
+ turn_id: string;
+ step_index: number;
+ msg_ids?: string[];
+}): SignalInput {
+ return {
+ type: 'skip',
+ source: 'event',
+ cid: args.cid,
+ aid: args.aid,
+ turn_id: args.turn_id,
+ context_ref: { msg_ids: args.msg_ids || [] },
+ extractor_version: EXTRACTOR_VERSION.event,
+ metadata: { step_index: args.step_index },
+ };
+}
+
+// ── form_left_blank ─────────────────────────────────────────────────────
+
+export interface FormFieldDef {
+ id: string;
+ required?: boolean;
+ default?: unknown;
+ type?: string;
+}
+
+/**
+ * Emit one signal per field that the user "didn't change" on submit.
+ *
+ * - required field with empty value → `was_required=true`
+ * - non-required field whose value matches `default` → `was_required=false`
+ *
+ * The phase-1 patch suggester reads these to recommend dropping fields
+ * the user never touches.
+ */
+export function buildFormLeftBlankSignals(args: {
+ cid: string;
+ aid: string;
+ turn_id: string;
+ msg_id: string;
+ fields: FormFieldDef[];
+ values: Record<string, unknown>;
+}): SignalInput[] {
+ const out: SignalInput[] = [];
+ for (const field of args.fields) {
+ const submitted = args.values[field.id];
+ const isBlank = _looksBlank(submitted);
+ const isDefault = !isBlank && _equals(submitted, field.default);
+ if (!isBlank && !isDefault) continue;
+ out.push({
+ type: 'form_left_blank',
+ source: 'event',
+ cid: args.cid,
+ aid: args.aid,
+ turn_id: args.turn_id,
+ context_ref: { msg_ids: [args.msg_id] },
+ extractor_version: EXTRACTOR_VERSION.event,
+ metadata: {
+ input_id: field.id,
+ was_required: !!field.required,
+ used_default: isDefault,
+ },
+ });
+ }
+ return out;
+}
+
+// ── tool_failure ────────────────────────────────────────────────────────
+
+/** A tool call returned `isError=true` that the agent didn't subsequently
+ * recover from in the same turn. Caller decides recovery semantics. */
+export function buildToolFailureSignal(args: {
+ cid: string;
+ aid: string | null;
+ turn_id: string;
+ tool_name: string;
+ error_excerpt: string;
+ msg_ids?: string[];
+}): SignalInput {
+ return {
+ type: 'tool_failure',
+ source: 'event',
+ cid: args.cid,
+ aid: args.aid,
+ turn_id: args.turn_id,
+ context_ref: { msg_ids: args.msg_ids || [] },
+ extractor_version: EXTRACTOR_VERSION.event,
+ metadata: {
+ tool_name: args.tool_name,
+ error_excerpt: args.error_excerpt.slice(0, 200),
+ },
+ };
+}
+
+// ── skill_advertised / skill_invoked ────────────────────────────────────
+
+/** One signal per (system) per turn carrying every advertised skill id from
+ * that catalog. The bus drains its per-turn buffer at turn-end and groups
+ * by `system` so a single advertised signal covers all of A.custom (or
+ * A.platform / B); consumers union over signals to get the full advertised
+ * set for the turn. */
+export function buildSkillAdvertisedSignal(args: {
+ cid: string;
+ aid: string | null;
+ turn_id: string;
+ system: SkillSystem;
+ skill_ids: string[];
+ msg_ids?: string[];
+}): SignalInput {
+ return {
+ type: 'skill_advertised',
+ source: 'event',
+ cid: args.cid,
+ aid: args.aid,
+ turn_id: args.turn_id,
+ context_ref: { msg_ids: args.msg_ids || [] },
+ extractor_version: EXTRACTOR_VERSION.skill_attribution,
+ delta: { system: args.system, skill_ids: args.skill_ids.slice() },
+ };
+}
+
+/** Emitted when the agent's `read_file` resolves to a SKILL.md path inside
+ * one of the three skill roots. Same turn can produce multiple invoked
+ * signals for distinct skills; consumers de-dup by (turn_id, system, skill_id). */
+export function buildSkillInvokedSignal(args: {
+ cid: string;
+ aid: string | null;
+ turn_id: string;
+ system: SkillSystem;
+ skill_id: string;
+ trigger: SkillInvokeTrigger;
+ msg_ids?: string[];
+}): SignalInput {
+ return {
+ type: 'skill_invoked',
+ source: 'event',
+ cid: args.cid,
+ aid: args.aid,
+ turn_id: args.turn_id,
+ context_ref: { msg_ids: args.msg_ids || [] },
+ extractor_version: EXTRACTOR_VERSION.skill_attribution,
+ delta: { system: args.system, skill_id: args.skill_id, trigger: args.trigger },
+ };
+}
+
+// ── agent_dispatched ────────────────────────────────────────────────────
+
+/** Commander's dispatch decision for a single ready-group: which agent ids
+ * were considered (`candidates`) and which got woken (`dispatched`). In the
+ * current plan executor model the two are identical (plan_set already
+ * filtered) — kept distinct in schema so phase 1 commander LLM can record
+ * "considered but rejected" without a schema migration. */
+export function buildAgentDispatchedSignal(args: {
+ cid: string;
+ turn_id: string;
+ candidates: string[];
+ dispatched: string[];
+ parallel_group: string | null;
+ msg_ids?: string[];
+}): SignalInput {
+ return {
+ type: 'agent_dispatched',
+ source: 'event',
+ cid: args.cid,
+ aid: null,
+ turn_id: args.turn_id,
+ context_ref: { msg_ids: args.msg_ids || [] },
+ extractor_version: EXTRACTOR_VERSION.agent_dispatch,
+ delta: {
+ candidates: args.candidates.slice(),
+ dispatched: args.dispatched.slice(),
+ parallel_group: args.parallel_group,
+ },
+ };
+}
+
+// ── helpers ─────────────────────────────────────────────────────────────
+
+function _looksBlank(v: unknown): boolean {
+ if (v === null || v === undefined) return true;
+ if (typeof v === 'string') return v.trim() === '';
+ if (Array.isArray(v)) return v.length === 0;
+ return false;
+}
+
+function _equals(a: unknown, b: unknown): boolean {
+ if (a === b) return true;
+ if (typeof a !== typeof b) return false;
+ if (Array.isArray(a) && Array.isArray(b)) {
+ if (a.length !== b.length) return false;
+ return a.every((x, i) => x === b[i]);
+ }
+ return false;
+}
diff --git a/src/main/features/expert_signals/extractors/silence.ts b/src/main/features/expert_signals/extractors/silence.ts
new file mode 100644
index 00000000..0f97689b
--- /dev/null
+++ b/src/main/features/expert_signals/extractors/silence.ts
@@ -0,0 +1,111 @@
+/**
+ * T0 silence extractor: agent message followed by N minutes of no user
+ * response → emit `silence` signal.
+ *
+ * Implementation: per-conv `setTimeout` registered at agent-turn-end,
+ * cancelled when the user sends the next message. NOT a global poller
+ * (plan §11 reject #8 — `setInterval` over all convs is O(N) waste).
+ *
+ * Restart semantics: timers live in process memory only — app restart
+ * drops pending checks. Phase 0 accepts the gap; phase 1+ can add a
+ * boot-time backfill (scan `<cid>.jsonl` for trailing agent msgs older
+ * than threshold) when there's a consumer that needs it.
+ *
+ * This module is also the **phase-1 LLM session-end pass mount point**
+ * (plan §5): the same timer's fire is "session inactive > N min", so a
+ * future LLM pass hook can register here without changing scheduling.
+ */
+
+import { emitSignal } from '../index';
+import { EXTRACTOR_VERSION, type SignalInput } from '../types';
+import { createLogger } from '../../../logger';
+
+const log = createLogger('expert-signals:silence');
+
+/** Default: 30 minutes of inactivity = "the user accepted silently".
+ * Tunable per call; tests pass a tiny value. */
+export const SILENCE_THRESHOLD_MS = 30 * 60 * 1000;
+
+interface PendingCheck {
+ timer: NodeJS.Timeout;
+ /** Captured at schedule time so the fire callback has all the context
+ * it needs without re-reading conv state. */
+ uid: string;
+ cid: string;
+ aid: string | null;
+ turn_id: string;
+ msg_ids: string[];
+}
+
+const _pending = new Map<string, PendingCheck>();
+
+function _key(uid: string, cid: string): string { return `${uid}:${cid}`; }
+
+/**
+ * Register a silence check after an agent turn ends. Cancels any prior
+ * check for this conv (a new agent message resets the silence window).
+ *
+ * Calling with `thresholdMs <= 0` cancels the check without scheduling
+ * a new one — useful when caller wants "explicit cancel" semantics.
+ */
+export function scheduleSilenceCheck(args: {
+ uid: string;
+ cid: string;
+ aid: string | null;
+ turn_id: string;
+ msg_ids: string[];
+ thresholdMs?: number;
+}): void {
+ cancelSilenceCheck(args.uid, args.cid);
+ const ms = args.thresholdMs ?? SILENCE_THRESHOLD_MS;
+ if (ms <= 0) return;
+ const key = _key(args.uid, args.cid);
+ const timer = setTimeout(() => {
+ _pending.delete(key);
+ try {
+ emitSignal(args.uid, _buildSilenceSignal(args));
+ } catch (err) {
+ log.warn(`silence emit threw uid=${args.uid} cid=${args.cid}: ${(err as Error).message}`);
+ }
+ }, ms);
+ // Don't keep the event loop alive just for silence checks — if the app
+ // is otherwise idle, it should be allowed to exit.
+ if (typeof (timer as { unref?: () => unknown }).unref === 'function') {
+ (timer as { unref: () => unknown }).unref();
+ }
+ _pending.set(key, { ...args, timer });
+}
+
+/** Cancel a pending silence check (user just sent a message). Idempotent. */
+export function cancelSilenceCheck(uid: string, cid: string): void {
+ const key = _key(uid, cid);
+ const p = _pending.get(key);
+ if (p) {
+ clearTimeout(p.timer);
+ _pending.delete(key);
+ }
+}
+
+/** Test seam: drop all pending timers. Tests should call this in
+ * afterEach to avoid leaked timers across cases. */
+export function _clearAllPending(): void {
+ for (const p of _pending.values()) clearTimeout(p.timer);
+ _pending.clear();
+}
+
+function _buildSilenceSignal(args: {
+ cid: string;
+ aid: string | null;
+ turn_id: string;
+ msg_ids: string[];
+}): SignalInput {
+ return {
+ type: 'silence',
+ source: 'event',
+ cid: args.cid,
+ aid: args.aid,
+ turn_id: args.turn_id,
+ context_ref: { msg_ids: args.msg_ids },
+ extractor_version: EXTRACTOR_VERSION.silence,
+ };
+}
diff --git a/src/main/features/expert_signals/extractors/text.ts b/src/main/features/expert_signals/extractors/text.ts
new file mode 100644
index 00000000..7db407fa
--- /dev/null
+++ b/src/main/features/expert_signals/extractors/text.ts
@@ -0,0 +1,219 @@
+/**
+ * T1 text-rule extractors: accept (silent + explicit) / correction / reject / edit.
+ *
+ * Pure functions: input is the agent's last final text + the user's reply
+ * text + context (cid/aid/turn_id/msg_ids); output is `SignalInput[]` ready
+ * to hand to `emitSignal`. No FS, no IO, no LLM.
+ *
+ * Why pure: the bus.ts turn-end hook owns chokepoint identity (uid + cid +
+ * actor + turn_id); the extractor only needs raw text. Keeps extractors
+ * testable with simple fixtures and the chokepoint logic small.
+ */
+
+import * as crypto from 'node:crypto';
+
+import type { SignalInput, SignalContextRef } from '../types';
+import { EXTRACTOR_VERSION } from '../types';
+
+// NOTE on `#core-agent`: this extractor used to re-export `detectUserCorrection`
+// for convenience, but a top-level `import { detectUserCorrection } from '#core-agent'`
+// transitively loads pi-ai at module-evaluation time and trips
+// `ERR_PACKAGE_PATH_NOT_EXPORTED` (PC/CLAUDE.md §3). The caller (`turn_hooks.ts`)
+// runs the heuristic via dynamic `await import('#core-agent')` and passes the
+// boolean in as `correction_detected` — no import here.
+
+// ── User-message classifier patterns ────────────────────────────────────
+
+/** Explicit-acceptance patterns. Kept narrow on purpose — only phrases
+ * whose ONLY semantic role is acceptance count. "好" alone is too noisy
+ * (matches "好像 / 好处 / 好奇"); anchor on a terminator (punctuation,
+ * whitespace, or EOL) right after the accept word. */
+const ACCEPT_EXPLICIT_RE = [
+ /^好的?(?:[,。!.!\s]|$)/,
+ /^OK(?:[,。!.!\s]|$)/i,
+ /^对的?(?:[,。!.!\s]|$)/,
+ /^可以(?:[,。!.!\s]|$)/,
+ /^收到(?:[,。!.!\s]|$)/,
+ /\bok[,!.]?\s*(thanks|thx)?\s*$/i,
+ /\b(sounds|looks)\s+good\b/i,
+ /\bperfect\b/i,
+];
+
+/** Reject patterns — stronger than correction; user wants the whole attempt
+ * discarded. Some words ("重新") also fire correction; that's intentional —
+ * a single message can carry both signals, downstream merges by turn_id. */
+const REJECT_RE = [
+ /重新(做|来|开始)/,
+ /算了/,
+ /不要(这个|这样|做了)/,
+ /放弃/,
+ /\bstart\s+over\b/i,
+ /\bnevermind\b/i,
+ /\bforget\s+(it|that)\b/i,
+];
+
+// ── Public extractor ────────────────────────────────────────────────────
+
+export interface TextExtractInput {
+ cid: string;
+ aid: string | null;
+ turn_id: string;
+ /** Agent's most recent final text in this conv (string before the user
+ * reply). Empty string when this is the conv's very first user turn. */
+ agent_last_text: string;
+ /** User's current message text (the one that closed the turn). */
+ user_msg: string;
+ /** Message ids contextualizing this signal (typically [agent_msg_id, user_msg_id]). */
+ msg_ids: string[];
+ /** Pre-computed `detectUserCorrection` result. Pass through from the
+ * bus turn-end hook so the same boolean drives both the `correction`
+ * signal here AND the RunMetrics `userCorrections+=1` in runner.ts —
+ * no double-judgment, no drift between the two. */
+ correction_detected: boolean;
+}
+
+/**
+ * Extract zero or more text-class signals from a (agent_text, user_msg)
+ * pair. Caller (bus.ts turn-end hook) is responsible for picking which
+ * pair to feed; this function does not look at history.
+ *
+ * Multiple signal types can fire simultaneously (e.g. user says "不对,
+ * 重新做" → correction + reject). Downstream merges by turn_id.
+ *
+ * `accept(silent)` is NOT emitted here — it's a delayed signal that fires
+ * only when N minutes pass with no further user message. Bus owns that
+ * timer; see `silence.ts` for the analogous handling.
+ */
+export function extractTextSignals(input: TextExtractInput): SignalInput[] {
+ const out: SignalInput[] = [];
+ const userMsg = input.user_msg || '';
+ if (!userMsg.trim()) return out;
+
+ const ref: SignalContextRef = { msg_ids: input.msg_ids };
+ const base = {
+ cid: input.cid,
+ aid: input.aid,
+ turn_id: input.turn_id,
+ source: 'event' as const,
+ extractor_version: EXTRACTOR_VERSION.text,
+ context_ref: ref,
+ };
+ const post = { user_msg: _truncate(userMsg, 200) };
+ const pre = input.agent_last_text ? {
+ text_hash: _sha1(input.agent_last_text),
+ text_excerpt: _truncate(input.agent_last_text, 200),
+ } : undefined;
+
+ if (input.correction_detected) {
+ out.push({
+ ...base, type: 'correction', pre, post,
+ delta: { matched_patterns: ['correction-heuristic'] },
+ });
+ }
+
+ const rejectMatches = _matchedPatterns(userMsg, REJECT_RE);
+ if (rejectMatches.length) {
+ out.push({
+ ...base, type: 'reject', pre, post,
+ delta: { matched_patterns: rejectMatches },
+ });
+ }
+
+ const acceptMatches = _matchedPatterns(userMsg, ACCEPT_EXPLICIT_RE);
+ // Don't double-emit accept on a message that's also correction / reject —
+ // those signals are stronger; an "好的" prefix doesn't override "重新做".
+ if (acceptMatches.length && !input.correction_detected && !rejectMatches.length) {
+ out.push({
+ ...base, type: 'accept', pre, post,
+ delta: { matched_patterns: acceptMatches },
+ metadata: { variant: 'explicit' },
+ });
+ }
+
+ // Edit signal: only when there's an agent_last_text to diff against AND
+ // the user message isn't already covered by correction / reject (which
+ // already encode "user pushed back").
+ if (input.agent_last_text && !input.correction_detected && !rejectMatches.length) {
+ const editClassification = _classifyEdit(input.agent_last_text, userMsg);
+ if (editClassification) {
+ out.push({
+ ...base, type: 'edit', pre, post,
+ delta: editClassification,
+ });
+ }
+ }
+
+ return out;
+}
+
+// ── Internals ───────────────────────────────────────────────────────────
+
+/** Classify the user message as an edit of the agent's last text, or skip
+ * (returns null) if it looks like a fresh turn / question rather than an
+ * edit.
+ *
+ * Heuristics (intentionally simple; phase 1 LLM pass can correct false
+ * positives — see plan §3.3 P0 source 'event_then_semantic'):
+ * - user msg length is within [30%, 200%] of agent's text → plausibly
+ * a rewrite (not a one-liner question)
+ * - char-level Levenshtein distance > 20 (skip near-identical echoes)
+ * - common prefix or sequence with agent text > 10 chars (some overlap;
+ * a fully fresh question would have ~0 overlap)
+ */
+function _classifyEdit(agentText: string, userMsg: string): { edit_distance: number; edit_type: 'minor' | 'major_rewrite' } | null {
+ const aLen = agentText.length;
+ const uLen = userMsg.length;
+ if (uLen < aLen * 0.3 || uLen > aLen * 2) return null;
+ const dist = _levenshtein(agentText.slice(0, 400), userMsg.slice(0, 400));
+ if (dist <= 20) return null;
+ if (_overlapChars(agentText, userMsg) < 10) return null;
+ return {
+ edit_distance: dist,
+ edit_type: dist < aLen * 0.4 ? 'minor' : 'major_rewrite',
+ };
+}
+
+/** Pattern→match list (returns the pattern's source string for each hit). */
+function _matchedPatterns(text: string, patterns: RegExp[]): string[] {
+ const out: string[] = [];
+ for (const re of patterns) {
+ if (re.test(text)) out.push(re.source);
+ }
+ return out;
+}
+
+/** Standard iterative two-row Levenshtein. Bounded to 400 chars in caller. */
+function _levenshtein(a: string, b: string): number {
+ if (a === b) return 0;
+ if (!a.length) return b.length;
+ if (!b.length) return a.length;
+ let prev = new Array(b.length + 1);
+ let curr = new Array(b.length + 1);
+ for (let j = 0; j <= b.length; j++) prev[j] = j;
+ for (let i = 1; i <= a.length; i++) {
+ curr[0] = i;
+ for (let j = 1; j <= b.length; j++) {
+ const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
+ curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
+ }
+ [prev, curr] = [curr, prev];
+ }
+ return prev[b.length];
+}
+
+/** Length of the longest common prefix-style overlap. Crude but fast —
+ * good enough for the edit classifier's "some shared text" check. */
+function _overlapChars(a: string, b: string): number {
+ const n = Math.min(a.length, b.length);
+ let i = 0;
+ while (i < n && a.charCodeAt(i) === b.charCodeAt(i)) i++;
+ return i;
+}
+
+function _sha1(s: string): string {
+ return 'sha1:' + crypto.createHash('sha1').update(s).digest('hex').slice(0, 12);
+}
+
+function _truncate(s: string, n: number): string {
+ return s.length <= n ? s : s.slice(0, n);
+}
diff --git a/src/main/features/expert_signals/index.ts b/src/main/features/expert_signals/index.ts
new file mode 100644
index 00000000..f48c5b5c
--- /dev/null
+++ b/src/main/features/expert_signals/index.ts
@@ -0,0 +1,38 @@
+/**
+ * Expert signals — public API.
+ *
+ * Two entry points for outer modules:
+ * - `emitSignal(uid, input)` — fire-and-forget write at chokepoints
+ * - `querySignals(filter)` — read-back for reflection / patch suggester / critic
+ *
+ * Outer callers must import only from here, never from `./extractors/*` or
+ * `./storage.ts` directly. Storage layout, jsonl format, and extractor
+ * versioning are implementation detail subject to change.
+ *
+ * Why so thin: the extractor rules live with their chokepoint callers (bus
+ * turn-end runs text + tool_failure extractors; IPC handlers run event
+ * extractors). This module is just the write/read facade — it doesn't own
+ * triggering logic.
+ */
+
+import { appendSignal, querySignals as _querySignals } from './storage';
+import type { Signal, SignalFilter, SignalInput } from './types';
+
+export type {
+ Signal, SignalFilter, SignalInput,
+ SignalType, SignalSource, SignalDelta, SignalContextRef, SignalTextSlice,
+} from './types';
+export { EXTRACTOR_VERSION } from './types';
+
+/** Emit a signal. Fire-and-forget; never throws. The caller passes the
+ * active uid explicitly (rather than resolving from `getActiveUserId()`
+ * here) so a turn-end hook fired during user-switch doesn't accidentally
+ * cross-write. */
+export function emitSignal(uid: string, input: SignalInput): void {
+ appendSignal(uid, input);
+}
+
+/** Query signals across one or more daily files. */
+export async function querySignals(filter: SignalFilter = {}): Promise<Signal[]> {
+ return _querySignals(filter);
+}
diff --git a/src/main/features/expert_signals/skill_path.ts b/src/main/features/expert_signals/skill_path.ts
new file mode 100644
index 00000000..b8148803
--- /dev/null
+++ b/src/main/features/expert_signals/skill_path.ts
@@ -0,0 +1,80 @@
+/**
+ * Pure helpers to classify a SKILL.md path back to its source system.
+ *
+ * Used at the `read_file` chokepoint to emit `skill_invoked` signals — when
+ * the LLM reads a SKILL.md body (Claude Code progressive disclosure), we
+ * want to know whether it came from System A.custom / A.platform / B.
+ *
+ * Why this lives in `features/expert_signals/` (not in a shared util):
+ * the parsing is a one-trick pony for signal attribution; no other caller
+ * needs it. Keeping it next to its consumer avoids over-abstracting.
+ *
+ * **No FS access**: pure path-string comparison against the three root
+ * helpers from `paths.ts`. Reading the SKILL.md body would violate
+ * PC/CLAUDE.md §3 (model layer doesn't read business data) and is
+ * unnecessary — the system label is derivable from the absolute path
+ * alone.
+ *
+ * See `docs/plans/expert-signals-skill-attribution.md` §3.3.
+ */
+
+import * as path from 'node:path';
+
+import {
+ userSkillsDir,
+ userMarketplaceSkillsDir,
+ userAgentsDir,
+} from '../../paths';
+
+export type SkillSystem = 'A.custom' | 'A.platform' | 'B';
+
+export interface ParsedSkillPath {
+ system: SkillSystem;
+ /** Directory name of the skill (last segment before `SKILL.md`). */
+ skill_id: string;
+ /** Owning agent id — only set for System B (`<uid>/cloud/agents/<aid>/skills/<sid>/SKILL.md`). */
+ agent_id?: string;
+}
+
+/** Returns true iff the absolute path resolves to a SKILL.md inside one of
+ * the three skill roots for the given uid. */
+export function isSkillMdPath(absPath: string, uid: string): boolean {
+ return parseSkillPath(absPath, uid) !== null;
+}
+
+/** Parse a SKILL.md absolute path into `{ system, skill_id, agent_id? }`.
+ * Returns `null` if the path is not under any of the three roots, doesn't
+ * end in SKILL.md, or has an unexpected segment count. */
+export function parseSkillPath(absPath: string, uid: string): ParsedSkillPath | null {
+ if (!absPath || !uid) return null;
+ const abs = path.resolve(absPath);
+ if (path.basename(abs) !== 'SKILL.md') return null;
+
+ const a = _tryUnderRoot(abs, userSkillsDir(uid), 1);
+ if (a) return { system: 'A.custom', skill_id: a.segments[0] };
+
+ const p = _tryUnderRoot(abs, userMarketplaceSkillsDir(uid), 1);
+ if (p) return { system: 'A.platform', skill_id: p.segments[0] };
+
+ // System B: `<uid>/cloud/agents/<aid>/skills/<sid>/SKILL.md`
+ const b = _tryUnderRoot(abs, userAgentsDir(uid), 3);
+ if (b && b.segments[1] === 'skills') {
+ return { system: 'B', skill_id: b.segments[2], agent_id: b.segments[0] };
+ }
+
+ return null;
+}
+
+/** If `abs` lives under `root` with exactly `expectedDirSegments` directory
+ * segments between root and the SKILL.md file, return those segments;
+ * otherwise return null. Rejects paths that escape root via `..` (we'd
+ * see segments starting with `..` from path.relative). */
+function _tryUnderRoot(abs: string, root: string, expectedDirSegments: number): { segments: string[] } | null {
+ const rel = path.relative(path.resolve(root), abs);
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
+ const segments = rel.split(path.sep);
+ // Expected: [...dirSegments, 'SKILL.md']
+ if (segments.length !== expectedDirSegments + 1) return null;
+ if (segments[segments.length - 1] !== 'SKILL.md') return null;
+ return { segments: segments.slice(0, expectedDirSegments) };
+}
diff --git a/src/main/features/expert_signals/storage.ts b/src/main/features/expert_signals/storage.ts
new file mode 100644
index 00000000..66598f58
--- /dev/null
+++ b/src/main/features/expert_signals/storage.ts
@@ -0,0 +1,119 @@
+/**
+ * Expert signals — storage layer.
+ *
+ * Append-only daily-rotated jsonl at `<uid>/local/signals/<yyyy-mm-dd>.jsonl`.
+ * Sole writer/reader of those files; outer modules must go through
+ * `emitSignal` / `querySignals` in `./index.ts`.
+ *
+ * Writes are fire-and-forget — a disk error logs `warn` and drops the
+ * signal (NEVER throws into the caller, which is bus.ts turn-end).
+ * Phase 0 has no redaction; phase 2 (consent toggle) will add it.
+ */
+
+import * as crypto from 'node:crypto';
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+
+import { signalsDailyFile, userSignalsDir } from '../../paths';
+import { createLogger } from '../../logger';
+import { getActiveUserId } from '../users';
+
+import { Signal, SignalFilter, SignalInput } from './types';
+
+const log = createLogger('expert-signals');
+
+const QUERY_HARD_CAP = 10_000;
+const QUERY_DEFAULT_LIMIT = 1000;
+
+/** Build a Signal from input + stamped id/ts. Pure helper exposed so tests
+ * can produce deterministic records without going through emit. */
+export function buildSignal(input: SignalInput, ts?: string): Signal {
+ return {
+ id: `sig_${crypto.randomUUID()}`,
+ ts: ts || new Date().toISOString(),
+ ...input,
+ };
+}
+
+/** Append a single signal to today's jsonl. Fire-and-forget; errors are
+ * logged and swallowed. Caller (emit) must not await this — it returns void
+ * to make that obvious. */
+export function appendSignal(uid: string, input: SignalInput): void {
+ const signal = buildSignal(input);
+ const file = signalsDailyFile(uid);
+ fsp.mkdir(path.dirname(file), { recursive: true })
+ .then(() => fsp.appendFile(file, JSON.stringify(signal) + '\n'))
+ .catch((err) => {
+ log.warn(`appendSignal failed uid=${uid} type=${input.type}: ${(err as Error).message}`);
+ });
+}
+
+/** Read signals from one or more daily files and apply the filter. Scans
+ * date range [since, until); without those bounds it falls back to "today
+ * only" to keep memory bounded. */
+export async function querySignals(filter: SignalFilter = {}): Promise<Signal[]> {
+ const uid = getActiveUserId();
+ const limit = Math.min(filter.limit || QUERY_DEFAULT_LIMIT, QUERY_HARD_CAP);
+ const dates = _datesInRange(filter.since, filter.until);
+ const out: Signal[] = [];
+
+ for (const date of dates) {
+ const file = signalsDailyFile(uid, date);
+ if (!fs.existsSync(file)) continue;
+ let content: string;
+ try { content = await fsp.readFile(file, 'utf8'); }
+ catch (err) {
+ log.warn(`querySignals read failed file=${file}: ${(err as Error).message}`);
+ continue;
+ }
+ for (const line of content.split('\n')) {
+ if (!line) continue;
+ let sig: Signal;
+ try { sig = JSON.parse(line) as Signal; }
+ catch { continue; } // corrupt line — skip (don't break the whole query)
+ if (!_matches(sig, filter)) continue;
+ out.push(sig);
+ if (out.length >= limit) return out;
+ }
+ }
+ return out;
+}
+
+/** List of Date objects for each YYYY-MM-DD in [since, until). When both
+ * unset, returns `[today]` only. When one is set, the missing bound
+ * defaults to today. */
+function _datesInRange(since?: string, until?: string): Date[] {
+ const today = _atMidnight(new Date());
+ if (!since && !until) return [today];
+ const start = since ? _atMidnight(new Date(since)) : today;
+ const end = until ? _atMidnight(new Date(until)) : today;
+ const out: Date[] = [];
+ for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
+ out.push(new Date(d));
+ }
+ return out;
+}
+
+function _atMidnight(d: Date): Date {
+ const out = new Date(d);
+ out.setHours(0, 0, 0, 0);
+ return out;
+}
+
+function _matches(sig: Signal, f: SignalFilter): boolean {
+ if (f.since && sig.ts < f.since) return false;
+ if (f.until && sig.ts >= f.until) return false;
+ if (f.types && f.types.length && !f.types.includes(sig.type)) return false;
+ if (f.cid && sig.cid !== f.cid) return false;
+ if (f.turn_id && sig.turn_id !== f.turn_id) return false;
+ if (f.aid !== undefined && sig.aid !== f.aid) return false;
+ return true;
+}
+
+/** Test seam: silence the warn log (used by unit tests to suppress IO errors
+ * on tmp dirs they tear down). Default no-op. */
+export const _internals = {
+ buildSignal, appendSignal,
+ ensureDir: (uid: string) => fs.mkdirSync(userSignalsDir(uid), { recursive: true }),
+};
diff --git a/src/main/features/expert_signals/turn_hooks.ts b/src/main/features/expert_signals/turn_hooks.ts
new file mode 100644
index 00000000..7ca7d7ec
--- /dev/null
+++ b/src/main/features/expert_signals/turn_hooks.ts
@@ -0,0 +1,229 @@
+/**
+ * Chokepoint glue between bus.ts / IPC handlers and the signal extractors.
+ *
+ * Outer modules (bus, IPC) call these two functions; they do all the
+ * emit / cache management internally. Keeps bus.ts free of extractor
+ * imports and signal-shape knowledge.
+ *
+ * In-memory `_lastAgentMsg` cache pairs an agent's final message with the
+ * next user reply for text-class signal extraction — avoids a per-user-msg
+ * jsonl re-read. App restart clears the cache; the first user reply after
+ * restart misses its text signals (acceptable v0 trade-off; phase 1+ can
+ * backfill on boot if a consumer needs it).
+ */
+
+import { emitSignal } from './index';
+import { extractTextSignals } from './extractors/text';
+import {
+ buildToolFailureSignal,
+ buildSkillAdvertisedSignal,
+ buildSkillInvokedSignal,
+} from './extractors/event';
+import {
+ scheduleSilenceCheck,
+ cancelSilenceCheck,
+} from './extractors/silence';
+import { createLogger } from '../../logger';
+import type { SkillSystem, SkillInvokeTrigger } from './types';
+
+const log = createLogger('expert-signals:hooks');
+
+// `#core-agent` must be loaded with dynamic `await import` — top-level
+// static import triggers `ERR_PACKAGE_PATH_NOT_EXPORTED` from pi-ai (no
+// `exports` field in its package.json). See PC/CLAUDE.md §3. Lazy singleton
+// caches the resolved fn so we pay the import cost once per process.
+let _detectFn: ((s: string) => boolean) | null = null;
+async function _getDetectUserCorrection(): Promise<(s: string) => boolean> {
+ if (_detectFn) return _detectFn;
+ const ca = await import('#core-agent');
+ _detectFn = ca.detectUserCorrection;
+ return _detectFn;
+}
+
+interface LastAgentMsg {
+ id: string;
+ /** Sender actor id — `'commander'` or an agent id; `aid` for the signal
+ * is `null` for commander, the id otherwise. */
+ from: string;
+ text: string;
+}
+
+const _lastAgentMsg = new Map<string, LastAgentMsg>();
+function _key(uid: string, cid: string): string { return `${uid}:${cid}`; }
+
+/**
+ * Per-turn skill-attribution buffer. Bus.ts owns one of these per actor
+ * turn (see `createSkillTurnBuffer`) and bridges its `record*` methods
+ * into ChatOptions.{onSkillAdvertised,onSkillInvoked}. `drainAndEmit`
+ * fires at turn-end, after we know the agent message id (= turn_id) but
+ * before `onAgentTurnEnd` schedules silence + text-signal pairing.
+ *
+ * Why a dedicated buffer (not an ad-hoc local in bus.ts): the dedup +
+ * skill_advertised group-by-system + signal emission logic shouldn't live
+ * inline in bus.ts. Keeping it here matches the chokepoint discipline
+ * (PC/CLAUDE.md §4 constraint 9): bus.ts gets callback shims; emit logic
+ * stays in expert_signals/.
+ */
+export interface SkillTurnBuffer {
+ recordAdvertised(skill_id: string, system: SkillSystem): void;
+ recordInvoked(skill_id: string, system: SkillSystem, trigger: SkillInvokeTrigger): void;
+ drainAndEmit(args: { uid: string; cid: string; aid: string | null; turn_id: string; msg_ids: string[] }): void;
+}
+
+export function createSkillTurnBuffer(): SkillTurnBuffer {
+ // `Set<string>` keyed on `${system}${skill_id}` — bus may call the
+ // recorders multiple times (e.g. ChatOptions wired to two layers); dedup
+ // keeps the emitted signal payload clean. Invoked uses the same shape
+ // since same SKILL.md can be read more than once per turn.
+ const advertised = new Set<string>();
+ const invoked = new Set<string>();
+ // Compact (system, id) key — `::` is safe because neither component
+ // contains `::`: system labels are A.custom / A.platform / B; ids match
+ // kebab/snake or 12-hex per CLAUDE.md §6.
+ const enc = (sys: SkillSystem, id: string) => sys + '::' + id;
+ const dec = (k: string): { system: SkillSystem; skill_id: string } => {
+ const i = k.indexOf('::');
+ return { system: k.slice(0, i) as SkillSystem, skill_id: k.slice(i + 2) };
+ };
+
+ return {
+ recordAdvertised(skill_id, system) {
+ if (!skill_id) return;
+ advertised.add(enc(system, skill_id));
+ },
+ recordInvoked(skill_id, system /* trigger fixed to 'read_file' for v0 */) {
+ if (!skill_id) return;
+ invoked.add(enc(system, skill_id));
+ },
+ drainAndEmit({ uid, cid, aid, turn_id, msg_ids }) {
+ if (!turn_id) {
+ // Without a turn id (= agent msg id) the signal can't be joined to
+ // anything else — drop instead of emitting a useless record.
+ return;
+ }
+ // skill_advertised: one signal per (system) carrying every id from
+ // that catalog. Caller never asks for the dispatch_to msg ids of
+ // each individual skill — the group-by-system rollup is the analyst-
+ // friendly shape.
+ const bySystem = new Map<SkillSystem, string[]>();
+ for (const k of advertised) {
+ const { system, skill_id } = dec(k);
+ const list = bySystem.get(system) || [];
+ list.push(skill_id);
+ bySystem.set(system, list);
+ }
+ for (const [system, skill_ids] of bySystem) {
+ emitSignal(uid, buildSkillAdvertisedSignal({
+ cid, aid, turn_id, system, skill_ids, msg_ids,
+ }));
+ }
+ // skill_invoked: one signal per distinct (system, skill_id). Trigger
+ // is fixed to `read_file` in v0 (the only path we hook today); the
+ // builder accepts an enum for future template / subagent loads.
+ for (const k of invoked) {
+ const { system, skill_id } = dec(k);
+ emitSignal(uid, buildSkillInvokedSignal({
+ cid, aid, turn_id, system, skill_id, trigger: 'read_file', msg_ids,
+ }));
+ }
+ advertised.clear();
+ invoked.clear();
+ },
+ };
+}
+
+/**
+ * Bus calls this AFTER it has enqueued the actor's final message. Handles:
+ * - cache the agent text for the next user reply's text-signal pairing
+ * - emit `tool_failure` when this turn ended with an unrecovered error
+ * - schedule a silence check (cancelled by `onUserMessage` if user replies)
+ *
+ * v0 simplification: `tool_failure` uses the bus's `errText` summary as a
+ * proxy for "unrecovered tool error"; phase 1 will scan the session jsonl
+ * for fine-grained `tool_result.isError=true` entries with tool_name.
+ */
+export function onAgentTurnEnd(args: {
+ uid: string;
+ cid: string;
+ actorId: string;
+ isCommander: boolean;
+ agentMsg: { id: string; text: string };
+ errText?: string;
+}): void {
+ try {
+ const aid = args.isCommander ? null : args.actorId;
+ const turn_id = args.agentMsg.id;
+ const trimmed = (args.agentMsg.text || '').trim();
+
+ if (trimmed) {
+ _lastAgentMsg.set(_key(args.uid, args.cid), {
+ id: args.agentMsg.id,
+ from: args.actorId,
+ text: args.agentMsg.text,
+ });
+ }
+
+ if (args.errText && args.errText.trim()) {
+ emitSignal(args.uid, buildToolFailureSignal({
+ cid: args.cid, aid, turn_id,
+ tool_name: 'unknown',
+ error_excerpt: args.errText,
+ msg_ids: [args.agentMsg.id],
+ }));
+ }
+
+ if (trimmed) {
+ scheduleSilenceCheck({
+ uid: args.uid, cid: args.cid, aid, turn_id,
+ msg_ids: [args.agentMsg.id],
+ });
+ }
+ } catch (err) {
+ log.warn(`onAgentTurnEnd threw uid=${args.uid} cid=${args.cid}: ${(err as Error).message}`);
+ }
+}
+
+/**
+ * Bus calls this when a user message has been enqueued. Handles:
+ * - cancel any pending silence check (user replied)
+ * - run `detectUserCorrection` once and extract text-class signals against
+ * the cached last agent message
+ *
+ * Returns `correctionDetected` so the caller can wire it into the agent's
+ * RunMetrics.userCorrections (see plan §6.1: same boolean, two consumers,
+ * no double-judgment).
+ */
+export async function onUserMessage(args: {
+ uid: string;
+ cid: string;
+ userMsg: { id: string; text: string };
+}): Promise<{ correctionDetected: boolean }> {
+ try {
+ cancelSilenceCheck(args.uid, args.cid);
+ const prev = _lastAgentMsg.get(_key(args.uid, args.cid));
+ if (!prev) return { correctionDetected: false };
+
+ const detect = await _getDetectUserCorrection();
+ const correctionDetected = detect(args.userMsg.text);
+
+ const signals = extractTextSignals({
+ cid: args.cid,
+ aid: prev.from === 'commander' ? null : prev.from,
+ turn_id: prev.id,
+ agent_last_text: prev.text,
+ user_msg: args.userMsg.text,
+ msg_ids: [prev.id, args.userMsg.id],
+ correction_detected: correctionDetected,
+ });
+ for (const sig of signals) emitSignal(args.uid, sig);
+ return { correctionDetected };
+ } catch (err) {
+ log.warn(`onUserMessage threw uid=${args.uid} cid=${args.cid}: ${(err as Error).message}`);
+ return { correctionDetected: false };
+ }
+}
+
+/** Test seam — clear in-memory cache between cases. */
+export function _clearAgentMsgCache(): void {
+ _lastAgentMsg.clear();
+}
diff --git a/src/main/features/expert_signals/types.ts b/src/main/features/expert_signals/types.ts
new file mode 100644
index 00000000..2fc3e766
--- /dev/null
+++ b/src/main/features/expert_signals/types.ts
@@ -0,0 +1,141 @@
+/**
+ * Expert signals — shared types.
+ *
+ * Signals are user-behavior records produced at known chokepoints (bus
+ * turn-end / retry-skip IPC / form submit / silence timer). They feed
+ * downstream reflection / patch suggester / critic (phase 1+). Each signal
+ * is a single jsonl line under `<uid>/local/signals/<yyyy-mm-dd>.jsonl`.
+ *
+ * See `docs/plans/expert-signals-phase-0.md` for the rule catalog.
+ */
+
+/** Phase 0 signal kinds (T0 system events + T1 text rules).
+ * Phase 1 adds T2 semantic kinds (accept_with_caveat / domain_constraint_revealed / …).
+ * When adding a new T0/T1 kind: extend this union, add an extractor case,
+ * add a positive + negative fixture (CLAUDE.md §9). */
+export type SignalType =
+ | 'retry' // T0: plan rail "Retry" clicked
+ | 'skip' // T0: plan rail "Skip" clicked
+ | 'form_left_blank' // T0: required field unfilled / default unchanged on submit
+ | 'silence' // T0: agent message followed by ≥ N min of no user response
+ | 'tool_failure' // T0: session jsonl has tool_result.isError=true unrecovered
+ | 'accept' // T1: silent or explicit acceptance of agent output
+ | 'correction' // T1: user message matched correction patterns
+ | 'reject' // T1: user message matched rejection patterns
+ | 'edit' // T1: user message token-diffed significantly from agent's last text
+ | 'skill_advertised' // T0: skills entered system prompt index at turn start (per system)
+ | 'skill_invoked' // T0: agent read_file'd a SKILL.md body during the turn
+ | 'agent_dispatched'; // T0: commander dispatched ready plan steps (candidates + dispatched)
+
+/** Which skill catalog produced a `skill_advertised` / `skill_invoked` signal.
+ * Three values, not two — `A.custom` (cloud/skills/) and `A.platform`
+ * (local/marketplace/skills/) live at different roots and patch suggester
+ * treats them differently (cloud edit vs marketplace republish). `B` is
+ * the agent's own SkillStore (`cloud/agents/<aid>/skills/`). */
+export type SkillSystem = 'A.custom' | 'A.platform' | 'B';
+
+/** How a skill body was reached. Reserved enum — phase 2 template system
+ * may add `subagent_load`. */
+export type SkillInvokeTrigger = 'read_file';
+
+/** Source layer of the extractor. Phase 0 is all `event`; phase 1 adds
+ * semantic and `event_then_semantic` (LLM-corrected event signal). */
+export type SignalSource = 'event' | 'semantic' | 'event_then_semantic';
+
+/** Per-signal extractor version stamp. Bump per extractor when the rule
+ * changes meaningfully so downstream consumers can re-process / segregate
+ * by version. */
+export const EXTRACTOR_VERSION = {
+ event: '[email protected]',
+ silence: '[email protected]',
+ skill_attribution: '[email protected]',
+ agent_dispatch: '[email protected]',
+} as const;
+
+export interface SignalDelta {
+ /** Levenshtein-ish character distance between pre and post text. */
+ edit_distance?: number;
+ /** Patterns that matched (e.g. `['不对', '应该']`). */
+ matched_patterns?: string[];
+ /** Coarse classifier for downstream rerank. */
+ edit_type?: 'minor' | 'major_rewrite';
+ /** Skill source system for skill_advertised / skill_invoked. */
+ system?: SkillSystem;
+ /** skill_advertised: the full set of ids advertised by this `system` in this turn. */
+ skill_ids?: string[];
+ /** skill_invoked: which skill was read. (`skill_ids` is plural for advertised; this is singular for invoked.) */
+ skill_id?: string;
+ /** skill_invoked: how the body was reached. */
+ trigger?: SkillInvokeTrigger;
+ /** agent_dispatched: ready steps the commander considered this dispatch round (aids). */
+ candidates?: string[];
+ /** agent_dispatched: subset actually woken in this dispatch round. */
+ dispatched?: string[];
+ /** agent_dispatched: the parallel_group key (null = solo step). */
+ parallel_group?: string | null;
+}
+
+export interface SignalContextRef {
+ /** Group-chat message ids that contextualize this signal. Downstream uses
+ * this to reconstruct an episode without storing the full text here. */
+ msg_ids: string[];
+}
+
+export interface SignalTextSlice {
+ /** sha1 of the full text — for dedup / fingerprinting. */
+ text_hash?: string;
+ /** First 200 chars; full text remains in `<cid>.jsonl`. */
+ text_excerpt?: string;
+ /** For text-class signals: the user message that triggered the rule. */
+ user_msg?: string;
+}
+
+export interface Signal {
+ /** sig_<uuid>. */
+ id: string;
+ /** ISO 8601 timestamp at emit time. */
+ ts: string;
+ type: SignalType;
+ source: SignalSource;
+ cid: string;
+ /** Agent-id the signal is attributed to. `null` = commander-scope. */
+ aid: string | null;
+ /** The agent message id this signal **reacts to or is produced by**.
+ * - agent-side (`tool_failure / silence / skill_advertised / skill_invoked`):
+ * the agent's own final message id for that turn.
+ * - user-reaction (`correction / reject / accept / edit`):
+ * the previous agent message id being reacted to.
+ * - dispatch (`agent_dispatched`): the commander msg id that produced the
+ * plan_set decision.
+ * - `form_left_blank`: the agent msg id that posted the form.
+ * - `retry / skip`: the source agent msg id of the output being retried
+ * (since 2026-05-19; was synthetic `<cid>:plan:<step>` before — break
+ * rebased; consumers count repeat retries via `metadata.step_index`).
+ * Direct JOIN on `turn_id` recovers cross-signal causality
+ * (skill_invoked × correction, retry × tool_failure, …). See
+ * `docs/plans/expert-signals-skill-attribution.md` §3.4. */
+ turn_id: string;
+ pre?: SignalTextSlice;
+ post?: SignalTextSlice;
+ delta?: SignalDelta;
+ context_ref: SignalContextRef;
+ /** Tag of the extractor that produced this signal (see EXTRACTOR_VERSION). */
+ extractor_version: string;
+ /** Optional kind-specific scratchpad. Avoid putting full text here. */
+ metadata?: Record<string, unknown>;
+}
+
+/** Filter shape for querySignals. All fields optional; combine = AND. */
+export interface SignalFilter {
+ since?: string; // ISO; inclusive
+ until?: string; // ISO; exclusive
+ types?: SignalType[];
+ aid?: string | null;
+ cid?: string;
+ turn_id?: string;
+ limit?: number; // default 1000; hard cap 10_000
+}
+
+/** New-signal input — `id` and `ts` are filled by emit. */
+export type SignalInput = Omit<Signal, 'id' | 'ts'>;
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 79101409..eab44d8e 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -54,6 +54,7 @@ import { isAgentEnabled } from '../component_enabled';
import { buildLanguageDirective, descriptionLang, t } from '../../i18n';
import * as marketplaceFeat from '../marketplace';
import { readInstalls } from '../marketplace_installs';
+import { createSkillTurnBuffer } from '../expert_signals/turn_hooks';
const log = createLogger('group_chat.bus');
@@ -116,6 +117,11 @@ export type GroupEvent =
* up as a stuck "thinking" bubble when commander's turn ends silently. */
| { type: 'message'; cid: string; msg: GroupMessage; turn_end?: boolean }
| { type: 'process'; cid: string; actor: string; data: Record<string, unknown> }
+ /** A `create_artifact` tool call finished writing its bundle. The final
+ * end-of-turn message still carries `msg.artifacts` for persistence; this
+ * live event lets the renderer mount the iframe immediately instead of
+ * waiting for the whole actor turn to finish. */
+ | { type: 'artifact_created'; cid: string; actor: string; artifact: { id: string; title: string; agent_id: string } }
| { type: 'plan_changed'; cid: string }
| { type: 'state_changed'; cid: string; state: Awaited<ReturnType<typeof readState>> }
| { type: 'member_joined'; cid: string; actor: Actor }
@@ -273,6 +279,19 @@ export function isQuiescent(uid: string, cid: string): boolean {
return true;
}
+export function runtimeSnapshot(uid: string, cid: string): { processing: boolean; inFlight: string[] } {
+ const s = _cids.get(cidKey(uid, cid));
+ if (!s) return { processing: false, inFlight: [] };
+ const inFlight: string[] = [];
+ for (const [, w] of s.workers) {
+ if (w.running) inFlight.push(w.actor.id);
+ }
+ return {
+ processing: !isQuiescent(uid, cid),
+ inFlight,
+ };
+}
+
/** Recompute the on-disk `status` field based on actual worker / queue
* state. Honors the sticky `aborted` flag — once aborted, ONLY an
* explicit USER `enqueue` clears it (so a follow-up worker reply
@@ -695,11 +714,15 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
// commander in `to`, so it goes through the regular dispatch loop above.
// User-driven reconcile: when user enqueues, plan_executor needs a chance
- // to mark a `user`-assignee step as done and dispatch downstream. Worker-
- // driven reconcile already runs in runTurn for agent/commander turns.
- // Fire-and-forget — reconcile is idempotent and shouldn't block enqueue.
+ // to mark a `user`-assignee step as done and dispatch downstream. This is
+ // part of the send transaction, not a background side effect: the IPC
+ // send-stream subscribes before calling send(), and it must not return until
+ // the immediate plan handoff (user step → next agent / commander) has queued
+ // its work. Otherwise the renderer can close the stream between the user
+ // echo and the downstream dispatch, which is exactly how form submissions
+ // ended up as fake loading bubbles until history polling caught up.
if (fromActorId === USER_ID) {
- void planExecutor.reconcile(uid, cid, {
+ await planExecutor.reconcile(uid, cid, {
finishedActorId: USER_ID,
finishedMessage: { id: msgId, text: rewrittenText, files: [], failed: false },
}).catch((err) => log.warn(`plan reconcile (user) threw cid=${cid}: ${(err as Error).message}`));
@@ -937,7 +960,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
let cliAgent: import('../agents').Agent | null = null;
if (isCommander) {
systemPrompt = await buildCommanderSystemPrompt(uid, cid, turnProjectScope?.agents ?? null);
- extraTools = await buildCommanderExtraTools(state, w);
+ 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).
} else {
@@ -982,6 +1005,14 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// Streaming.
const { streamChatWithModel } = await import('../../model/client');
+ // Per-turn skill-attribution buffer. Records skill_advertised at runner
+ // build time (System A via skill-registry, System B via SkillStore) and
+ // skill_invoked at each successful `read_file` of a SKILL.md. Drained
+ // at turn-end below using the persisted agent msg id as `turn_id`, so
+ // downstream signals JOIN cleanly with text/tool_failure/retry on the
+ // same turn. Silent turns (no persisted message) drop the buffer — see
+ // expert-signals-skill-attribution plan §3.4 + `turn_hooks.ts`.
+ const skillBuffer = createSkillTurnBuffer();
// Per-turn list — feeds the green-chip "files produced" bubble. The
// conversation-scoped `state.producedPaths` is what uniquify consults
// for ownership; we keep this Set per turn purely for UI surfacing.
@@ -1000,7 +1031,15 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// one as a sandboxed `<iframe>` (`chat-app://`); `agent_id` = this actor,
// the routing target for a user→artifact interaction result.
const turnArtifacts: Array<{ id: string; title: string }> = [];
- const onArtifactCreated = (a: { id: string; title: string }) => { turnArtifacts.push(a); };
+ const onArtifactCreated = (a: { id: string; title: string }) => {
+ turnArtifacts.push(a);
+ emit(state, {
+ type: 'artifact_created',
+ cid,
+ actor: actor.id,
+ artifact: { id: a.id, title: a.title, agent_id: actor.id },
+ });
+ };
let finalText = '';
// Mirror of every text delta we forwarded to the renderer this turn.
// Used as the salvage source when the user aborts mid-stream — the
@@ -1065,21 +1104,19 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// conventions and don't need that scoping. Override here:
const userWorkspace = await import('../user_workspace');
const wsRoot = userWorkspace.getWorkspacePath(uid, turnProjectId);
- // Coding agents (claude / codex) honour the per-conversation
- // `coding_project_dir` when set so the CLI runs inside the user's
- // actual project; non-coding CLIs always use the workspace. The
- // chip in the conversation surface lets the user set/change the
- // dir mid-conversation. We also defensively check the directory
- // exists and is a real dir — if it vanished between picker and
- // dispatch we fall back rather than failing the run.
+ // Coding agents (claude / codex) initialise the per-conversation
+ // `coding_project_dir` from the agent detail page's project-dir
+ // setting. Missing setting = effective workspace. Once a
+ // conversation has a dir, later turns keep using it; the agent can
+ // still ask the user to switch through the standard directory form.
+ // Non-coding CLIs always use the workspace. We defensively check
+ // the directory exists — if it vanished we fall back rather than
+ // failing the run.
let cliWorkingDir = wsRoot;
if (agentsFeat.cliIsCodingAgent(cliAgent.runtime?.kind === 'cli' ? cliAgent.runtime.cli : '')) {
- // Default + workspace-sync: on the first coding-agent turn the
- // user shouldn't have to pick a directory just to start; default
- // to their effective workspace. On later turns, follow workspace
- // changes silently — unless the user has explicitly picked
- // something different through the input-form (sticky).
- await _syncCodingProjectDirWithWorkspace(uid, cid, wsRoot);
+ const dirInfo = agentsFeat.getCliProjectDirInfoForAgent(uid, cliAgent, turnProjectId);
+ cliWorkingDir = dirInfo.effective_path;
+ await _initializeCodingProjectDir(uid, cid, dirInfo);
const st = await import('./state');
const stateFile = await st.readState(uid, cid);
const projDir = stateFile.coding_project_dir;
@@ -1143,6 +1180,8 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
onFileWritten,
hasProducedPath,
onArtifactCreated,
+ onSkillAdvertised: (id, sys) => skillBuffer.recordAdvertised(id, sys),
+ onSkillInvoked: (id, sys, trig) => skillBuffer.recordInvoked(id, sys, trig),
cacheRetention: 'short',
abortSignal: w.abortController.signal,
readOnlyExtraRoots: [...skillRoots, ...agentRoots],
@@ -1512,8 +1551,9 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
}
}
+ let persistedMsg: GroupMessage | null = null;
if (outcome.kind === 'persist') {
- await enqueue({
+ persistedMsg = await enqueue({
uid, cid,
fromActorId: actor.id,
text: outcome.text,
@@ -1572,6 +1612,14 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
if (actor.kind === 'commander' && w.pendingDispatches && w.pendingDispatches.length) {
const pending = w.pendingDispatches;
w.pendingDispatches = undefined;
+ // Inherit the commander turn's user-uploaded attachments so the recipient
+ // worker sees the same image / file bytes the commander saw. Without this
+ // a worker honestly answers "I can't see the image" because turnImages
+ // only fires when `item.attachments` is populated. Plan-step dispatches
+ // get the same inheritance via PlanFile.initial_attachments (persisted
+ // because steps live across worker turn boundaries); dispatch_to is one-
+ // shot so per-turn flush is enough.
+ const inheritedAttachments = item.attachments;
for (const d of pending) {
try {
await enqueue({
@@ -1580,6 +1628,9 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
text: d.message,
forceTo: [d.to],
dispatch: true,
+ ...(inheritedAttachments && inheritedAttachments.length
+ ? { attachments: inheritedAttachments }
+ : {}),
});
} catch (err) {
log.warn(`dispatch_to flush failed cid=${cid} to=${d.to}: ${(err as Error).message}`);
@@ -1587,6 +1638,20 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
}
}
+ // Expert-signals: drain skill_advertised / skill_invoked using the
+ // persisted msg id as turn_id (per turn_id convention — see
+ // PC/CLAUDE.md §4 constraint 9 + expert-signals plan §3.4). Silent
+ // turns drop the buffer; CLI agents bypass SkillLoader so the buffer
+ // is empty for them and the drain is a no-op.
+ if (persistedMsg) {
+ skillBuffer.drainAndEmit({
+ uid, cid,
+ aid: actor.kind === 'commander' ? null : actor.id,
+ turn_id: persistedMsg.id,
+ msg_ids: [persistedMsg.id],
+ });
+ }
+
await _syncStateStatus(state);
log.info(
`turn-end user=${uid} cid=${cid} actor=${actor.id} ms=${Date.now() - turnStartedAt}`
@@ -1740,7 +1805,7 @@ async function buildAgentsIndexBlock(uid: string, allowedIds?: readonly string[]
async function buildAgentInGroupSystemPrompt(
_uid: string,
- agent: { name?: string; description?: string; workflow?: string; agent_id: string; inputs?: unknown },
+ agent: { name?: string; description?: string; workflow?: string; agent_id: string; inputs?: unknown; output_format?: string },
workingDir: string,
): Promise<string> {
const { prompts } = await import('../../prompts/loader');
@@ -1766,11 +1831,35 @@ async function buildAgentInGroupSystemPrompt(
workflow: (agent.workflow || '').trim() || '(not provided)',
inputs_schema: inputsSchemaJson || '(none)',
working_dir: workingDir,
+ output_format_hint: buildOutputFormatHint(agent.output_format),
});
const shared = prompts.load('chat_shared_rules', {});
return appendLanguageDirective(concatSharedRules(main, shared));
}
+/** Render the agent's `output_format` preference as a one-line worker prompt
+ * hint. Sits in the `## Runtime injection` tail (most-volatile slot per
+ * PC/CLAUDE.md §3 prompt-md cache layout). `'auto'` (legacy) and missing both
+ * produce an empty string — old agents authored before the redesign keep
+ * unconstrained behavior until the user explicitly picks a value. `'artifact'`
+ * is the renamed `'allow_artifacts'`; the old key is accepted as an alias for
+ * on-disk back-compat (specs written by pre-redesign builds). See
+ * `chat_shared_rules.md` "Output formats" for the underlying rule. */
+function buildOutputFormatHint(format: string | undefined): string {
+ switch (format) {
+ case 'markdown_only':
+ return '### Output format\nThis agent is configured **markdown-only**: do NOT emit `:::dashboard` blocks or call `create_artifact`. Plain markdown only.';
+ case 'dashboard':
+ return '### Output format\nThis agent is configured for **dashboard output**: prefer `:::dashboard` for structured snapshots (KPIs, tables, alerts, timelines); do NOT call `create_artifact`.';
+ case 'artifact':
+ case 'allow_artifacts':
+ return '### Output format\nThis agent is configured to **allow artifacts**: prefer `:::dashboard` for structured snapshots; reach for `create_artifact` when interactivity actually matters.';
+ case 'auto':
+ default:
+ return '';
+ }
+}
+
// ── Commander tools (plan_set / marketplace / dispatch) ─────────────────
function _toolJson(data: unknown): { content: string } {
@@ -1814,6 +1903,7 @@ function _compactMarketplaceItem(
category: item.category || '',
version: item.version,
published_at: item.published_at,
+ ...(typeof item.updated_at === 'number' ? { updated_at: item.updated_at } : {}),
create_uid: item.create_uid || '',
download_count: item.download_count || 0,
installed,
@@ -1844,7 +1934,7 @@ function _marketplaceSearchTerms(query: string): string[] {
push(query);
for (const token of query.split(/[\s,,;;::|/]+/g)) {
push(token);
- const runs = token.match(/[\u3400-\u9fff]{2,}/g) || [];
+ const runs = token.match(/[㐀-鿿]{2,}/g) || [];
hanRuns.push(...runs);
for (const run of runs) {
for (const term of commonHanTerms) {
@@ -1861,7 +1951,17 @@ function _marketplaceSearchTerms(query: string): string[] {
return out.slice(0, 12);
}
-async function buildCommanderExtraTools(state: CidState, w: WorkerState): Promise<AgentTool[]> {
+
+async function buildCommanderExtraTools(
+ state: CidState,
+ w: WorkerState,
+ // Attachments on the current commander turn's source item — passed through
+ // to plan_set so the plan persists them under `initial_attachments`. Worker
+ // dispatches in subsequent reconciles read it back from the plan so image /
+ // file bytes follow the dispatch chain. Same flow as `dispatch_to` flush,
+ // but persisted because plan steps live across worker turn boundaries.
+ currentTurnAttachments?: string[],
+): Promise<AgentTool[]> {
const { uid, cid } = w;
const tools: AgentTool[] = [];
tools.push({
@@ -1928,6 +2028,9 @@ async function buildCommanderExtraTools(state: CidState, w: WorkerState): Promis
...(typeof input?.initial_message === 'string' && input.initial_message.trim()
? { initial_message: String(input.initial_message) }
: {}),
+ ...(currentTurnAttachments && currentTurnAttachments.length
+ ? { initial_attachments: currentTurnAttachments.slice() }
+ : {}),
steps: raw.filter((s) => s && typeof s.title === 'string' && s.title.trim() && typeof s.assignee === 'string' && s.assignee.trim())
.map((s) => ({
title: String(s.title),
@@ -2131,6 +2234,7 @@ async function buildCommanderExtraTools(state: CidState, w: WorkerState): Promis
create_uid: { type: 'string', description: 'Author uid from marketplace_search; "0" means official.' },
version: { type: 'string', description: 'Version from marketplace_search.' },
published_at: { type: 'number', description: 'Published timestamp from marketplace_search.' },
+ updated_at: { type: 'number', description: 'Updated timestamp from marketplace_search; include when present.' },
reason: {
type: 'string',
description: 'Short user-facing reason this resource helps the current task.',
@@ -2152,6 +2256,8 @@ async function buildCommanderExtraTools(state: CidState, w: WorkerState): Promis
const reason = _trimText(input?.reason, 800);
if (!reason) return _toolError('`reason` is required');
const searchMeta = w.marketplaceSearchResults?.get(`${kind}:${id}`);
+ const rawUpdatedAt = input?.updated_at ?? searchMeta?.updated_at;
+ const updatedAt = rawUpdatedAt == null ? NaN : Number(rawUpdatedAt);
const icon = kind === 'agent'
? (_trimText(input?.icon, 64) || _trimText(searchMeta?.icon, 64))
: '';
@@ -2204,6 +2310,7 @@ async function buildCommanderExtraTools(state: CidState, w: WorkerState): Promis
...(createUid ? { create_uid: createUid } : {}),
version,
published_at: publishedAt,
+ ...(Number.isFinite(updatedAt) ? { updated_at: updatedAt } : {}),
reason,
status: 'pending',
requested_at: nowIso(),
@@ -2416,6 +2523,7 @@ planExecutor.bindBusHooks({
...(params.forceTo ? { forceTo: params.forceTo } : {}),
...(typeof params.triggered_step === 'number' ? { triggered_step: params.triggered_step } : {}),
...(params.dispatch ? { dispatch: true } : {}),
+ ...(params.attachments && params.attachments.length ? { attachments: params.attachments } : {}),
...(params.form ? { form: params.form } : {}),
});
},
@@ -2469,56 +2577,38 @@ planExecutor.bindBusHooks({
// ── CLI agent turn ────────────────────────────────────────────────────────
//
// CLI-backed agents replace the LLM stream loop in runTurn. We pack the
-// agent's full visibility slice + the dispatched message + any user
-// attachments into a single prompt, spawn the configured CLI in the
-// user's workspace, and stream events into the same `process` rail the
-// renderer already understands. The final body is the CLI's last
-// "result" text — assigned into runTurn's `finalText` so plan_executor /
-// post-turn enqueue keep working unchanged.
+// dispatched message + any user attachments into a single prompt, spawn
+// the configured CLI in the user's workspace, and stream events into the
+// same `process` rail the renderer already understands. The final body
+// is the CLI's last "result" text — assigned into runTurn's `finalText`
+// so plan_executor / post-turn enqueue keep working unchanged.
//
-// Stateless on purpose: every dispatch starts a fresh CLI run. Session
-// continuity (`--resume`) is a future optimisation; for now the slice is
-// the source of truth.
+// CLI continuity normally belongs to the CLI itself (`--resume` / thread
+// resume), so the host prompt sends only the current task plus lightweight
+// runtime context (attachments, cwd-switch protocol).
+// Exception: if we have to start a fresh CLI session after this agent already
+// has visible history (for example cwd changed and the old cwd-keyed session
+// id was cleared), we bridge that prior visible transcript once.
const CLI_PROMPT_MAX_BYTES = 200 * 1024;
-/** Default + workspace-sync for the coding-agent project directory.
- *
- * Two cases the user expects to "just work":
- * 1. First dispatch in a fresh conv: we shouldn't pop a directory
- * picker just to start — the user already chose a workspace,
- * use that.
- * 2. User switches the workspace mid-conversation (chip in the
- * chat surface): the next coding-agent turn should follow.
+/** Initialise the coding-agent project directory for a conversation.
*
- * Either case = "auto-set" with `explicit=false`. Once the user
- * picks a different directory through the input-form picker
- * (form-submit hook flips `explicit=true`), workspace switches no
- * longer override their choice. Caller must already have established
- * this is a coding agent (the explicit flag is meaningless for
- * non-coding CLIs that don't honour `coding_project_dir`). */
-async function _syncCodingProjectDirWithWorkspace(
- uid: string, cid: string, wsPath: string,
+ * The source is the agent detail page's local project-dir setting:
+ * custom override if present, otherwise the effective workspace for
+ * this conversation/project. This runs only while the conversation has
+ * no `coding_project_dir`; once set, that cwd stays stable for the
+ * conversation until the user explicitly switches it through the
+ * directory form. */
+async function _initializeCodingProjectDir(
+ uid: string, cid: string, info: agentsFeat.AgentCliProjectDirInfo,
): Promise<void> {
const cur = await readState(uid, cid);
- if (cur.coding_project_dir_explicit) return; // sticky
- if (cur.coding_project_dir === wsPath) return; // already in sync
- const oldDir = cur.coding_project_dir || '';
- await setCodingProjectDir(uid, cid, wsPath, { explicit: false });
- if (oldDir && oldDir !== wsPath) {
- // CLI session bindings reference the OLD cwd. claude code keys
- // sessions by cwd (`~/.claude/projects/<encoded-cwd>/<id>.jsonl`),
- // so resuming a stale id at the new cwd fails with
- // "No conversation found". Drop bindings preemptively so the
- // next dispatch goes through the full-slice replay path —
- // user-visible conversation continues seamlessly because
- // `_buildCliPrompt` includes the slice when `resuming=false`.
- const cliSessions = await import('../local_agents/sessions');
- await cliSessions.clearForConversation(uid, cid);
- log.info(`coding cwd changed cid=${cid} ${oldDir} → ${wsPath} — cleared cli sessions`);
- } else {
- log.info(`coding project_dir auto-set cid=${cid} → ${wsPath}`);
- }
+ if (cur.coding_project_dir) return;
+ const target = info.effective_path;
+ if (!target) return;
+ await setCodingProjectDir(uid, cid, target, { explicit: info.mode === 'custom' && info.exists });
+ log.info(`coding project_dir initialised cid=${cid} → ${target}`);
}
/** Build an `<agent-input-form>` block listing the agent's required
@@ -2582,17 +2672,19 @@ async function _runCliAgentTurn(opts: {
if (formBlock) return { text: formBlock };
// Look up any prior CLI session bound to this (cid, aid, cli). If
- // present, we ask the CLI to resume it (claude: `--resume <id>`)
- // and skip replaying the visibility slice in the prompt — the CLI
- // already remembers the prior turns. First dispatch / fresh CLI
- // swap → null → we replay the slice as before. Saves significant
- // tokens and round-trip latency on long conversations.
+ // present, we ask the CLI to resume it (claude: `--resume <id>`,
+ // codex: `thread/resume`). With a valid resume handle, the prompt stays
+ // current-turn-only: CLI agents persist their own conversation records,
+ // and duplicating host chat history here bloats context and can confuse
+ // the CLI's native memory. Without a handle, but with prior visible
+ // turns, we bridge that transcript into the fresh CLI session.
const cliSessions = await import('../local_agents/sessions');
const resumeSessionId = await cliSessions.getSessionId(
opts.uid, opts.cid, opts.agent.agent_id, runtime.cli,
);
+ const bridgeHistory = !resumeSessionId && _hasPriorVisibleCliHistory(opts.item, opts.slice);
const promptText = await _buildCliPrompt(
- opts.uid, opts.cid, opts.agent, opts.item, opts.slice, !!resumeSessionId,
+ opts.uid, opts.cid, opts.agent, opts.item, opts.slice, bridgeHistory,
);
// When `_buildCliPrompt` took the slash-command fast-path, promptText is
// the raw `/cmd …` we forwarded. Remember the command name so the
@@ -2736,11 +2828,7 @@ async function _buildCliPrompt(
agent: import('../agents').Agent,
item: QueueItem,
slice: GroupMessage[],
- /** When true, the CLI is resuming a prior session and already has
- * the conversation history in its own memory — we skip the slice
- * block entirely and just send the static frame + new task. Drops
- * massive redundancy on long convs. */
- resuming: boolean,
+ bridgeHistory: boolean,
): Promise<string> {
// Slash-command fast-path: when the user sends `/foo …` to a CLI agent,
// forward the raw text so the CLI's own slash dispatcher (built-ins +
@@ -2764,7 +2852,7 @@ async function _buildCliPrompt(
// Layout = `chat_cli_agent.md` (static frame) + `chat_cli_coding_protocol.md`
// (coding-only). The static-first / runtime-last split keeps the
// CLI's prompt cache stable across turns: identity + protocol stay
- // byte-identical, attachments / slice / task body all change.
+ // byte-identical, attachments / task body change.
const { prompts } = await import('../../prompts/loader');
const { chatAttachmentDir } = await import('../../paths');
@@ -2838,8 +2926,6 @@ async function _buildCliPrompt(
taskBody = item.llmPayload;
}
- // Render the template with a candidate conversation block. The
- // truncation pass below sizes the block against the byte cap.
const render = (conversationBlock: string) => prompts.load('chat_cli_agent', {
agent_name: agent.name || agent.agent_id,
agent_description: (agent.description_en || agent.description_zh || '').trim(),
@@ -2849,31 +2935,26 @@ async function _buildCliPrompt(
task_body: taskBody,
});
- // Resuming → CLI already has the slice in its own memory; skip
- // replay entirely. Static frame + new task is enough.
- if (resuming) return render('');
+ if (!bridgeHistory) return render('');
+
+ const history = _priorVisibleCliHistory(item, slice);
+ if (!history.length) return render('');
- // Conversation slice, oldest → newest. Empty-text rows skipped.
const sliceLines: string[] = [];
- for (const m of slice) {
+ for (const m of history) {
const to = (m.to || []).join(',') || '-';
const text = (m.text || '').replace(/\r/g, '').trim();
if (!text) continue;
sliceLines.push(`[${m.from} → ${to}] ${text}`);
}
+ if (!sliceLines.length) return render('');
- // Size the slice against the byte cap by rendering once with an
- // empty block — gives an exact base size including the protocol /
- // attachments / task. If even the base exceeds the cap, fall back
- // to a no-history prompt rather than truncating the task body.
const baseBytes = Buffer.byteLength(render(''), 'utf8');
if (baseBytes >= CLI_PROMPT_MAX_BYTES) {
log.warn(`cli prompt: base exceeds cap; sending minimal prompt cid=${cid} agent=${agent.agent_id}`);
return render('');
}
const sliceBudget = CLI_PROMPT_MAX_BYTES - baseBytes;
- // Walk newest-backward, keep lines while we have budget. Oldest
- // lines that don't fit are dropped.
const kept: string[] = [];
let used = 0;
for (let i = sliceLines.length - 1; i >= 0; i--) {
@@ -2886,8 +2967,15 @@ async function _buildCliPrompt(
if (truncated) {
log.warn(`cli prompt: trimmed ${sliceLines.length - kept.length}/${sliceLines.length} oldest slice rows cid=${cid} agent=${agent.agent_id}`);
}
- const conversationBlock = kept.length
- ? `## Conversation so far${truncated ? ' (truncated)' : ''}\n${kept.join('\n')}`
- : '';
+ const conversationBlock = `## Conversation so far${truncated ? ' (truncated)' : ''}\n${kept.join('\n')}`;
return render(conversationBlock);
}
+
+function _priorVisibleCliHistory(item: QueueItem, slice: GroupMessage[]): GroupMessage[] {
+ const idx = slice.findIndex((m) => m.id === item.msgId);
+ return idx >= 0 ? slice.slice(0, idx) : slice;
+}
+
+function _hasPriorVisibleCliHistory(item: QueueItem, slice: GroupMessage[]): boolean {
+ return _priorVisibleCliHistory(item, slice).some((m) => (m.text || '').trim());
+}
diff --git a/src/main/features/group_chat/conv_title.ts b/src/main/features/group_chat/conv_title.ts
new file mode 100644
index 00000000..08fedcfa
--- /dev/null
+++ b/src/main/features/group_chat/conv_title.ts
@@ -0,0 +1,25 @@
+// 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.
+
+// 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',
+ 'New Conversation',
+ 'New chat',
+ 'New Chat',
+]);
+
+/** True when `title` is a placeholder default written at conversation
+ * creation, i.e. the user hasn't named the chat yet. Locale-agnostic: it
+ * recognises every default form the title generator can emit. */
+export function isPlaceholderTitle(title: string | undefined | null): boolean {
+ if (!title) return true;
+ return PLACEHOLDER_TITLES.has(title);
+}
diff --git a/src/main/features/group_chat/conv_workspace.ts b/src/main/features/group_chat/conv_workspace.ts
index e7b1add4..9a8382f2 100644
--- a/src/main/features/group_chat/conv_workspace.ts
+++ b/src/main/features/group_chat/conv_workspace.ts
@@ -37,34 +37,13 @@ import * as path from 'node:path';
import { getWorkspacePath } from '../user_workspace';
import { getConversation } from '../chats';
import { readState, setWorkspaceDirOnce } from './state';
+import { PLACEHOLDER_TITLES } from './conv_title';
import { createLogger } from '../../logger';
const log = createLogger('group_chat.conv_workspace');
const MAX_SLUG_LEN = 32;
-// Match the literal default titles `chats.createConversation` writes when
-// no title is supplied (currently `t('chat.default_title')` resolved at
-// creation time → '新对话' for zh UI, 'New conversation' for en UI) AND
-// 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',
- 'New Conversation',
- 'New chat',
- 'New Chat',
-]);
-
-/** True when `title` is a placeholder default written at conversation
- * creation, i.e. the user hasn't named the chat yet. Locale-agnostic — it
- * recognises every default form the title generator can emit. */
-export function isPlaceholderTitle(title: string | undefined | null): boolean {
- if (!title) return true;
- return PLACEHOLDER_TITLES.has(title);
-}
-
// Windows reserved device names (case-insensitive). A directory bearing
// any of these names cannot be created on Windows — fall back rather than
// fight the OS.
diff --git a/src/main/features/group_chat/index.ts b/src/main/features/group_chat/index.ts
index 0bcc4a15..e352a3f6 100644
--- a/src/main/features/group_chat/index.ts
+++ b/src/main/features/group_chat/index.ts
@@ -18,13 +18,13 @@ import { t } from '../../i18n';
import {
COMMANDER_ID, USER_ID, readMembers, readState, seedReservedActors, purgeGroupDir,
- setCodingProjectDir,
+ setCodingProjectDir, setStatus,
} from './state';
-import { isPlaceholderTitle } from './conv_workspace';
+import { isPlaceholderTitle } from './conv_title';
import { readPlan, type PlanFile } from './plan';
import * as planExecutor from './plan_executor';
import {
- abort as busAbort, dropConv as busDropConv, enqueue, subscribe, isQuiescent,
+ abort as busAbort, dropConv as busDropConv, enqueue, subscribe, isQuiescent, runtimeSnapshot,
type GroupEvent,
} from './bus';
@@ -34,6 +34,29 @@ import {
* authoritative source. */
export const busIsQuiescent = isQuiescent;
+export async function runtimeStatus(
+ userId: string,
+ cid: string,
+): Promise<{ processing: boolean; processing_since: string | null; in_flight: string[] }> {
+ if (!safeId(cid)) return { processing: false, processing_since: null, in_flight: [] };
+ try {
+ const state = await readState(userId, cid);
+ const runtime = runtimeSnapshot(userId, cid);
+ const inFlight = Array.from(new Set([
+ ...(Array.isArray(state.in_flight) ? state.in_flight : []),
+ ...runtime.inFlight,
+ ].filter(Boolean)));
+ const processing = state.status === 'running' || runtime.processing;
+ return {
+ processing,
+ processing_since: processing ? (state.last_active_at || null) : null,
+ in_flight: inFlight,
+ };
+ } catch {
+ return { processing: false, processing_since: null, in_flight: [] };
+ }
+}
+
/** Re-export so the IPC layer can subscribe to the bus BEFORE calling
* send(). enqueue wakes the recipient worker synchronously, which then
* starts emitting events on the same microtask cycle as send's return —
@@ -146,7 +169,10 @@ export async function retryStep(
): Promise<{ ok: boolean; error?: string }> {
if (!safeId(cid)) return { ok: false, error: 'invalid cid' };
if (!Number.isFinite(stepIndex) || stepIndex < 1) return { ok: false, error: 'invalid stepIndex' };
- return planExecutor.retryStep(userId, cid, stepIndex);
+ await clearAbortedStatusForRecovery(userId, cid);
+ const result = await planExecutor.retryStep(userId, cid, stepIndex);
+ if (result.ok) _emitPlanSignal(userId, cid, stepIndex, 'retry');
+ return result;
}
/** User-initiated skip of a failed plan step (rail "Skip" button). */
@@ -155,7 +181,56 @@ export async function skipStep(
): Promise<{ ok: boolean; error?: string }> {
if (!safeId(cid)) return { ok: false, error: 'invalid cid' };
if (!Number.isFinite(stepIndex) || stepIndex < 1) return { ok: false, error: 'invalid stepIndex' };
- return planExecutor.skipStep(userId, cid, stepIndex);
+ await clearAbortedStatusForRecovery(userId, cid);
+ const result = await planExecutor.skipStep(userId, cid, stepIndex);
+ if (result.ok) _emitPlanSignal(userId, cid, stepIndex, 'skip');
+ return result;
+}
+
+/** Expert-signals hook (plan §5 mounts #2/#3) — read the plan to recover
+ * the agent_id assigned to this step + the source agent msg id, then emit
+ * retry/skip signal. Fire-and-forget; failures never block the IPC reply.
+ *
+ * turn_id = `step.output_msg_id` (the agent msg this step produced).
+ * Per expert-signals plan §3.4 + types.ts Signal.turn_id doc: `turn_id` is
+ * the agent msg id this signal reacts to / is produced by. For retry/skip
+ * that's the source output being retried — letting consumers JOIN this
+ * signal against `skill_invoked` / `tool_failure` from the same agent
+ * turn. Previous design used synthetic `<cid>:plan:<step>` shared across
+ * every retry on the same step; the shared-id property is now recovered
+ * via `metadata.step_index` group-by (consumers count repeat retries
+ * there). When the step has no `output_msg_id` (rare — step in_progress
+ * with no output yet), the signal is dropped: a turn_id-less retry signal
+ * can't be attributed to a specific agent turn. */
+function _emitPlanSignal(uid: string, cid: string, stepIndex: number, kind: 'retry' | 'skip'): void {
+ (async () => {
+ try {
+ const plan = await readPlan(uid, cid);
+ const step = plan?.steps?.[stepIndex - 1];
+ const aid = (step && typeof (step as any).assignee === 'string') ? (step as any).assignee : '';
+ if (!aid) return; // user-assignee or missing — no signal target
+ const turn_id = (step as any)?.output_msg_id;
+ if (!turn_id) return; // no source agent msg id → drop (see fn doc)
+ const { emitSignal } = await import('../expert_signals');
+ const { buildRetrySignal, buildSkipSignal } = await import('../expert_signals/extractors/event');
+ emitSignal(uid, (kind === 'retry' ? buildRetrySignal : buildSkipSignal)({
+ cid, aid, turn_id, step_index: stepIndex,
+ msg_ids: [turn_id],
+ }));
+ } catch (err) {
+ log.warn(`expert-signals plan ${kind} emit failed cid=${cid} step=${stepIndex}: ${(err as Error).message}`);
+ }
+ })();
+}
+
+async function clearAbortedStatusForRecovery(userId: string, cid: string): Promise<void> {
+ try {
+ const state = await readState(userId, cid);
+ if (state.status === 'aborted') await setStatus(userId, cid, 'idle');
+ } catch {
+ // Recovery actions should still reach the plan executor even if the
+ // runtime status file is temporarily unavailable.
+ }
}
// ── Streaming events ─────────────────────────────────────────────────────
@@ -263,6 +338,24 @@ export async function markFormSubmittedAndDispatch(
}
log.info(`form-submitted user=${userId} cid=${cid} msgId=${msgId} agent=${agentId} fields=${target.form.fields.length}`);
+ // Expert-signals hook (plan §5 mount #4): one form_left_blank signal per
+ // field the user didn't touch (kept blank OR kept default). Fire-and-
+ // forget; failures never block the form submission.
+ (async () => {
+ try {
+ const { emitSignal } = await import('../expert_signals');
+ const { buildFormLeftBlankSignals } = await import('../expert_signals/extractors/event');
+ const signals = buildFormLeftBlankSignals({
+ cid, aid: agentId, turn_id: msgId, msg_id: msgId,
+ fields: target.form.fields as any,
+ values: (values || {}) as Record<string, unknown>,
+ });
+ for (const sig of signals) emitSignal(userId, sig);
+ } catch (err) {
+ log.warn(`expert-signals form_left_blank emit failed cid=${cid} msgId=${msgId}: ${(err as Error).message}`);
+ }
+ })();
+
// Coding-agent contract: when a `project_dir` field is present in the
// submitted form for an external claude / codex agent, persist it to
// conv state so `_runCliAgentTurn` can spawn the CLI inside that
@@ -283,8 +376,9 @@ export async function markFormSubmittedAndDispatch(
if (oldDir && oldDir !== projDir) {
// cwd is about to change — claude code's sessions are cwd-keyed,
// so the existing binding would fail with "No conversation
- // found" on resume. Drop it; next dispatch replays the full
- // slice so the user-visible conversation continues seamlessly.
+ // found" on resume. Drop it; next dispatch starts a fresh CLI
+ // session and bridges the prior visible transcript once so the
+ // user-visible conversation continues seamlessly.
const cliSessions = await import('../local_agents/sessions');
await cliSessions.clearForConversation(userId, cid);
log.info(`coding cwd changed (form) user=${userId} cid=${cid} ${oldDir} → ${projDir} — cleared cli sessions`);
@@ -381,6 +475,7 @@ function _encodeMarketplaceInstallResult(
name: req.name,
version: req.version,
published_at: req.published_at,
+ ...(typeof req.updated_at === 'number' ? { updated_at: req.updated_at } : {}),
status,
...(error ? { error } : {}),
};
@@ -521,9 +616,17 @@ export async function resolveMarketplaceInstallRequest(
try {
if (req.kind === 'agent') {
- await marketplace.installMarketplaceAgent(req.id, { version: req.version, published_at: req.published_at });
+ await marketplace.installMarketplaceAgent(req.id, {
+ version: req.version,
+ published_at: req.published_at,
+ ...(typeof req.updated_at === 'number' ? { updated_at: req.updated_at } : {}),
+ });
} else {
- await marketplace.installMarketplaceSkill(req.id, { version: req.version, published_at: req.published_at });
+ await marketplace.installMarketplaceSkill(req.id, {
+ version: req.version,
+ published_at: req.published_at,
+ ...(typeof req.updated_at === 'number' ? { updated_at: req.updated_at } : {}),
+ });
}
await _autoBindInstalledMarketplaceResource(userId, cid, req);
const patched = await _patchMarketplaceRequest(userId, cid, msgId, requestId, {
diff --git a/src/main/features/group_chat/plan.ts b/src/main/features/group_chat/plan.ts
index 27823f31..68608ff7 100644
--- a/src/main/features/group_chat/plan.ts
+++ b/src/main/features/group_chat/plan.ts
@@ -88,6 +88,14 @@ export interface PlanFile {
* `{{user_initial_message}}` template substitution. Set by `setPlan` when
* the plan is first written and the bus has the trigger context. */
initial_message?: string;
+ /** Attachment filenames (relative to `chat_attachments/<cid>/`) carried by
+ * the user turn that triggered planning. Every step dispatch inherits this
+ * list so worker agents see the same image/file bytes the commander saw —
+ * otherwise images bypass the worker turn and the agent honestly answers
+ * "I can't see the image". `dispatch_to` (non-plan) handles inheritance
+ * via per-turn flush in bus.ts; plan steps live across worker turn
+ * boundaries so the source must be persisted here. */
+ initial_attachments?: string[];
/** True after bus has fired the "all steps terminal" notification, so we
* don't fire it again on subsequent reconciles for the same plan. */
completed_signaled?: boolean;
@@ -108,6 +116,9 @@ export async function readPlan(uid: string, cid: string): Promise<PlanFile | nul
created_at: parsed.created_at || nowIso(),
updated_at: parsed.updated_at || nowIso(),
initial_message: parsed.initial_message,
+ ...(Array.isArray(parsed.initial_attachments) && parsed.initial_attachments.length
+ ? { initial_attachments: parsed.initial_attachments.map(String) }
+ : {}),
completed_signaled: parsed.completed_signaled,
steps: parsed.steps.map(normalizeStep),
};
@@ -160,6 +171,10 @@ export interface PlanSetInput {
/** Optional: the user message that triggered planning. Captured for
* `{{user_initial_message}}` substitution at dispatch time. */
initial_message?: string;
+ /** Optional: attachment filenames carried by the triggering user turn.
+ * Persisted on the plan so every step dispatch can hand the same image/
+ * file bytes to the worker (see PlanFile.initial_attachments). */
+ initial_attachments?: string[];
}
async function writePlanRaw(uid: string, cid: string, plan: PlanFile): Promise<void> {
@@ -181,11 +196,17 @@ export async function setPlan(
const existed = fs.existsSync(file);
let created_at = nowIso();
let prevInitial: string | undefined;
+ let prevAttachments: string[] | undefined;
if (existed) {
const cur = await readPlan(uid, cid);
if (cur?.created_at) created_at = cur.created_at;
prevInitial = cur?.initial_message;
+ prevAttachments = cur?.initial_attachments;
}
+ const inAtts = Array.isArray(input.initial_attachments) && input.initial_attachments.length
+ ? input.initial_attachments.map(String)
+ : undefined;
+ const initialAttachments = inAtts ?? prevAttachments;
const steps: PlanStep[] = input.steps.map((s, i) => ({
index: i + 1,
title: (s.title || '').trim() || `Step ${i + 1}`,
@@ -202,6 +223,7 @@ export async function setPlan(
created_at,
updated_at: nowIso(),
initial_message: input.initial_message ?? prevInitial,
+ ...(initialAttachments && initialAttachments.length ? { initial_attachments: initialAttachments } : {}),
completed_signaled: false,
steps,
};
diff --git a/src/main/features/group_chat/plan_executor.ts b/src/main/features/group_chat/plan_executor.ts
index 64d17065..1129ae4e 100644
--- a/src/main/features/group_chat/plan_executor.ts
+++ b/src/main/features/group_chat/plan_executor.ts
@@ -196,13 +196,16 @@ export interface ReconcileCtx {
* don't pull a circular import. Bus implements + injects on init. */
export interface ExecutorBusHooks {
/** Persist + emit a normal group message; same signature as `bus.enqueue`
- * but with one extra optional `triggered_step` knob. */
+ * but with one extra optional `triggered_step` knob. `attachments` lets
+ * the executor forward the plan's `initial_attachments` so worker agents
+ * receive the same image / file bytes the originating user turn carried. */
enqueue(params: {
uid: string; cid: string;
fromActorId: string; text: string;
forceTo?: string[];
triggered_step?: number;
dispatch?: boolean;
+ attachments?: string[];
form?: ChatFormPayload;
}): Promise<void>;
/** Push a turn directly into commander's worker queue without persisting
@@ -303,12 +306,11 @@ function outcomeForSynthTurn(evt: TurnFinishedEvent): TurnOutcome {
/** User-direct (or non-plan) turn outcome decision.
*
- * Side effect: if this is an agent reply AND there's a `blocked` plan step
- * whose assignee matches this agent (typical post-form-submit case), the
- * step transitions to `done` and downstream is dispatched. This bridges
- * the gap between "form pause" (step blocked) and "agent re-runs after
- * user submits" (which arrives here as trigger=user_direct since the user
- * enqueue triggered the agent worker, not the executor).
+ * Side effect: if this is an agent reply AND there's an active plan step
+ * whose assignee matches this agent, the step transitions through the normal
+ * plan-step completion path and downstream is dispatched. This covers both
+ * form-unblock replies (`blocked`) and commander/manual recovery dispatches
+ * that do not carry a `triggered_step` stamp (`in_progress`).
*
* commander empty-final policy: user_direct means the user is actively
* waiting on commander, so silent is forbidden — even a tool-only turn
@@ -320,18 +322,16 @@ function outcomeForSynthTurn(evt: TurnFinishedEvent): TurnOutcome {
* agent empty-final → always persist '(no reply)'.
*/
async function outcomeForUserDirectTurn(uid: string, cid: string, evt: TurnFinishedEvent): Promise<TurnOutcome> {
- // Form-pause unblock: if this agent has a blocked step, treat THIS turn
- // as that step's terminator. Re-route through applyPlanStepTurn so the
- // exact same transition logic applies (success / form-again / failure).
if (evt.actor.kind === 'agent') {
const plan = await readPlan(uid, cid);
if (plan?.steps?.length) {
const members = await readMembers(uid, cid);
- const blocked = plan.steps.find((s) =>
- s.status === 'blocked' && assigneeMatches(s.assignee, evt.actor.id, members.actors),
+ const active = plan.steps.find((s) =>
+ (s.status === 'in_progress' || s.status === 'blocked')
+ && assigneeMatches(s.assignee, evt.actor.id, members.actors),
);
- if (blocked) {
- const outcome = await applyPlanStepTurn(uid, cid, evt, blocked.index);
+ if (active) {
+ const outcome = await applyPlanStepTurn(uid, cid, evt, active.index);
await reconcileAfterStepTransition(uid, cid);
return outcome;
}
@@ -838,6 +838,33 @@ async function dispatchReady(uid: string, cid: string, plan: PlanFile): Promise<
if (!groups.has(k)) groups.set(k, []);
groups.get(k)!.push(s);
}
+ // Expert-signals: emit one `agent_dispatched` signal per group BEFORE
+ // wakening — we want the audit record even if the enqueue downstream
+ // throws. turn_id is synthesized (this signal's consumer use case is
+ // aggregation — "did commander dispatch multiple agents to the same
+ // query?" — not JOIN with other signals; see expert-signals plan §4.3
+ // + reservation against cross-signal JOIN). Best-effort.
+ try {
+ const { emitSignal } = await import('../expert_signals');
+ const { buildAgentDispatchedSignal } = await import('../expert_signals/extractors/event');
+ const baseTs = Date.now();
+ let i = 0;
+ for (const [groupKey, steps] of groups) {
+ const assignees = steps.map((s) => s.assignee).filter(Boolean);
+ const parallel_group = groupKey.startsWith('_solo_') ? null : groupKey;
+ emitSignal(uid, buildAgentDispatchedSignal({
+ cid,
+ // `plan:dispatch:<ts>:<i>` is unique per emit. Documented in the
+ // signal builder comment.
+ turn_id: `${cid}:plan:dispatch:${baseTs}:${i++}`,
+ candidates: assignees.slice(),
+ dispatched: assignees.slice(),
+ parallel_group,
+ }));
+ }
+ } catch (err) {
+ log.warn(`agent_dispatched emit failed cid=${cid}: ${(err as Error).message}`);
+ }
for (const [, steps] of groups) {
for (const step of steps) {
await dispatchStep(uid, cid, step, plan);
@@ -863,6 +890,10 @@ async function dispatchStep(
const rendered = renderTemplate(step.input, plan);
const assignee = step.assignee.trim();
+ // Forward attachments captured at plan-set time so worker agents (and
+ // the user, for a `user`-assignee question) receive the same image / file
+ // bytes the triggering user turn carried — see PlanFile.initial_attachments.
+ const inheritedAttachments = plan.initial_attachments;
if (USER_ALIASES.has(assignee.toLowerCase())) {
// Step asks user for input. Commander voice; render goes to user with
@@ -874,6 +905,7 @@ async function dispatchStep(
text: rendered,
forceTo: [USER_ID],
triggered_step: step.index,
+ ...(inheritedAttachments && inheritedAttachments.length ? { attachments: inheritedAttachments } : {}),
form: buildUserStepForm(step),
});
return;
@@ -915,6 +947,7 @@ async function dispatchStep(
forceTo: [agentId],
triggered_step: step.index,
dispatch: true,
+ ...(inheritedAttachments && inheritedAttachments.length ? { attachments: inheritedAttachments } : {}),
});
}
diff --git a/src/main/features/group_chat/state.ts b/src/main/features/group_chat/state.ts
index 15f54b0a..48b3568d 100644
--- a/src/main/features/group_chat/state.ts
+++ b/src/main/features/group_chat/state.ts
@@ -65,13 +65,9 @@ export interface StateFile {
* slug rules and the placeholder fallback. */
workspace_dir?: string;
/** Project directory for coding-agent (claude / codex) dispatches in
- * this conversation. Auto-set on the first coding-agent turn to the
- * user's effective workspace path (so the user doesn't have to pick
- * manually for the common case), and re-synced to follow workspace
- * switches as long as `coding_project_dir_explicit` is false. Once
- * the user picks a different directory through the input-form
- * (`coding_project_dir_explicit=true`), workspace changes no longer
- * override their choice. Absolute path. Missing / empty → coding
+ * this conversation. Initialised on the first coding-agent turn from
+ * that agent's detail-page project-dir setting; missing setting =
+ * effective workspace path. Absolute path. Missing / empty → coding
* agents fall back to the conv's workspace root. The field is
* per-conversation, NOT per-agent: one project for the whole
* conversation across however many coding agents it has. */
@@ -86,6 +82,11 @@ export interface StateFile {
* auto-set by the workspace-sync path in `bus.ts` and is allowed to
* follow future workspace switches. Cleared whenever
* `coding_project_dir` is cleared. */
+ /** True when the user picked `coding_project_dir` explicitly, either
+ * via the agent detail page's custom project-dir setting at initial
+ * conversation setup, or via the `<agent-input-form>` directory
+ * picker (form-submit hook in `group_chat/index.ts`). Cleared
+ * whenever `coding_project_dir` is cleared. */
coding_project_dir_explicit?: boolean;
}
@@ -349,12 +350,10 @@ export async function setWorkspaceDirOnce(uid: string, cid: string, dir: string)
* Caller is responsible for absolute-path validation — we only do
* string handling here. Returns the resulting state.
*
- * `opts.explicit` records whether the user actively chose this
- * directory through the `<agent-input-form>` picker. The flag is
- * consulted by the workspace-sync path in `bus.ts`: explicit picks
- * are sticky (workspace switches don't override them), auto-set
- * values track the workspace. Clearing `dir` also clears the flag
- * so the next auto-set doesn't accidentally inherit a stale `true`. */
+ * `opts.explicit` records whether this value came from a user-chosen
+ * custom directory (agent detail setting or `<agent-input-form>`).
+ * Clearing `dir` also clears the flag so the next initialisation
+ * doesn't accidentally inherit a stale `true`. */
export async function setCodingProjectDir(
uid: string, cid: string, dir: string,
opts: { explicit: boolean },
diff --git a/src/main/features/group_chat/visibility.ts b/src/main/features/group_chat/visibility.ts
index 8db4f815..07871cab 100644
--- a/src/main/features/group_chat/visibility.ts
+++ b/src/main/features/group_chat/visibility.ts
@@ -100,6 +100,9 @@ export interface MarketplaceInstallRequest {
create_uid?: string;
version: string;
published_at: number;
+ /** Server row update timestamp. Preferred freshness key for marketplace installs because
+ * republishing keeps `published_at` stable. */
+ updated_at?: number;
reason?: string;
status: 'pending' | 'installed' | 'skipped' | 'failed';
requested_at: string;
diff --git a/src/main/features/local_agents/sessions.ts b/src/main/features/local_agents/sessions.ts
index 23043437..a0b332c6 100644
--- a/src/main/features/local_agents/sessions.ts
+++ b/src/main/features/local_agents/sessions.ts
@@ -2,9 +2,11 @@
* Per-conversation CLI session bindings.
*
* Each (cid, aid, cli) tuple gets a CLI-reported session id so the
- * next dispatch can pass `--resume <id>` instead of re-replaying the
- * full visibility slice as prompt context. The CLI keeps its own
- * conversation memory; we only persist the handle.
+ * next dispatch can pass `--resume <id>`. The CLI keeps its own
+ * conversation memory; we only persist the handle. Host prompts stay
+ * current-turn-only while this handle is valid; if the handle is absent
+ * after prior visible turns (for example cwd changed), group_chat may
+ * bridge that transcript once into the fresh CLI session.
*
* Storage: `<uid>/local/cli-sessions/<cid>.json`, shape:
* { "<aid>": { "cli": "claude", "sessionId": "...", "updatedAt": "..." } }
@@ -15,7 +17,7 @@
*
* `cli` is captured alongside the id so a runtime swap (the user
* picks a different CLI from the detail page selector) treats the
- * old binding as stale — fresh dispatch, fresh prompt. The runner
+ * old binding as stale — fresh dispatch, fresh CLI session. The runner
* persists a new id once the new CLI emits one.
*/
@@ -63,8 +65,7 @@ async function write(uid: string, cid: string, data: CliSessionsFile): Promise<v
/**
* Return the bound CLI session id for the (cid, aid, cli) tuple, or
* null if no binding exists OR the binding is for a different CLI
- * (runtime swapped). Caller treats null as "fresh dispatch — replay
- * the visibility slice".
+ * (runtime swapped). Caller treats null as a fresh CLI session.
*/
export async function getSessionId(uid: string, cid: string, aid: string, cli: string): Promise<string | null> {
const file = await read(uid, cid);
diff --git a/src/main/features/marketplace.ts b/src/main/features/marketplace.ts
index f760e2ad..b080849c 100644
--- a/src/main/features/marketplace.ts
+++ b/src/main/features/marketplace.ts
@@ -6,8 +6,8 @@
* 1. **Server** owns the catalog (marketplace_agents / marketplace_skills tables) and the
* blob URLs (agent.json on COS, skill bundle .zip on COS).
* 2. **Cloud-synced install manifest** (`<uid>/cloud/marketplace/installs.json`) — the only
- * multi-device state. Records what the user has installed: id / version / published_at /
- * COS URL / installed_at. See `marketplace_installs.ts`.
+ * multi-device state. Records what the user has installed: id / version / freshness
+ * timestamp / COS URL / installed_at. See `marketplace_installs.ts`.
* 3. **Per-machine install target** (`<uid>/local/marketplace/{agents,skills}/<id>/`) — the
* actual content. Reconciled from (2) on startup by `marketplace_reconcile.ts`: any entry
* in the manifest without local content gets fetched in parallel. Listed alongside
@@ -157,6 +157,7 @@ export interface AgentDetail {
version: string;
category: string;
published_at: number;
+ updated_at?: number;
/** Full agent.json content (already merged from cache or freshly fetched). */
agent_json: Record<string, unknown>;
/** COS URL of the agent.json blob — recorded in installs.json so reconcile on other
@@ -174,6 +175,7 @@ export interface SkillDetail {
version: string;
category: string;
published_at: number;
+ updated_at?: number;
/** Local filesystem path to the cache directory (caller can walk it to render the file tree
* + read SKILL.md). The cache may also be wiped between calls — re-fetch via this function. */
cache_dir: string;
@@ -210,8 +212,10 @@ export async function listMarketplaceSkills(
// ── detail (cache-aware) ──────────────────────────────────────────────────
// Detail-page entry. Caller provides the list-row's freshness pair so we can short-circuit
// when cache is hot; we still fetch + repopulate cache on miss / stale.
+type MarketplaceFreshness = { version: string; published_at: number; updated_at?: number };
+
export async function getAgentDetail(
- agentId: string, expect: { version: string; published_at: number },
+ agentId: string, expect: MarketplaceFreshness,
): Promise<AgentDetail> {
if (!agentId) throw new Error('agentId required');
if (await isCacheFresh('agent', agentId, expect)) {
@@ -220,36 +224,56 @@ export async function getAgentDetail(
await touchCacheEntry('agent', agentId);
// Cache hit path: agent_json_url / create_uid are unknown (not stored in cache meta).
// Install path re-fetches via /detail to get them; detail render doesn't need them.
- return { id: agentId, version: expect.version, category: '', published_at: expect.published_at, agent_json: cached, agent_json_url: '', create_uid: '' };
+ return {
+ id: agentId, version: expect.version, category: '',
+ published_at: expect.published_at, updated_at: expect.updated_at,
+ agent_json: cached, agent_json_url: '', create_uid: '',
+ };
}
}
// Miss → fetch + repopulate.
- const data = await postJson<{ agent_json: Record<string, unknown>; version: string; category: string; published_at: number; agent_json_url: string; create_uid: string; default_install?: boolean }>(
+ const data = await postJson<{ agent_json: Record<string, unknown>; version: string; category: string; published_at: number; updated_at?: number; agent_json_url: string; create_uid: string; default_install?: boolean }>(
'/marketplace/agents/detail', { id: agentId },
);
- await writeAgentCache(agentId, data.agent_json, { version: data.version, published_at: data.published_at });
- return { id: agentId, version: data.version, category: data.category, published_at: data.published_at, agent_json: data.agent_json, agent_json_url: data.agent_json_url || '', create_uid: data.create_uid || '', default_install: data.default_install === true };
+ await writeAgentCache(agentId, data.agent_json, {
+ version: data.version, published_at: data.published_at, updated_at: data.updated_at,
+ });
+ return {
+ id: agentId, version: data.version, category: data.category,
+ published_at: data.published_at, updated_at: data.updated_at,
+ agent_json: data.agent_json, agent_json_url: data.agent_json_url || '',
+ create_uid: data.create_uid || '', default_install: data.default_install === true,
+ };
}
export async function getSkillDetail(
- skillId: string, expect: { version: string; published_at: number },
+ skillId: string, expect: MarketplaceFreshness,
): Promise<SkillDetail> {
if (!skillId) throw new Error('skillId required');
if (await isCacheFresh('skill', skillId, expect)) {
await touchCacheEntry('skill', skillId);
- return { id: skillId, version: expect.version, category: '', published_at: expect.published_at, cache_dir: getSkillCacheDir(skillId), bundle_url: '', create_uid: '' };
+ return {
+ id: skillId, version: expect.version, category: '',
+ published_at: expect.published_at, updated_at: expect.updated_at,
+ cache_dir: getSkillCacheDir(skillId), bundle_url: '', create_uid: '',
+ };
}
// Miss → fetch + write.
- const meta = await postJson<{ bundle_url: string; version: string; category: string; published_at: number; create_uid: string; default_install?: boolean }>(
+ const meta = await postJson<{ bundle_url: string; version: string; category: string; published_at: number; updated_at?: number; create_uid: string; default_install?: boolean }>(
'/marketplace/skills/bundle', { id: skillId },
);
await _fetchAndCacheSkill(skillId, meta);
- return { id: skillId, version: meta.version, category: meta.category, published_at: meta.published_at, cache_dir: getSkillCacheDir(skillId), bundle_url: meta.bundle_url, create_uid: meta.create_uid || '', default_install: meta.default_install === true };
+ return {
+ id: skillId, version: meta.version, category: meta.category,
+ published_at: meta.published_at, updated_at: meta.updated_at,
+ cache_dir: getSkillCacheDir(skillId), bundle_url: meta.bundle_url,
+ create_uid: meta.create_uid || '', default_install: meta.default_install === true,
+ };
}
/** Fetch a skill .zip from COS and extract into the local cache (idempotent: wipe-and-replace). */
async function _fetchAndCacheSkill(
- skillId: string, meta: { bundle_url: string; version: string; published_at: number },
+ skillId: string, meta: { bundle_url: string; version: string; published_at: number; updated_at?: number },
): Promise<void> {
const res = await fetch(meta.bundle_url);
if (!res.ok) throw new Error(`download bundle failed (${res.status})`);
@@ -257,7 +281,7 @@ async function _fetchAndCacheSkill(
const zipBuf = Buffer.from(ab);
await writeSkillCache(skillId, async (dir) => {
extractBundleSafely(new AdmZip(zipBuf), dir);
- }, { version: meta.version, published_at: meta.published_at });
+ }, { version: meta.version, published_at: meta.published_at, updated_at: meta.updated_at });
}
// zip-bomb defense, mirrored at server (see `api/marketplace.py::_validate_skill_bundle`).
@@ -293,7 +317,7 @@ export function extractBundleSafely(zip: AdmZip, dst: string): void {
// ── install ───────────────────────────────────────────────────────────────
export async function installMarketplaceAgent(
- agentId: string, expect: { version: string; published_at: number },
+ agentId: string, expect: MarketplaceFreshness,
): Promise<{ ok: true; id: string }> {
if (!agentId) throw new Error('agentId required');
// Ensure cache is hot (and pick up agent_json_url for the manifest).
@@ -301,11 +325,12 @@ export async function installMarketplaceAgent(
if (!detail.agent_json_url) {
// Cache-hit path returns url='' (and create_uid=''); re-fetch via detail endpoint to
// capture both — needed for manifest + `_install.json` author badge.
- const fresh = await postJson<{ agent_json: Record<string, unknown>; version: string; category: string; published_at: number; agent_json_url: string; create_uid: string; default_install?: boolean }>(
+ const fresh = await postJson<{ agent_json: Record<string, unknown>; version: string; category: string; published_at: number; updated_at?: number; agent_json_url: string; create_uid: string; default_install?: boolean }>(
'/marketplace/agents/detail', { id: agentId },
);
detail = {
- id: agentId, version: fresh.version, category: fresh.category, published_at: fresh.published_at,
+ id: agentId, version: fresh.version, category: fresh.category,
+ published_at: fresh.published_at, updated_at: fresh.updated_at,
agent_json: fresh.agent_json, agent_json_url: fresh.agent_json_url || '',
create_uid: fresh.create_uid || '',
default_install: fresh.default_install === true,
@@ -324,10 +349,14 @@ export async function installMarketplaceAgent(
await Promise.all(missingSkillIds.map(async (sid) => {
// Direct hit on /skills/bundle for meta — avoids paging /skills/list (O(catalog) lookup
// that breaks once the catalog grows past 500 skills).
- const meta = await postJson<{ bundle_url: string; version: string; category: string; published_at: number }>(
+ const meta = await postJson<{ bundle_url: string; version: string; category: string; published_at: number; updated_at?: number }>(
'/marketplace/skills/bundle', { id: sid },
);
- await installMarketplaceSkill(sid, { version: meta.version, published_at: meta.published_at });
+ await installMarketplaceSkill(sid, {
+ version: meta.version,
+ published_at: meta.published_at,
+ updated_at: meta.updated_at,
+ });
log.info(` dep-installed skill ${sid}`);
}));
}
@@ -348,17 +377,18 @@ export async function installMarketplaceAgent(
// 3. Now materialize the agent: cache content → `<uid>/local/marketplace/agents/<id>/`.
// `_install.json` is a version pin read by `marketplace_reconcile.ts::_agentNeedsPull`
// on other devices to skip a re-pull when their local copy already matches the manifest's
- // (version, published_at).
+ // (version, freshness timestamp).
const target = userMarketplaceAgentDir(getActiveUserId(), agentId);
await fsp.mkdir(target, { recursive: true });
await fsp.writeFile(path.join(target, 'agent.json'), JSON.stringify(detail.agent_json, null, 2), 'utf8');
// `_install.json` stores everything the in-app UI needs without re-hitting the network:
- // version/published_at for reconcile freshness; create_uid for the author badge on the
+ // version/freshness timestamp for reconcile; create_uid for the author badge on the
// agent detail page.
await fsp.writeFile(path.join(target, '_install.json'),
JSON.stringify({
version: detail.version,
published_at: detail.published_at,
+ ...(typeof detail.updated_at === 'number' ? { updated_at: detail.updated_at } : {}),
create_uid: detail.create_uid || '',
}, null, 2), 'utf8');
await touchCacheEntry('agent', agentId);
@@ -366,6 +396,7 @@ export async function installMarketplaceAgent(
// 4. Record in the cloud-synced manifest so other devices reconcile this install.
await addAgentInstall(getActiveUserId(), {
id: agentId, version: detail.version, published_at: detail.published_at,
+ ...(typeof detail.updated_at === 'number' ? { updated_at: detail.updated_at } : {}),
agent_json_url: detail.agent_json_url, create_uid: detail.create_uid || '',
});
log.info(`installed marketplace agent ${agentId} v${detail.version} → ${target}`);
@@ -374,15 +405,22 @@ export async function installMarketplaceAgent(
}
export async function installMarketplaceSkill(
- skillId: string, expect: { version: string; published_at: number },
+ skillId: string, expect: MarketplaceFreshness,
): Promise<{ ok: true; id: string }> {
if (!skillId) throw new Error('skillId required');
let detail = await getSkillDetail(skillId, expect);
if (!detail.bundle_url) {
- const fresh = await postJson<{ bundle_url: string; version: string; category: string; published_at: number; create_uid: string; default_install?: boolean }>(
+ const fresh = await postJson<{ bundle_url: string; version: string; category: string; published_at: number; updated_at?: number; create_uid: string; default_install?: boolean }>(
'/marketplace/skills/bundle', { id: skillId },
);
- detail = { ...detail, bundle_url: fresh.bundle_url, create_uid: fresh.create_uid || '', default_install: fresh.default_install === true };
+ detail = {
+ ...detail,
+ published_at: fresh.published_at,
+ updated_at: fresh.updated_at,
+ bundle_url: fresh.bundle_url,
+ create_uid: fresh.create_uid || '',
+ default_install: fresh.default_install === true,
+ };
}
const cacheDir = getSkillCacheDir(skillId);
@@ -408,6 +446,7 @@ export async function installMarketplaceSkill(
JSON.stringify({
version: detail.version,
published_at: detail.published_at,
+ ...(typeof detail.updated_at === 'number' ? { updated_at: detail.updated_at } : {}),
create_uid: detail.create_uid || '',
}, null, 2), 'utf8');
await touchCacheEntry('skill', skillId);
@@ -415,6 +454,7 @@ export async function installMarketplaceSkill(
await addSkillInstall(getActiveUserId(), {
id: skillId, version: detail.version, published_at: detail.published_at,
+ ...(typeof detail.updated_at === 'number' ? { updated_at: detail.updated_at } : {}),
bundle_url: detail.bundle_url, create_uid: detail.create_uid || '',
});
log.info(`installed marketplace skill ${skillId} v${detail.version} → ${target}`);
@@ -486,8 +526,8 @@ export async function ensureDefaultInstalls(uid: string): Promise<{ seeded_agent
}
try {
const data = await postJson<{
- agents: { id: string; version: string; published_at: number; agent_json_url: string; create_uid?: string }[];
- skills: { id: string; version: string; published_at: number; bundle_url: string; create_uid?: string }[];
+ agents: { id: string; version: string; published_at: number; updated_at?: number; agent_json_url: string; create_uid?: string }[];
+ skills: { id: string; version: string; published_at: number; updated_at?: number; bundle_url: string; create_uid?: string }[];
}>('/marketplace/defaults', {});
let seededAgents = 0;
let seededSkills = 0;
@@ -496,6 +536,7 @@ export async function ensureDefaultInstalls(uid: string): Promise<{ seeded_agent
await addAgentInstall(uid, {
id: a.id, version: a.version || '1.0.0',
published_at: a.published_at || 0,
+ ...(typeof a.updated_at === 'number' ? { updated_at: a.updated_at } : {}),
agent_json_url: a.agent_json_url || '',
create_uid: a.create_uid || '',
});
@@ -506,6 +547,7 @@ export async function ensureDefaultInstalls(uid: string): Promise<{ seeded_agent
await addSkillInstall(uid, {
id: s.id, version: s.version || '1.0.0',
published_at: s.published_at || 0,
+ ...(typeof s.updated_at === 'number' ? { updated_at: s.updated_at } : {}),
bundle_url: s.bundle_url || '',
create_uid: s.create_uid || '',
});
diff --git a/src/main/features/marketplace_biz.ts b/src/main/features/marketplace_biz.ts
index d19997e6..fa058294 100644
--- a/src/main/features/marketplace_biz.ts
+++ b/src/main/features/marketplace_biz.ts
@@ -26,6 +26,7 @@ import { createLogger } from '../logger';
const log = createLogger('marketplace_biz');
const TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
+export const DEFAULT_MARKETPLACE_CATEGORY_CODE = 'general';
// In-memory mirror of `marketplace.json::categories`. Populated on first read from disk; refreshed
// on every successful server fetch. Skips the fs + JSON.parse round-trip when the IPC handler is
@@ -43,6 +44,18 @@ export interface MarketplaceCategory {
sort_order: number;
}
+export function isSafeMarketplaceCategoryCode(code: string): boolean {
+ return /^[a-z][a-z0-9_-]{0,79}$/.test(String(code || '').trim().toLowerCase());
+}
+
+export function normalizeMarketplaceCategoryCode(
+ code: string,
+ fallback = DEFAULT_MARKETPLACE_CATEGORY_CODE,
+): string {
+ const normalized = String(code || '').trim().toLowerCase();
+ return isSafeMarketplaceCategoryCode(normalized) ? normalized : fallback;
+}
+
/** Hard-coded fallback used only when both the persisted cache and the server are unreachable
* on a cold start. Mirrors the server category registry so the UI behaves identically when
* the network blip clears. Keep in sync with `Server/biz/marketplace/marketplace_mgr.py`. */
diff --git a/src/main/features/marketplace_cache.ts b/src/main/features/marketplace_cache.ts
index 7b6ab96c..0982b091 100644
--- a/src/main/features/marketplace_cache.ts
+++ b/src/main/features/marketplace_cache.ts
@@ -9,8 +9,8 @@
* 2. `sweepIfNeeded()` — entry-time GC: when total cache > 100 MB OR any entry's
* `last_used_at` > 7d ago, evict expired then LRU-trim until size ≤ 80 MB.
*
- * Cache hit rule (`isCacheFresh`): persisted `_cache.json` must carry `version` + `published_at`
- * matching the server-list row for this id. Any mismatch (uploader pushed a new version) ⇒ miss,
+ * Cache hit rule (`isCacheFresh`): persisted `_cache.json` must carry `version` + freshness
+ * timestamp matching the server-list row for this id. Any mismatch (uploader republished) ⇒ miss,
* caller refetches. The install target lives separately at `<uid>/local/marketplace/{agents,
* skills}/<id>/` with its own `_install.json` version pin (read by `marketplace_reconcile.ts`).
* The cache is a strictly local staging area and may be cleared by the user without touching
@@ -46,6 +46,9 @@ export interface CacheMeta {
version: string;
/** `marketplace_<kind>s.published_at` (ms) at fetch time — staleness check. */
published_at: number;
+ /** `marketplace_<kind>s.updated_at` (ms) at fetch time. Preferred staleness key because
+ * republishing keeps `published_at` stable. Optional for older cache entries. */
+ updated_at?: number;
/** When the bytes landed on disk (ms). */
fetched_at: number;
/** Bumped on every detail-page read or install. Drives LRU eviction. */
@@ -65,16 +68,20 @@ async function _writeMeta(dir: string, meta: CacheMeta): Promise<void> {
await fsp.writeFile(_metaFile(dir), JSON.stringify(meta, null, 2), 'utf8');
}
-/** Hit check. Caller passes the server-list row's `version` + `published_at`; both must match
+function _freshnessAt(row: { published_at: number; updated_at?: number }): number {
+ return typeof row.updated_at === 'number' ? row.updated_at : row.published_at;
+}
+
+/** Hit check. Caller passes the server-list row's `version` + freshness timestamp; both must match
* the cached values. The cache dir itself existing is necessary but not sufficient — a
* half-written dir would also exist, hence the field comparison. */
-export async function isCacheFresh(kind: 'agent' | 'skill', id: string, expect: { version: string; published_at: number }): Promise<boolean> {
+export async function isCacheFresh(kind: 'agent' | 'skill', id: string, expect: { version: string; published_at: number; updated_at?: number }): Promise<boolean> {
const dir = _cacheDir(kind, id);
if (!fs.existsSync(dir)) return false;
const meta = await _readMeta(dir);
if (!meta) return false;
if (meta.version !== expect.version) return false;
- if (meta.published_at !== expect.published_at) return false;
+ if (_freshnessAt(meta) !== _freshnessAt(expect)) return false;
return true;
}
@@ -97,7 +104,7 @@ export async function touchCacheEntry(kind: 'agent' | 'skill', id: string): Prom
* a previous version surviving). Sentinel-style atomic write: meta is written last so a
* half-written entry fails `isCacheFresh`. */
export async function writeAgentCache(
- id: string, agentJson: Record<string, unknown>, meta: { version: string; published_at: number },
+ id: string, agentJson: Record<string, unknown>, meta: { version: string; published_at: number; updated_at?: number },
): Promise<void> {
const dir = _cacheDir('agent', id);
await fsp.rm(dir, { recursive: true, force: true });
@@ -106,6 +113,7 @@ export async function writeAgentCache(
const now = Date.now();
await _writeMeta(dir, {
server_id: id, version: meta.version, published_at: meta.published_at,
+ ...(typeof meta.updated_at === 'number' ? { updated_at: meta.updated_at } : {}),
fetched_at: now, last_used_at: now,
});
}
@@ -124,7 +132,7 @@ export async function readAgentCache(id: string): Promise<Record<string, unknown
export async function writeSkillCache(
id: string,
extract: (dir: string) => Promise<void> | void,
- meta: { version: string; published_at: number },
+ meta: { version: string; published_at: number; updated_at?: number },
): Promise<void> {
const dir = _cacheDir('skill', id);
await fsp.rm(dir, { recursive: true, force: true });
@@ -133,6 +141,7 @@ export async function writeSkillCache(
const now = Date.now();
await _writeMeta(dir, {
server_id: id, version: meta.version, published_at: meta.published_at,
+ ...(typeof meta.updated_at === 'number' ? { updated_at: meta.updated_at } : {}),
fetched_at: now, last_used_at: now,
});
}
diff --git a/src/main/features/marketplace_installs.ts b/src/main/features/marketplace_installs.ts
index cac7c6b8..1cf4b093 100644
--- a/src/main/features/marketplace_installs.ts
+++ b/src/main/features/marketplace_installs.ts
@@ -2,7 +2,7 @@
* Marketplace install manifest — `<uid>/cloud/marketplace/installs.json`.
*
* The ONLY marketplace state that crosses devices. Records what the user has installed (id +
- * version + published_at + COS URL); the actual content lives at `<uid>/local/marketplace/`
+ * version + freshness timestamp + COS URL); the actual content lives at `<uid>/local/marketplace/`
* on each machine and is reconciled on startup by `features/marketplace_reconcile.ts`
* (fetches whatever's listed in the manifest but missing locally).
*
@@ -12,11 +12,13 @@
* "version": 1,
* "agents": [
* { "id": "abc123def456", "version": "1.0.0", "published_at": 1747066800000,
+ * "updated_at": 1747067800000,
* "agent_json_url": "https://orkas-1367889399.cos.../agent.json",
* "installed_at": 1747066800100 }
* ],
* "skills": [
* { "id": "xyz789...", "version": "1.0.0", "published_at": 1747066800000,
+ * "updated_at": 1747067800000,
* "bundle_url": "https://orkas-1367889399.cos.../xyz789.zip",
* "installed_at": 1747066800100 }
* ]
@@ -66,6 +68,10 @@ export interface AgentInstall {
id: string;
version: string;
published_at: number;
+ /** Server row update timestamp. Preferred freshness key because republish updates this
+ * while `published_at` remains the original first-publish time. Optional so old manifest
+ * rows still parse and fall back to `published_at`. */
+ updated_at?: number;
agent_json_url: string;
installed_at: number;
/** Author uid as recorded on the server. `"0"` is the official-platform marker (label
@@ -80,6 +86,8 @@ export interface SkillInstall {
id: string;
version: string;
published_at: number;
+ /** Same freshness semantics as `AgentInstall.updated_at`. */
+ updated_at?: number;
bundle_url: string;
installed_at: number;
/** Same as `AgentInstall.create_uid` — see comment there. */
diff --git a/src/main/features/marketplace_reconcile.ts b/src/main/features/marketplace_reconcile.ts
index f849e2ff..62daa3c0 100644
--- a/src/main/features/marketplace_reconcile.ts
+++ b/src/main/features/marketplace_reconcile.ts
@@ -20,6 +20,8 @@ import * as path from 'node:path';
import {
userMarketplaceAgentDir, userMarketplaceSkillDir,
} from '../paths';
+import { clearAgentListCache } from './agents';
+import { clearSkillListCache } from './skills';
import {
readInstalls, addAgentInstall, addSkillInstall,
type AgentInstall, type SkillInstall,
@@ -71,7 +73,7 @@ function _setStatus(next: ReconcileStatus): void {
}
/** Pre-reconcile step: sync the local cloud manifest against the server catalog. For every
- * installed item, look up the server's current (version, published_at). When the server has
+ * installed item, look up the server's current (version, updated_at/published_at). When the server has
* newer values, write them back into the manifest — the subsequent `reconcileInstalls` pass
* then detects the mismatch against per-machine `_install.json` and re-pulls the blob.
*
@@ -105,14 +107,14 @@ export async function checkServerUpdatesForInstalls(uid: string): Promise<{ upda
for (const a of manifest.agents) {
const server = agentMap.get(a.id);
if (!server) continue;
- if (server.version !== a.version || server.published_at !== a.published_at) {
- log.info(`server-update agent ${a.id}: v${a.version} → v${server.version} (published_at ${a.published_at} → ${server.published_at})`);
- // Replace the row in the manifest; reconcile will detect the version/published_at
+ if (server.version !== a.version || _freshnessAt(server) !== _freshnessAt(a)) {
+ log.info(`server-update agent ${a.id}: v${a.version} → v${server.version} (freshness ${_freshnessAt(a)} → ${_freshnessAt(server)})`);
+ // Replace the row in the manifest; reconcile will detect the version/freshness
// mismatch against `_install.json` and re-pull. agent_json_url is reused (server
// overwrites the same COS key on republish — see Server `api/marketplace.py::upload_agent`).
await addAgentInstall(uid, {
id: a.id, version: server.version, published_at: server.published_at,
- agent_json_url: a.agent_json_url, create_uid: a.create_uid,
+ updated_at: server.updated_at, agent_json_url: a.agent_json_url, create_uid: a.create_uid,
});
updated_agents++;
}
@@ -120,11 +122,11 @@ export async function checkServerUpdatesForInstalls(uid: string): Promise<{ upda
for (const s of manifest.skills) {
const server = skillMap.get(s.id);
if (!server) continue;
- if (server.version !== s.version || server.published_at !== s.published_at) {
- log.info(`server-update skill ${s.id}: v${s.version} → v${server.version} (published_at ${s.published_at} → ${server.published_at})`);
+ if (server.version !== s.version || _freshnessAt(server) !== _freshnessAt(s)) {
+ log.info(`server-update skill ${s.id}: v${s.version} → v${server.version} (freshness ${_freshnessAt(s)} → ${_freshnessAt(server)})`);
await addSkillInstall(uid, {
id: s.id, version: server.version, published_at: server.published_at,
- bundle_url: s.bundle_url, create_uid: s.create_uid,
+ updated_at: server.updated_at, bundle_url: s.bundle_url, create_uid: s.create_uid,
});
updated_skills++;
}
@@ -135,7 +137,7 @@ export async function checkServerUpdatesForInstalls(uid: string): Promise<{ upda
return { updated_agents, updated_skills };
}
-interface _CatalogRow { version: string; published_at: number }
+interface _CatalogRow { version: string; published_at: number; updated_at?: number }
/** Paginate the public `/marketplace/{kind}/list` endpoint and collapse to (id → version + ts).
* Page-size 100 × 20 pages = 2000 row cap (well above current catalog scale). */
@@ -143,13 +145,17 @@ async function _fetchServerCatalogMap(kind: 'agents' | 'skills'): Promise<Map<st
const out = new Map<string, _CatalogRow>();
const PAGE_SIZE = 100;
for (let page = 1; page <= 20; page++) {
- const r = await postJson<{ list: Array<{ id?: string; version?: string; published_at?: number }>; total?: number }>(
+ const r = await postJson<{ list: Array<{ id?: string; version?: string; published_at?: number; updated_at?: number }>; total?: number }>(
`/marketplace/${kind}/list`, { page, size: PAGE_SIZE },
);
const list = r.list || [];
for (const row of list) {
if (typeof row.id === 'string' && typeof row.version === 'string' && typeof row.published_at === 'number') {
- out.set(row.id, { version: row.version, published_at: row.published_at });
+ out.set(row.id, {
+ version: row.version,
+ published_at: row.published_at,
+ ...(typeof row.updated_at === 'number' ? { updated_at: row.updated_at } : {}),
+ });
}
}
if (list.length < PAGE_SIZE) break;
@@ -205,8 +211,12 @@ export async function reconcileInstalls(uid: string): Promise<{ pulled_agents: n
await Promise.all([...agentTasks, ...skillTasks]);
if (pulled_skills > 0) {
+ try { clearSkillListCache(); } catch { /* list cache may not be loaded yet */ }
try { invalidateCoreAgentSkills(); } catch { /* runner may not be loaded yet */ }
}
+ if (pulled_agents > 0) {
+ try { clearAgentListCache(); } catch { /* list cache may not be loaded yet */ }
+ }
_setStatus({
state: 'done', total, pulled: pulled_agents + pulled_skills,
failed, updated_at: Date.now(),
@@ -216,14 +226,14 @@ export async function reconcileInstalls(uid: string): Promise<{ pulled_agents: n
}
/** Need-pull check: missing dir / missing agent.json / `_install.json::version` mismatch.
- * Mirrors the cache freshness rule from marketplace_cache.ts (version + published_at). */
+ * Mirrors the cache freshness rule from marketplace_cache.ts (version + updated_at fallback). */
function _agentNeedsPull(uid: string, row: AgentInstall): boolean {
const dir = userMarketplaceAgentDir(uid, row.id);
const agentJsonFile = path.join(dir, 'agent.json');
if (!fs.existsSync(agentJsonFile)) return true;
const meta = _readInstallMeta(dir);
if (!meta) return true;
- return meta.version !== row.version || meta.published_at !== row.published_at;
+ return meta.version !== row.version || _freshnessAt(meta) !== _freshnessAt(row);
}
function _skillNeedsPull(uid: string, row: SkillInstall): boolean {
@@ -231,10 +241,14 @@ function _skillNeedsPull(uid: string, row: SkillInstall): boolean {
if (!fs.existsSync(path.join(dir, 'SKILL.md'))) return true;
const meta = _readInstallMeta(dir);
if (!meta) return true;
- return meta.version !== row.version || meta.published_at !== row.published_at;
+ return meta.version !== row.version || _freshnessAt(meta) !== _freshnessAt(row);
}
-interface InstallMeta { version: string; published_at: number; create_uid?: string }
+interface InstallMeta { version: string; published_at: number; updated_at?: number; create_uid?: string }
+
+function _freshnessAt(row: { published_at: number; updated_at?: number }): number {
+ return typeof row.updated_at === 'number' ? row.updated_at : row.published_at;
+}
function _readInstallMeta(dir: string): InstallMeta | null {
const f = path.join(dir, '_install.json');
@@ -245,6 +259,7 @@ function _readInstallMeta(dir: string): InstallMeta | null {
return {
version: j.version,
published_at: j.published_at,
+ ...(typeof j.updated_at === 'number' ? { updated_at: j.updated_at } : {}),
create_uid: typeof j.create_uid === 'string' ? j.create_uid : '',
};
} catch { return null; }
@@ -270,6 +285,7 @@ async function _pullAgent(uid: string, row: AgentInstall): Promise<void> {
await fsp.writeFile(path.join(dir, 'agent.json'), text, 'utf8');
await _writeInstallMeta(dir, {
version: row.version, published_at: row.published_at,
+ ...(typeof row.updated_at === 'number' ? { updated_at: row.updated_at } : {}),
create_uid: row.create_uid || '',
});
}
@@ -292,6 +308,7 @@ async function _pullSkill(uid: string, row: SkillInstall): Promise<void> {
if (!fs.existsSync(path.join(dir, 'SKILL.md'))) throw new Error('bundle missing SKILL.md');
await _writeInstallMeta(dir, {
version: row.version, published_at: row.published_at,
+ ...(typeof row.updated_at === 'number' ? { updated_at: row.updated_at } : {}),
create_uid: row.create_uid || '',
});
}
diff --git a/src/main/features/projects.ts b/src/main/features/projects.ts
index 108ae29a..130f21dd 100644
--- a/src/main/features/projects.ts
+++ b/src/main/features/projects.ts
@@ -378,6 +378,31 @@ export async function getBindings(uid: string, projectId: string): Promise<Proje
return _readBindings(uid, projectId);
}
+export async function pruneBindings(
+ uid: string,
+ projectId: string,
+ valid: { agents?: ReadonlySet<string>; skills?: ReadonlySet<string> },
+): Promise<{ ok: true; bindings: ProjectBindings; pruned: ProjectBindings } | { ok: false; error: ProjectError }> {
+ await _ensurePromoted(uid);
+ if (!fs.existsSync(projectMetaFile(uid, projectId))) return { ok: false, error: 'not_found' };
+ const cur = await _readBindings(uid, projectId);
+ const validAgents = valid.agents;
+ const validSkills = valid.skills;
+ const next: ProjectBindings = {
+ agents: validAgents ? cur.agents.filter((id) => validAgents.has(id)) : cur.agents,
+ skills: validSkills ? cur.skills.filter((id) => validSkills.has(id)) : cur.skills,
+ };
+ const pruned: ProjectBindings = {
+ agents: validAgents ? cur.agents.filter((id) => !validAgents.has(id)) : [],
+ skills: validSkills ? cur.skills.filter((id) => !validSkills.has(id)) : [],
+ };
+ if (pruned.agents.length || pruned.skills.length) {
+ await _writeBindings(uid, projectId, next);
+ log.info(`pruned stale bindings user=${uid} pid=${projectId} agents=${pruned.agents.length} skills=${pruned.skills.length}`);
+ }
+ return { ok: true, bindings: next, pruned };
+}
+
/** Single resolver, threaded through runTurn alongside the workspace lookup.
*
* - `null` = orphan conversation (no project_id) → no scope filter; legacy
diff --git a/src/main/features/reflection-digest.ts b/src/main/features/reflection-digest.ts
index 8bd674ef..c244a9ae 100644
--- a/src/main/features/reflection-digest.ts
+++ b/src/main/features/reflection-digest.ts
@@ -8,10 +8,11 @@
* cooldown window — see `reflection-trigger.ts` for the call site.
*
* Scope:
- * - Only `<uid>-gconv-*.jsonl` are scanned (main conversations).
- * Subagent invocations are not in scope (the `sub` kind has been
- * deprecated; group_chat `gmember` sessions are the new home for
- * per-agent histories).
+ * - `<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.
*/
@@ -20,6 +21,7 @@ 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');
@@ -157,26 +159,43 @@ export async function buildAgentReflectionDigest(
for (const conv of convs) {
if (!targetMatches(conv.agent_id || '')) continue;
- if (!conv.session_id) continue;
- let file: string;
- try { file = userSessionFile(uid, conv.session_id); }
- catch { continue; }
- let stat: fs.Stats;
- try { stat = fs.statSync(file); }
- catch { continue; }
- if (stat.mtimeMs < sinceMs) continue;
-
- let raw: string;
- try { raw = fs.readFileSync(file, 'utf8'); }
- catch (err) { log.warn(`read ${file} failed: ${(err as Error).message}`); continue; }
- const messages: any[] = [];
- for (const line of raw.split('\n')) {
- if (!line.trim()) continue;
- try { messages.push(JSON.parse(line)); }
- catch { /* skip malformed line */ }
+ // 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);
}
- aggregateSession(messages, 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/skills.ts b/src/main/features/skills.ts
index d8e08ffe..3e746385 100644
--- a/src/main/features/skills.ts
+++ b/src/main/features/skills.ts
@@ -51,6 +51,10 @@ import {
ValidationReport as QualityReport,
} from '../quality';
import { persistReport as persistQualityReport } from '../quality/report';
+import {
+ DEFAULT_MARKETPLACE_CATEGORY_CODE,
+ normalizeMarketplaceCategoryCode,
+} from './marketplace_biz';
// Names hidden from the in-app skill source-tree view. `_install.json` (marketplace install
// version pin) and `_cache.json` (marketplace cache LRU bookkeeping) are tooling sidecars,
@@ -62,6 +66,7 @@ const SKILL_TREE_IGNORE: ReadonlySet<string> = new Set([
// Starts with a letter, then letters/digits/_/-; single spaces are allowed
// between word groups (no leading/trailing/consecutive spaces).
const SKILL_NAME_RE = /^[A-Za-z][A-Za-z0-9_-]*(?: [A-Za-z0-9_-]+)*$/;
+const CATEGORY_LINE_RE = /(^|\n)category\s*:\s*(.*?)(?=\n|$)/;
// Block syntax: `<<<skill-file path=<rel> ... >>>`. Cross-skill writes (the
// old `skill=<id>` attribute) are no longer supported — every skill is
// self-contained. Attribute order is flexible.
@@ -86,8 +91,8 @@ export interface SkillListing {
source: SkillSource;
description_zh: string;
description_en: string;
- /** Marketplace category code (`education` / `ecommerce` / `rnd` / …). Empty string when
- * the SKILL.md frontmatter doesn't set one — UI treats that as "uncategorized". */
+ /** Marketplace category code. Empty string when the SKILL.md frontmatter doesn't set one —
+ * UI treats that as "uncategorized". */
category: string;
/** **Computed at load time, not persisted.** Filled by `listSkills` from
* `features/component_enabled.ts`. Defaults to true unless the user has
@@ -154,8 +159,8 @@ export interface SkillFrontmatter {
description?: string;
description_zh?: string;
description_en?: string;
- /** Marketplace category code; required for skills published to the marketplace, optional for
- * user-created skills (defaults to empty string / "uncategorized" in `listSkills` output). */
+ /** Marketplace category code. Model-authored SKILL.md writes must choose one of the known
+ * category codes; legacy/manual entries without one still list as "uncategorized". */
category?: string;
[key: string]: string | string[] | undefined;
}
@@ -251,8 +256,9 @@ function skillBaseDir(source: SkillSource): string {
interface SkillListCache { stamp: string; data: SkillListing[] }
let _skillListCache: SkillListCache | null = null;
-function _invalidateSkillListCache(): void {
+function _invalidateSkillListCache(opts: { markDirty?: boolean } = {}): void {
_skillListCache = null;
+ if (opts.markDirty === false) return;
// Sync engine dirty signal (lazy-require — stripped in OrkasOpen). Mirrors the pattern in
// `agents.ts::_invalidateAgentListCache`: every cache-invalidate is also a disk-mutation
// point, co-locating keeps wiring tight.
@@ -271,6 +277,12 @@ export function invalidateSkillCachesForEdit(): void {
invalidateCoreAgentSkills().catch(() => { /* runner may not be loaded yet */ });
}
+/** Drop only the renderer-facing list cache. Marketplace reconcile writes local marketplace
+ * installs, not cloud/custom skill files, so it should not mark the sync domain dirty. */
+export function clearSkillListCache(): void {
+ _invalidateSkillListCache({ markDirty: false });
+}
+
/** A skill id resolves to a built-in iff there's a directory with that name
* under the runtime built-in tree. The src tree may be missing in packaged
* builds, so the runtime tree is the authoritative check. */
@@ -502,10 +514,12 @@ export function skillMdContent(
}
const cleanZh = sanitize(zh);
const cleanEn = sanitize(en);
- const cleanCategory = sanitize(category || '');
+ const cleanCategory = category && String(category).trim()
+ ? sanitize(normalizeMarketplaceCategoryCode(category))
+ : '';
const trimmedBody = body.replace(/^\n+/, '');
- // Emit `category` only when explicitly provided — user-created skills without a category yet
- // are perfectly valid; the field becomes mandatory only at marketplace upload time.
+ // Emit `category` only when explicitly provided. Model-authored SKILL.md writes are validated
+ // elsewhere and must include one; this helper stays tolerant for legacy/manual specs.
const categoryLine = cleanCategory ? `\ncategory: "${cleanCategory}"` : '';
return `---\nname: "${cleanName}"\ndescription_zh: "${cleanZh}"\ndescription_en: "${cleanEn}"${categoryLine}\n---\n\n${trimmedBody}`;
}
@@ -520,6 +534,28 @@ export function splitSkillMd(text: string): { meta: SkillFrontmatter; body: stri
};
}
+function ensureSkillMdCategoryForWrite(content: string): string {
+ if (!content.startsWith('---')) return content;
+ const end = content.indexOf('---', 3);
+ if (end === -1) return content;
+ const meta = parseSkillFrontmatter(content);
+ const current = String(meta.category || '').trim();
+ const repaired = current
+ ? normalizeMarketplaceCategoryCode(current)
+ : DEFAULT_MARKETPLACE_CATEGORY_CODE;
+ if (current && repaired === current) {
+ return content;
+ }
+ const line = `category: "${repaired}"`;
+ let fm = content.slice(3, end);
+ if (CATEGORY_LINE_RE.test(fm)) {
+ fm = fm.replace(CATEGORY_LINE_RE, (m, prefix) => `${prefix}${line}`);
+ } else {
+ fm = `${fm}${fm.endsWith('\n') ? '' : '\n'}${line}\n`;
+ }
+ return `---${fm}${content.slice(end)}`;
+}
+
export async function getCustomSkill(skillId: string): Promise<CustomSkill | null> {
const d = customSkillDir(skillId);
if (!fs.existsSync(d) || !fs.statSync(d).isDirectory()) return null;
@@ -1079,21 +1115,24 @@ export async function writeSkillFileForEditChecked(
relpath: string,
content: string,
): Promise<WriteSkillFileResult> {
+ const contentForWrite = relpath.toUpperCase() === 'SKILL.MD'
+ ? ensureSkillMdCategoryForWrite(content)
+ : content;
const customDir = customSkillDir(skillId);
if (fs.existsSync(customDir) && fs.statSync(customDir).isDirectory()) {
- return writeCustomSkillFileChecked(skillId, relpath, content);
+ return writeCustomSkillFileChecked(skillId, relpath, contentForWrite);
}
if (isBuiltinSkill(skillId) && false) {
// Built-in (platform-installed) skill edit. Validate first; defer the
// actual write to skills_dev (which knows the target install dir).
- const report = validateSkillFile({ relpath, content });
+ const report = validateSkillFile({ relpath, content: contentForWrite });
void persistQualityReport({
uid: getActiveUserId(), kind: 'skill', id: skillId, report,
});
if (!report.ok) return { ok: false, report };
try {
const dev = await import('./skills_dev');
- const written = await dev.writeBuiltinSkillFile(skillId, relpath, content);
+ const written = await dev.writeBuiltinSkillFile(skillId, relpath, contentForWrite);
return written ? { ok: true, report } : { ok: false, report, reason: 'invalid_path' };
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
@@ -1296,11 +1335,14 @@ export interface SkillContainerResult {
error?: string;
}
-/** Apply a parsed `<skill>` container from commander. Routes to create vs
- * edit by `container.skillId`. Built-in skills are read-only here — same
- * policy as the per-skill edit chat outside dev mode. Best-effort writes
- * per-file: a single rejected path doesn't roll back earlier successes
- * (matches `streamSendToSkillChat`'s file-by-file outcome). */
+/** Apply a parsed `<skill>` container from commander. Routes to edit when
+ * `container.skillId` resolves to an existing skill; otherwise a full
+ * SKILL.md payload is treated as create. This makes the commander path
+ * resilient to LLMs that mistakenly include `<skill_id>` while creating a
+ * brand-new skill. Built-in skills are read-only here — same policy as the
+ * per-skill edit chat outside dev mode. Best-effort writes per-file: a
+ * single rejected path doesn't roll back earlier successes (matches
+ * `streamSendToSkillChat`'s file-by-file outcome). */
export async function applySkillContainerFromCommander(
container: SkillContainerExtracted,
): Promise<SkillContainerResult> {
@@ -1314,6 +1356,11 @@ export async function applySkillContainerFromCommander(
}
async function _applySkillContainerCreate(files: SkillFileBlock[]): Promise<SkillContainerResult> {
+ files = files.map((f) => (
+ f.path.toUpperCase() === 'SKILL.MD'
+ ? { ...f, content: ensureSkillMdCategoryForWrite(f.content || '') }
+ : f
+ ));
// SKILL.md is mandatory in the create branch — that's where the skill id
// (frontmatter `name`) and bilingual descriptions are sourced from.
const skillMd = files.find((f) => f.path.toUpperCase() === 'SKILL.MD');
@@ -1359,7 +1406,7 @@ async function _applySkillContainerCreate(files: SkillFileBlock[]): Promise<Skil
// All files passed EXTREME — proceed with the actual create.
const desc = migrateDescriptionPair(meta as any);
const seedDescription = desc.description_zh || desc.description_en || '';
- const created = await createCustomSkill(name, seedDescription);
+ const created = await createCustomSkill(name, seedDescription, String(meta.category || ''));
if (!created) return { ok: false, error: t('skills.errors.create_failed') };
const written: string[] = [];
@@ -1388,7 +1435,14 @@ async function _applySkillContainerCreate(files: SkillFileBlock[]): Promise<Skil
async function _applySkillContainerEdit(skillId: string, files: SkillFileBlock[]): Promise<SkillContainerResult> {
const skill = await getSkillForEdit(skillId);
- if (!skill) return { ok: false, error: t('skills.errors.skill_not_found', { id: skillId }) };
+ if (!skill) {
+ const hasSkillMd = files.some((f) => f.path.toUpperCase() === 'SKILL.MD');
+ if (hasSkillMd) {
+ log.info(`commander target skill=${skillId} missing; treating SKILL.md payload as create`);
+ return _applySkillContainerCreate(files);
+ }
+ 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).
@@ -1451,6 +1505,7 @@ export async function buildSkillEditSystemPrompt(skill: {
description?: string;
description_zh?: string;
description_en?: string;
+ category?: string;
dir?: string;
}): Promise<string> {
const files = await listCustomSkillFiles(skill.id || '');
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 247d2678..d291018d 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -127,8 +127,9 @@ const invokeHandlers: Record<string, InvokeHandler> = {
// grey out the input + show a banner without making a second IPC round trip.
// True for unbound (no agent_id) — input always allowed there.
const agent_enabled = conv.agent_id ? isAgentEnabled(ctx.userId, conv.agent_id) : true;
+ const runtime = await groupChat.runtimeStatus(ctx.userId, cid);
return {
- conversation: { ...conv, agent_enabled },
+ conversation: { ...conv, ...runtime, agent_enabled },
history: await chats.getMessages(ctx.userId, cid, limit),
};
},
@@ -198,20 +199,24 @@ const invokeHandlers: Record<string, InvokeHandler> = {
// ── 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
- // the renderer can paint the detail page in one round-trip; unknown ids
- // (referent deleted) are filtered out of the joined view but kept in the
- // raw `agents` / `skills` arrays so the user can see + clean up stale
- // bindings.
+ // the renderer can paint the detail page in one round-trip. Unknown ids
+ // (referent deleted) are pruned here so stale bindings never become user
+ // cleanup work.
'projects.bindings.list': async ({ projectId }, ctx) => {
if (!safeId(projectId)) throw new Error('invalid projectId');
if (!await projects.projectExists(ctx.userId, projectId)) throw new Error('not_found');
- const bindings = await projects.getBindings(ctx.userId, projectId);
const [agentList, skillList] = await Promise.all([
agents.listAgents(),
skills.listSkills(),
]);
const agentById = new Map(agentList.map((a: any) => [a.agent_id, a]));
const skillById = new Map(skillList.map((s: any) => [s.id, s]));
+ const pruned = await projects.pruneBindings(ctx.userId, projectId, {
+ agents: new Set(agentList.map((a: any) => a.agent_id)),
+ skills: new Set(skillList.map((s: any) => s.id)),
+ });
+ if (!pruned.ok) throw new Error((pruned as { error: string }).error);
+ const bindings = pruned.bindings;
return {
bindings,
agentDetails: bindings.agents
@@ -340,6 +345,11 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return groupChat.readPlanForCid(ctx.userId, cid);
},
+ 'groupChat.runtimeStatus': async ({ cid }, ctx) => {
+ if (!safeId(cid)) throw new Error('invalid cid');
+ return groupChat.runtimeStatus(ctx.userId, cid);
+ },
+
'groupChat.retryStep': async ({ cid, stepIndex }, ctx) => {
if (!safeId(cid)) throw new Error('invalid cid');
return groupChat.retryStep(ctx.userId, cid, Number(stepIndex));
@@ -487,8 +497,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { agent };
},
- 'agents.create': async ({ name = '', description = '', description_zh, description_en, workflow = '', icon, color, runtime, category } = {}) => {
- return { agent: await agents.createCustomAgent({ name, description, description_zh, description_en, workflow, icon, color, runtime, category }) };
+ 'agents.create': async ({ name = '', description = '', description_zh, description_en, workflow = '', icon, color, runtime, category, output_format } = {}) => {
+ return { agent: await agents.createCustomAgent({ name, description, description_zh, description_en, workflow, icon, color, runtime, category, output_format }) };
},
@@ -515,6 +525,21 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { ok: true, enabled };
},
+ 'agents.cliProjectDir.get': async ({ agent_id }, ctx) => {
+ if (!agents.isValidAgentId(agent_id)) throw new Error('invalid agent_id');
+ const info = await agents.getAgentCliProjectDirInfo(ctx.userId, agent_id);
+ if (!info) throw new Error('agent not found');
+ return { info };
+ },
+
+ 'agents.cliProjectDir.set': async ({ agent_id, path: dirPath = '' }, ctx) => {
+ if (!agents.isValidAgentId(agent_id)) throw new Error('invalid agent_id');
+ if (typeof dirPath !== 'string') throw new Error('path must be string');
+ const info = await agents.setAgentCliProjectDir(ctx.userId, agent_id, dirPath);
+ if (!info) throw new Error('agent not found');
+ return { info };
+ },
+
'agents.chat.history': async ({ agent_id, limit = 500 }, ctx) => {
if (!agents.isValidAgentId(agent_id)) throw new Error('invalid agent_id');
if (!(await agents.getAgent(agent_id))) throw new Error('agent not found');
@@ -646,38 +671,50 @@ const invokeHandlers: Record<string, InvokeHandler> = {
'marketplace.listSkills': async (opts = {}) => marketplace.listMarketplaceSkills(opts),
// Detail endpoints (cache-first) — used by the marketplace panel's detail view to render
- // full content. Caller passes the list-row's (version, published_at) so we can short-circuit
+ // full content. Caller passes the list-row's (version, freshness timestamp) so we can short-circuit
// on a hot cache. Sweep is invoked once per openMarketplace at the entry point.
- 'marketplace.detailAgent': async ({ id, version, published_at }) => {
+ 'marketplace.detailAgent': async ({ id, version, published_at, updated_at }) => {
if (!id || typeof id !== 'string') throw new Error('id required');
if (typeof version !== 'string' || typeof published_at !== 'number') {
throw new Error('version + published_at required');
}
- return marketplace.getAgentDetail(id, { version, published_at });
+ return marketplace.getAgentDetail(id, {
+ version, published_at,
+ ...(typeof updated_at === 'number' ? { updated_at } : {}),
+ });
},
- 'marketplace.detailSkill': async ({ id, version, published_at }) => {
+ 'marketplace.detailSkill': async ({ id, version, published_at, updated_at }) => {
if (!id || typeof id !== 'string') throw new Error('id required');
if (typeof version !== 'string' || typeof published_at !== 'number') {
throw new Error('version + published_at required');
}
- return marketplace.getSkillDetail(id, { version, published_at });
+ return marketplace.getSkillDetail(id, {
+ version, published_at,
+ ...(typeof updated_at === 'number' ? { updated_at } : {}),
+ });
},
- 'marketplace.installAgent': async ({ id, version, published_at }) => {
+ 'marketplace.installAgent': async ({ id, version, published_at, updated_at }) => {
if (!id || typeof id !== 'string') throw new Error('id required');
if (typeof version !== 'string' || typeof published_at !== 'number') {
throw new Error('version + published_at required');
}
- return marketplace.installMarketplaceAgent(id, { version, published_at });
+ return marketplace.installMarketplaceAgent(id, {
+ version, published_at,
+ ...(typeof updated_at === 'number' ? { updated_at } : {}),
+ });
},
- 'marketplace.installSkill': async ({ id, version, published_at }) => {
+ 'marketplace.installSkill': async ({ id, version, published_at, updated_at }) => {
if (!id || typeof id !== 'string') throw new Error('id required');
if (typeof version !== 'string' || typeof published_at !== 'number') {
throw new Error('version + published_at required');
}
- return marketplace.installMarketplaceSkill(id, { version, published_at });
+ return marketplace.installMarketplaceSkill(id, {
+ version, published_at,
+ ...(typeof updated_at === 'number' ? { updated_at } : {}),
+ });
},
// Uninstall is non-dev: wipes the local install copy + manifest entry. Does NOT touch the
@@ -1071,6 +1108,44 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { ok: true, text, size: st.size };
},
+ // Write a UTF-8 text file into the workspace (or current cid's attachment
+ // dir). Sandbox parity with `produced.readText`: same scope, same 2MB cap on
+ // the resulting bytes — the chat-md drawer is the sole caller today, and
+ // the file's job is "human edits the LLM's md output", so anything larger
+ // belongs in the OS editor (open via reveal).
+ 'produced.writeText': async (payload, ctx) => {
+ const target = payload?.path;
+ const content = payload?.content;
+ if (typeof target !== 'string' || !target) {
+ throw new Error('missing path');
+ }
+ if (typeof content !== 'string') {
+ throw new Error('missing content');
+ }
+ const MAX_TEXT_BYTES = 2 * 1024 * 1024;
+ const bytes = Buffer.byteLength(content, 'utf8');
+ 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) {
+ throw new Error('path is outside the user workspace');
+ }
+ try {
+ fs.writeFileSync(norm, content, 'utf8');
+ } catch (err) {
+ return { ok: false, error: String((err as Error).message || 'write failed') };
+ }
+ return { ok: true, size: bytes };
+ },
+
// Read the install data root (`<container>/data`) — read-only display
// for the settings page "Data root" row. WS_ROOT is process-stable so
// no async work is needed.
@@ -1092,6 +1167,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {
// User-account login (Google / Apple OAuth). Stripped from the OrkasOpen build.
+ // User feedback from Settings. Depends on the account session for Server auth.
+
// Multi-device sync. Stripped from the OrkasOpen build (depends on account).
// Quality validator — renderer reads persisted ValidationReports to display
@@ -1155,22 +1232,12 @@ const streamHandlers: Record<string, StreamHandler> = {
yield { type: 'error', text: sendRes.error || 'send failed' };
return;
}
- let sawWorkActivity = false;
drainLoop: while (!cancelled) {
while (buf.length) {
const ev = buf.shift()!;
- if (ev.type === 'state_changed') {
- const st = (ev as any).state;
- if (st && st.status === 'running') sawWorkActivity = true;
- if (sawWorkActivity && st && st.status !== 'running'
- && (!st.in_flight || st.in_flight.length === 0)
- && groupChat.busIsQuiescent(ctx.userId, cid)) {
- yield { type: 'event', event: { stream: 'group', data: ev } };
- break drainLoop;
- }
- }
yield { type: 'event', event: { stream: 'group', data: ev } };
}
+ if (groupChat.busIsQuiescent(ctx.userId, cid)) break drainLoop;
if (cancelled) break;
await new Promise<void>((resolve) => { wake = resolve; });
}
@@ -1180,11 +1247,52 @@ const streamHandlers: Record<string, StreamHandler> = {
}
},
- 'groupChat.events': async function* ({ cid }, ctx, signal) {
+ 'groupChat.events': async function* ({ cid, untilIdle }, ctx, signal) {
if (!safeId(cid)) {
yield { type: 'error', text: 'invalid cid' };
return;
}
+ if (untilIdle) {
+ const buf: GroupEvent[] = [];
+ let wake: (() => void) | null = null;
+ let cancelled = signal.aborted;
+ let sawWorkActivity = !groupChat.busIsQuiescent(ctx.userId, cid);
+ 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) => {
+ buf.push(ev);
+ const w = wake; wake = null; w?.();
+ });
+ try {
+ while (!cancelled) {
+ while (buf.length) {
+ const ev = buf.shift()!;
+ if (ev.type === 'process') sawWorkActivity = true;
+ if (ev.type === 'artifact_created') sawWorkActivity = true;
+ if (ev.type === 'message') {
+ const msg = (ev as any).msg;
+ if (msg && msg.from !== 'user') sawWorkActivity = true;
+ }
+ if (ev.type === 'state_changed') {
+ const st = ev.state;
+ const inFlight = Array.isArray(st?.in_flight) ? st.in_flight : [];
+ if (st?.status === 'running' || inFlight.length > 0 || !groupChat.busIsQuiescent(ctx.userId, cid)) {
+ sawWorkActivity = true;
+ }
+ }
+ yield ev;
+ if (sawWorkActivity && groupChat.busIsQuiescent(ctx.userId, cid)) return;
+ }
+ if (sawWorkActivity && groupChat.busIsQuiescent(ctx.userId, cid)) return;
+ if (cancelled) break;
+ await new Promise<void>((resolve) => { wake = resolve; });
+ }
+ } finally {
+ try { unsub(); } catch { /* ignore */ }
+ try { signal.removeEventListener?.('abort', onAbort); } catch { /* ignore */ }
+ }
+ return;
+ }
for await (const ev of groupChat.streamEvents(ctx.userId, cid, { abortSignal: signal })) {
yield ev;
}
diff --git a/src/main/model/client.ts b/src/main/model/client.ts
index b7022d77..d2833473 100644
--- a/src/main/model/client.ts
+++ b/src/main/model/client.ts
@@ -124,6 +124,16 @@ export interface ChatOptions {
* and attaches a `artifacts[]` list to the assistant message so the
* renderer embeds each interactive web-app artifact in the bubble. */
onArtifactCreated?: (a: { id: string; title: string }) => void;
+ /** Fired at turn start with each skill id that entered the system-prompt
+ * index, split by source system (`A.custom` / `A.platform` / `B`).
+ * `features/group_chat` buffers per turn and emits `skill_advertised`
+ * signals at turn-end (grouped by system). See expert-signals plan
+ * §4.1 + PC/CLAUDE.md §4 constraint 9. */
+ onSkillAdvertised?: (skill_id: string, system: 'A.custom' | 'A.platform' | 'B') => void;
+ /** Fired when the agent's `read_file` resolves to a SKILL.md path inside
+ * any of the three skill roots. Bus buffers per turn and emits one
+ * `skill_invoked` signal per (system, skill_id) pair at turn-end. */
+ onSkillInvoked?: (skill_id: string, system: 'A.custom' | 'A.platform' | 'B', trigger: 'read_file') => void;
/** Prompt-cache TTL policy. Undefined lets pi-ai pick its default
* (`"short"` = Anthropic 5m / OpenAI in-memory). `"long"` opts into
* extended retention (Anthropic 1h with 2x write premium / OpenAI 24h).
diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.ts
index 38a43b2d..83da51e0 100644
--- a/src/main/model/core-agent/client.ts
+++ b/src/main/model/core-agent/client.ts
@@ -92,6 +92,8 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
onFileWritten,
hasProducedPath,
onArtifactCreated,
+ onSkillAdvertised,
+ onSkillInvoked,
cacheRetention,
thinkingLevel,
} = opts;
@@ -188,6 +190,53 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
...(onFileWritten ? { onFileWritten } : {}),
...(hasProducedPath ? { hasProducedPath } : {}),
...(onArtifactCreated ? { onArtifactCreated } : {}),
+ ...(onSkillAdvertised ? { onSkillAdvertised } : {}),
+ ...(onSkillInvoked ? { onSkillInvoked } : {}),
+ onNativeSearchInjected: (info) => {
+ recorder?.record({
+ type: 'progress',
+ event: { stream: 'native_search', data: { phase: 'injected', ...info } },
+ });
+ },
+ // rotating-provider commits / surfaced-error candidate notice. Rewrite
+ // the archive row so model / provider / profile reflect the candidate
+ // that actually owned this call's visible outcome, not the rotating-
+ // provider's primary label. Recorder may not be set yet at the moment
+ // buildRunner eagerly constructs the rotating-provider; fires at runtime
+ // when complete()/stream() actually picks a candidate, so the recorder
+ // is always live by then.
+ onCandidateChosen: (info) => {
+ recorder?.setActiveCandidate(info);
+ },
+ });
+ const { runner, providerId, modelId, resolvedSystemPrompt, profileId, entryId, toolDefs } = built;
+
+ recorder = startRecording({
+ userId,
+ sessionId,
+ input: {
+ message,
+ systemPrompt: resolvedSystemPrompt,
+ model: modelId,
+ provider: providerId,
+ profileId,
+ entryId,
+ tools: toolDefs,
+ },
+ context: {
+ ...(agentId ? { agentId } : {}),
+ ...(cid ? { cid } : {}),
+ ...(workingDir ? { workingDir } : {}),
+ // skillList: undefined → no allowlist (full listing); preserve as null
+ // so the renderer can distinguish "all skills" from "explicit []".
+ skillList: skillList === undefined ? null : [...skillList],
+ ...(extraRoots && extraRoots.length ? { extraRoots: [...extraRoots] } : {}),
+ ...(readOnlyExtraRoots && readOnlyExtraRoots.length ? { readOnlyExtraRoots: [...readOnlyExtraRoots] } : {}),
+ ...(cacheRetention ? { cacheRetention } : {}),
+ idleTimeoutSec: idleTimeout,
+ ...(images && images.length ? { imageCount: images.length } : {}),
+ ...(abortSignal ? { hasAbortSignal: true } : {}),
+ },
});
const { runner, providerId, modelId } = built;
diff --git a/src/main/model/core-agent/file-tools.ts b/src/main/model/core-agent/file-tools.ts
index 1a3f11d5..a9c79764 100644
--- a/src/main/model/core-agent/file-tools.ts
+++ b/src/main/model/core-agent/file-tools.ts
@@ -46,6 +46,7 @@ import {
import { chatAttachmentDir } from '../../paths';
import { getWorkspacePath } from '../../features/user_workspace';
import { isPathAllowed } from '../../util/path-sandbox';
+import { parseSkillPath } from '../../features/expert_signals/skill_path';
const log = createLogger('file-tools');
@@ -90,6 +91,11 @@ export interface FileToolsOpts {
* picks up the project-scoped selection (per CLAUDE.md projects feature).
* Empty / missing → default-scope workspace. */
projectId?: string;
+ /** Fires when `read_file` resolves to a SKILL.md path under one of the
+ * three skill roots (System A.custom / A.platform / B). Bus collects
+ * per turn for the `skill_invoked` signal. Pure callback — exceptions
+ * swallowed, never blocks the tool result. */
+ onSkillInvoked?: (skill_id: string, system: 'A.custom' | 'A.platform' | 'B', trigger: 'read_file') => void;
}
/** Assemble the allowed-roots list for the current (uid, cid). File-tools
@@ -226,6 +232,17 @@ function createReadFileTool(opts: FileToolsOpts): AgentTool {
log.info(
`read_file user=${opts.userId} kind=${kind} covered=${cs}-${ce} total=${total} path=${abs}`,
);
+ // skill_invoked attribution: when the LLM read_file's a SKILL.md
+ // body, the body is the progressive-disclosure "use this skill"
+ // signal (per Claude Code conventions). Emit AFTER the successful
+ // text read — image / pdf / docx SKILL.md is not a real shape.
+ if (opts.onSkillInvoked) {
+ const parsed = parseSkillPath(abs, opts.userId);
+ if (parsed) {
+ try { opts.onSkillInvoked(parsed.skill_id, parsed.system, 'read_file'); }
+ catch (err) { log.warn(`onSkillInvoked callback failed: ${(err as Error).message}`); }
+ }
+ }
return { content: `${header}\n${result.content}\n</file>` };
} catch (err) {
if (err instanceof NeedStatError) {
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index 6633e8d9..9aba6c80 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -131,6 +131,26 @@ export interface BuildRunnerParams {
/** Fires after each successful `create_artifact` call. See `model/client.ts`
* `ChatOptions.onArtifactCreated`. */
onArtifactCreated?: (a: { id: string; title: string }) => void;
+ /** Fires once per skill id rendered into the system-prompt skills index,
+ * with its source system. Called at runner build time (before the LLM
+ * sees the prompt). Bus collects per turn for `skill_advertised`. */
+ onSkillAdvertised?: (skill_id: string, system: 'A.custom' | 'A.platform' | 'B') => void;
+ /** Fires when `read_file` resolves to a SKILL.md path inside any of the
+ * three skill roots. Bus collects per turn for `skill_invoked`. */
+ onSkillInvoked?: (skill_id: string, system: 'A.custom' | 'A.platform' | 'B', trigger: 'read_file') => void;
+ /** Fires when the pi-ai onPayload hook injects a vendor native web search
+ * tool schema for this call. Used by client.ts to record a synthetic
+ * `progress/native_search/injected` event into the devtools archive.
+ * May fire multiple times per chat turn if rotating-provider falls over
+ * to a secondary candidate. */
+ onNativeSearchInjected?: (info: NativeSearchInjectedInfo) => void;
+ /** Fires when rotating-provider commits to a candidate (success) or
+ * surfaces a non-rotatable error (failure). Used by client.ts to update
+ * the dev archive's recorded model / provider / profile so the stored
+ * row reflects the candidate that actually owned the visible outcome,
+ * not the rotating-provider's primary label. Fires at most once per
+ * call; not invoked when rotation rolls past a candidate. */
+ onCandidateChosen?: (info: { profileId: string; providerId: string; modelId: string }) => void;
}
/** Tool definition snapshot used to log "what tools did the LLM actually see
@@ -192,6 +212,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
getSystemPromptBlock({
...(renderAllowlist === undefined ? {} : { allowlist: [...renderAllowlist] }),
disabledIds: disabledSkillIds,
+ ...(params.onSkillAdvertised ? { onSkillAdvertised: params.onSkillAdvertised } : {}),
}),
]);
@@ -262,6 +283,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
...(params.projectId ? { projectId: params.projectId } : {}),
...(params.extraRoots?.length ? { extraRoots: params.extraRoots } : {}),
...(params.readOnlyExtraRoots?.length ? { readOnlyExtraRoots: params.readOnlyExtraRoots } : {}),
+ ...(params.onSkillInvoked ? { onSkillInvoked: params.onSkillInvoked } : {}),
})
: [];
@@ -486,6 +508,13 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
}
: undefined;
+ // Bridge System B advertised → ChatOptions.onSkillAdvertised. The SDK
+ // doesn't know about the host's skill-system taxonomy; we tag every id
+ // it surfaces as `'B'` before passing it up.
+ const onLearnedSkillAdvertised = params.onSkillAdvertised
+ ? (id: string) => params.onSkillAdvertised!(id, 'B')
+ : undefined;
+
const runner = new mod.AgentRunner({
config,
providers,
@@ -493,6 +522,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
...(wrappedTools.length ? { tools: wrappedTools } : {}),
...(params.skillList !== undefined ? { skillAllowlist: params.skillList } : {}),
...(onSkillCreated ? { onSkillCreated } : {}),
+ ...(onLearnedSkillAdvertised ? { onLearnedSkillAdvertised } : {}),
});
return {
diff --git a/src/main/model/core-agent/skill-registry.ts b/src/main/model/core-agent/skill-registry.ts
index 4907fa4f..dd246585 100644
--- a/src/main/model/core-agent/skill-registry.ts
+++ b/src/main/model/core-agent/skill-registry.ts
@@ -54,8 +54,8 @@ function skillSourceLabel(source: string): 'builtin' | 'custom' {
// `\`read_file(<ROOT>/<id>/SKILL.md)\` — ROOT by Source:\n` +
// `- custom: <abs path>\n` +
// `- builtin: <abs path>\n` +
-// `Use these ROOT values verbatim; do NOT use training-prior layouts (e.g. \`/data/custom/skills/\`).\n\n` +
-// per-entry lines `- **<id>** (Source: custom|builtin) — desc`
+// `Use these ROOT values verbatim.\n\n` +
+// per-entry lines `- **<display name>** (Source: custom|builtin; internal read id: <id>) — desc`
//
// Why the inline ROOT header (added 2026-05): putting only `(Source: ...)` on
// each entry and listing the path constants in a separate `## Resource locations`
@@ -90,7 +90,9 @@ async function renderSkillLines(
'`read_file(<ROOT>/<id>/SKILL.md)` — ROOT by Source:',
`- custom: ${customRoot}`,
`- builtin: ${builtinRoot}`,
- 'Use these ROOT values verbatim. `<id>` is the directory name shown after each entry; use it in the path even when it differs from the display name.',
+ 'Use these ROOT values verbatim. `<id>` is the internal read id shown after each entry; use it only inside read_file paths, even when it differs from the display name.',
+ 'These entries are skills, not tool names. To use one, read its SKILL.md by internal read id and follow the instructions; never call the display name or id as a tool.',
+ 'Never mention skill ids in plans, workflows, progress, or final replies. User-facing text must refer to skills by display name only.',
'',
];
for (const s of specs) {
@@ -98,9 +100,11 @@ async function renderSkillLines(
const description = pick(s, lang);
const desc = description ? ` — ${description}` : '';
// When name == id (custom skills authored locally), collapse the redundancy; when they
- // differ (marketplace installs), surface both so the model can pick by name and read by id.
- const head = s.name && s.name !== s.id ? `**${s.name}** (id: ${s.id})` : `**${s.id}**`;
- lines.push(`- ${head} (Source: ${source})${desc}`);
+ // differ (marketplace installs), keep the id explicitly internal so the model can read by
+ // path without being primed to repeat the id in user-facing prose.
+ const displayName = s.name || s.id;
+ const internal = displayName !== s.id ? `; internal read id: ${s.id}` : '';
+ lines.push(`- **${displayName}** (Source: ${source}${internal})${desc}`);
}
return lines.join('\n');
}
@@ -109,6 +113,113 @@ type CoreAgent = typeof import('#core-agent');
type SkillLoaderCtor = CoreAgent['SkillLoader'];
type SkillLoaderInstance = InstanceType<SkillLoaderCtor>;
type SkillSpec = ReturnType<SkillLoaderInstance['list']>[number];
+export interface SkillAllowlistRef {
+ id: string;
+ name?: string;
+ source?: string;
+}
+
+function _skillRefRank(s: SkillAllowlistRef): number {
+ if (!s.source) return 1;
+ return skillSourceLabel(s.source) === 'custom' ? 0 : 1;
+}
+
+export function resolveSkillAllowlistRefs(
+ specs: SkillAllowlistRef[],
+ refs: string[],
+): { ids: string[]; unknown: string[] } {
+ const byId = new Map<string, SkillAllowlistRef>();
+ const byName = new Map<string, SkillAllowlistRef[]>();
+ for (const s of specs) {
+ if (!s || !s.id) continue;
+ byId.set(s.id, s);
+ const name = typeof s.name === 'string' ? s.name : '';
+ if (name) {
+ const list = byName.get(name) || [];
+ list.push(s);
+ byName.set(name, list);
+ }
+ }
+ for (const list of byName.values()) {
+ list.sort((a, b) => {
+ const byRank = _skillRefRank(a) - _skillRefRank(b);
+ return byRank || a.id.localeCompare(b.id);
+ });
+ }
+
+ const ids: string[] = [];
+ const seen = new Set<string>();
+ const unknown: string[] = [];
+ for (const ref of refs) {
+ if (typeof ref !== 'string' || ref.length === 0) continue;
+ const resolved = byId.get(ref) || byName.get(ref)?.[0] || null;
+ if (!resolved) {
+ unknown.push(ref);
+ continue;
+ }
+ if (!seen.has(resolved.id)) {
+ seen.add(resolved.id);
+ ids.push(resolved.id);
+ }
+ }
+ return { ids, unknown };
+}
+
+function _buildDisplayNameByInternalId(specs: SkillAllowlistRef[]): Map<string, string> {
+ const out = new Map<string, string>();
+ for (const s of specs || []) {
+ const id = typeof s?.id === 'string' ? s.id.trim() : '';
+ const name = typeof s?.name === 'string' ? s.name.trim() : '';
+ if (!id || !name || id === name) continue;
+ out.set(id.toLowerCase(), name);
+ }
+ return out;
+}
+
+function _buildDisplayNameByRef(specs: SkillAllowlistRef[]): Map<string, string> {
+ const out = new Map<string, string>();
+ for (const s of specs || []) {
+ const id = typeof s?.id === 'string' ? s.id.trim() : '';
+ const name = typeof s?.name === 'string' ? s.name.trim() : '';
+ const display = name || id;
+ if (!display) continue;
+ if (id) out.set(id.toLowerCase(), display);
+ if (name) out.set(name.toLowerCase(), display);
+ }
+ return out;
+}
+
+export function replaceKnownSkillIdsForDisplay(text: string, specs: SkillAllowlistRef[]): string {
+ if (!text) return text;
+ const byId = _buildDisplayNameByInternalId(specs);
+ if (!byId.size) return text;
+ const ids = [...byId.keys()].sort((a, b) => b.length - a.length);
+ const alt = ids.map((id) => id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
+ const re = new RegExp(`(^|[^A-Za-z0-9_])(${alt})(?=$|[^A-Za-z0-9_])`, 'gi');
+ return String(text).replace(re, (_m, prefix: string, id: string) => {
+ return `${prefix}${byId.get(id.toLowerCase()) || id}`;
+ });
+}
+
+export function simplifyKnownSkillFollowPhrasesForDisplay(text: string, specs: SkillAllowlistRef[]): string {
+ if (!text) return text;
+ const byRef = _buildDisplayNameByRef(specs);
+ if (!byRef.size) return text;
+ const replaceRef = (full: string, ref: string) => {
+ const display = byRef.get(String(ref || '').trim().toLowerCase());
+ return display ? `\`${display}\` skill` : full;
+ };
+ let out = String(text).replace(/`skill:\s*follow\s+the\s+([A-Za-z0-9_.-]+)\s+skill`/gi, replaceRef);
+ out = out.replace(/skill:\s*follow\s+the\s+`?([A-Za-z0-9_.-]+)`?\s+skill/gi, replaceRef);
+ return out;
+}
+
+export function normalizeKnownSkillRefsForDisplay(text: string, specs: SkillAllowlistRef[]): string {
+ return simplifyKnownSkillFollowPhrasesForDisplay(
+ replaceKnownSkillIdsForDisplay(text, specs),
+ specs,
+ );
+}
// Skill loader is rebuilt on uid switch — `invalidateSkills()` clears it so
// the next `getLoader()` call re-reads the new user's custom skills dir.
@@ -133,8 +244,9 @@ export interface SystemPromptBlockOptions {
* array is passed, renders an empty block — used when an agent declares
* `skill_list: []` to opt out of all skills.
*
- * Unknown ids are silently dropped (skill may have been deleted since the
- * agent was configured); a warn-level log surfaces the mismatch.
+ * Unknown ids/names are silently dropped (skill may have been deleted
+ * since the agent was configured). Display-name matching preserves legacy
+ * agents authored before marketplace installs decoupled id from name.
*/
allowlist?: string[];
/**
@@ -145,6 +257,15 @@ export interface SystemPromptBlockOptions {
* in — this module stays free of `features/*` imports.
*/
disabledIds?: Iterable<string>;
+ /**
+ * Fires once per skill id rendered, with its source system (`A.custom`
+ * for `<uid>/cloud/skills/` or `A.platform` for the marketplace install
+ * dir). Caller (`runner.ts::buildRunner`) bridges this to ChatOptions
+ * so `features/group_chat/bus.ts` collects per turn for the
+ * `skill_advertised` signal. Pure callback — no FS, no IO, no awaits.
+ * See `docs/plans/expert-signals-skill-attribution.md` §4.1.
+ */
+ onSkillAdvertised?: (skill_id: string, system: 'A.custom' | 'A.platform') => void;
}
/**
@@ -170,13 +291,26 @@ export async function getSystemPromptBlock(opts: SystemPromptBlockOptions = {}):
const customRoot = path.resolve(userSkillsDir(getActiveUserId()));
const builtinRoot = path.resolve(userMarketplaceSkillsDir(getActiveUserId()));
- if (opts.allowlist === undefined) return renderSkillLines(filterDisabled(specs), customRoot, builtinRoot);
+ let rendered: typeof specs;
+ if (opts.allowlist === undefined) {
+ rendered = filterDisabled(specs);
+ } else {
+ const rawAllow = opts.allowlist.filter((id) => typeof id === 'string' && id.length > 0);
+ if (rawAllow.length === 0) return '';
+ const { ids } = resolveSkillAllowlistRefs(specs, rawAllow);
+ const allow = new Set(ids);
+ rendered = filterDisabled(specs.filter((s) => allow.has(s.id)));
+ }
- const rawAllow = opts.allowlist.filter((id) => typeof id === 'string' && id.length > 0);
- if (rawAllow.length === 0) return '';
+ if (opts.onSkillAdvertised && rendered.length) {
+ for (const s of rendered) {
+ try {
+ opts.onSkillAdvertised(s.id, skillSourceLabel(s.source) === 'custom' ? 'A.custom' : 'A.platform');
+ } catch { /* callback throws are non-fatal; signal emission is best-effort */ }
+ }
+ }
- const allow = new Set(rawAllow);
- return renderSkillLines(filterDisabled(specs.filter((s) => allow.has(s.id))), customRoot, builtinRoot);
+ return renderSkillLines(rendered, customRoot, builtinRoot);
}
/** Drop the internal mtime cache so the next `list()` rescans. */
diff --git a/src/main/paths.ts b/src/main/paths.ts
index 53387a0e..81c81795 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -263,6 +263,9 @@ export const userAuthProfilesFile = (uid: string) => path.join(userLocalConfigDi
export const userWebSearchCache = (uid: string) => path.join(userLocalConfigDir(uid), 'web-search-cache.json');
export const userReflectionStateFile = (uid: string) => path.join(userLocalConfigDir(uid), 'reflection-state.json');
export const userDevtoolsFile = (uid: string) => path.join(userLocalConfigDir(uid), 'devtools.json');
+// Machine-local defaults for external coding agents. Values are absolute
+// project directories, so they must not sync across devices.
+export const userAgentRuntimeConfigFile = (uid: string) => path.join(userLocalConfigDir(uid), 'agent-runtime.json');
// Local search index (derived data, self-healing via reconcile, never synced).
// Only the main conversation + knowledge base get a persistent inverted
@@ -374,7 +377,7 @@ export const localAgentRunDir = (uid: string, runId: string) =>
// CLI agent session bindings (features/local_agents/sessions.ts) —
// per-conversation map `{aid → {cli, sessionId}}` so the next dispatch
-// can `--resume` instead of re-replaying the whole visibility slice.
+// can `--resume` through the CLI's own conversation memory.
// Lives under `local/` (NOT cloud-synced) because the session id
// references claude's machine-local session files (`~/.claude/...`)
// which aren't valid on a different device.
@@ -388,6 +391,22 @@ export const localCliSessionsFile = (uid: string, cid: string) =>
// paths are machine-specific, so this is never synced.
export const userWorkspaceConfigFile = (uid: string) => path.join(userLocalRoot(uid), 'workspace.json');
+// ── Expert signals (machine-private, append-only) ───────────────────────
+// Per-day jsonl of T0/T1 user behavior signals emitted by bus.ts turn-end
+// hook + IPC handlers (retry/skip/form/silence). Local-only: signals are
+// extractor-version dependent and shouldn't cross devices; they're inputs
+// to reflection / patch suggester / critic (phase 1+). See plan
+// `docs/plans/expert-signals-phase-0.md`. Daily rotation keeps query
+// scoped to a date range; no archive sweep yet (50-200 KB/day × 365 ≈
+// 18-73 MB/year is acceptable for append-only jsonl).
+export const userSignalsDir = (uid: string) => path.join(userLocalRoot(uid), 'signals');
+/** Returns `<signalsDir>/<yyyy-mm-dd>.jsonl`. `date` defaults to today (local). */
+export const signalsDailyFile = (uid: string, date?: Date) => {
+ const d = date || new Date();
+ const ymd = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
+ return path.join(userSignalsDir(uid), `${ymd}.jsonl`);
+};
+
// ── Quality validator reports (machine-private) ──────────────────────────
// Per-spec ValidationReport produced by `src/main/quality/`. Local-only:
// validator version + ruleset are tied to the installed build, so a report
@@ -496,6 +515,7 @@ export function ensureUserLayout(uid: string): void {
userKbDir(uid),
userQualitySkillsDir(uid),
userQualityAgentsDir(uid),
+ userSignalsDir(uid),
];
for (const d of dirs) fs.mkdirSync(d, { recursive: true });
diff --git a/src/main/prompts/chat_agent_in_group.md b/src/main/prompts/chat_agent_in_group.md
index 42e8c3e7..b5eec0eb 100644
--- a/src/main/prompts/chat_agent_in_group.md
+++ b/src/main/prompts/chat_agent_in_group.md
@@ -111,7 +111,7 @@ The "Runtime injection" section at the end lists your `inputs_schema`. If it is
## Tools and resources
-**Tools** are auto-registered via the tool-use protocol — call them by name (`read_file` / `bash` / `kb_search` / `web_search` / `markdown_to_pdf`, etc.). **Skills** are listed in the system prompt's `## Available skills (skills)` section; locate the detailed usage based on `Source` (`cat` the corresponding `SKILL.md`) — don't try both roots.
+**Tools** are auto-registered via the tool-use protocol — call them by name (`read_file` / `bash` / `kb_search` / `web_search` / `markdown_to_pdf`, etc.). **Skills are not tools.** They are listed in the system prompt's `## Available skills (skills)` section; locate the detailed usage based on `Source` (`read_file` the corresponding `SKILL.md`) — don't try both roots. If your workflow says `skill:` or names something that appears only in Available skills, read and follow that skill; do NOT attempt a tool call with the skill's display name or id.
**Connectors**: when the system prompt has a `## Connectors` block, invoke listed services via `list_connector_tools({connector_id})` (to see an action's JSON schema) then `call_connector_tool({connector_id, tool_name, args})`. List before calling — don't guess. If the needed service isn't listed, tell the dispatcher; don't fake it with `web_search` / `bash`.
@@ -142,3 +142,5 @@ $inputs_schema
### Working directory
$working_dir
+
+$output_format_hint
diff --git a/src/main/prompts/chat_commander.md b/src/main/prompts/chat_commander.md
index 2f5dba6f..c7fe8ca8 100644
--- a/src/main/prompts/chat_commander.md
+++ b/src/main/prompts/chat_commander.md
@@ -40,7 +40,7 @@ You are NOT woken up in scenarios outside the table (e.g. agent X replies to the
## Decision tree: how to handle an inbound message
-**Rule 0 (highest priority) — explicit user pick**: if the user names a specific agent or skill ("use XX / @XX") in their text → for an agent, call `dispatch_to({ to: 'XX', message: '<the user's verbatim text>' })`; for a skill, `cat SKILL.md` + invoke as instructed.
+**Rule 0 (highest priority) — explicit user pick**: if the user names a specific agent, skill, or connector ("use XX / @XX") in their text → for an agent, call `dispatch_to({ to: 'XX', message: '<the user's verbatim text>' })`; for a skill, `cat SKILL.md` + invoke as instructed; for a connector, match it to the `## Connectors` block (prefer connector id, otherwise display name), call `list_connector_tools({connector_id})`, then call the relevant connector action with `call_connector_tool`.
**Rule 1 — classify the intent**:
- **Q&A** ("what is / why / how should I understand / what did I record before") → go to Rule 2.
@@ -228,6 +228,13 @@ Authoring rules live in two builtin skills — full container shape, field valid
Read the matching SKILL.md **before** emitting any `<agent>` / `<skill>` container — both files use whole-replacement semantics; guessing fields from training priors silently overwrites user content. The skills are listed in the "Available skills" block below as `agent-creator` / `skill-creator`; their `<ROOT>` is the builtin skills root.
+When you emit machine blocks for creation/editing, keep them raw and invisible-ready:
+
+- Emit `<agent>` / `<skill>` containers as top-level raw blocks, never inside Markdown fences, quotes, bullets, numbered lists, tables, or explanatory previews.
+- Do not duplicate any container body in visible prose. No `name:`, `description_zh`, `description_en`, YAML frontmatter, `<workflow>`, `<inputs>`, `<skills>`, `<<<skill-file>>>`, or similar config snippets outside the machine block.
+- Visible prose outside the container must be a short user-facing summary only. For bulk creation, one summary sentence is enough; the created cards carry the detailed objects.
+- After emitting the required containers, end the turn. Do not add a second "preview" section of the generated agent/skill definitions.
+
---
## Resources you can use
diff --git a/src/main/prompts/chat_shared_rules.md b/src/main/prompts/chat_shared_rules.md
index 04e9d2ca..d4d6baa5 100644
--- a/src/main/prompts/chat_shared_rules.md
+++ b/src/main/prompts/chat_shared_rules.md
@@ -17,9 +17,41 @@ To generate a PDF you **must** use `markdown_to_pdf` (pure markdown) or `html_to
**`$working_dir` is the write default, not a read boundary**: writes from `write_file` / `edit_file` / `markdown_to_pdf` / `html_to_pdf` / `generate_image` land under `$working_dir` by default with relative paths — including intermediate and final artifacts. When the user asks you to redo the same task, just **write the same filename again** (e.g. `requirements.md`); the system uniquifies only on real external conflicts, so you do **not** need to hand-version basenames (`requirements-v2.md` / `report-final.md`). Reading is unrestricted: `read_file` / `search_files` / `grep_files` / `bash` / `ls` reach anywhere in the workspace (including other conversations' artifacts) when the user gives a path or you locate one through search.
-**The chip row is the user-visible product surface — the reply text must align with it**: the five tools above produce **clickable chips that include the filename** (clicking opens the file's location in Finder / File Explorer); a chip is the user's only handle on a deliverable. So in your reply, mention chip-tracked filenames once each (no full absolute paths — `/Users/xxx/...` leaks the home dir and is visually noisy; the chip already gives "filename + click to open"). And **do not** enumerate scratch files written from inside `bash` (Python here-docs that `open(path,'w')`, shell redirection `>` / `tee`, `curl -o`, scripts run via `run-skill`) under headings like "已归档文件 / Generated files / Outputs / 产出文件" — they have no chip, the user is not expected to manage them, and listing them silently puzzles the reader. Summarise scratch as a count if useful ("scored 575 candidates → top 10"). If an intermediate genuinely needs to be a user-visible deliverable, write it via `write_file` so it gets a chip — don't dual-track via prose.
+**The chip row is the user-visible product surface — the reply text must align with it**: the five tools above produce **clickable chips that include the filename** (clicking opens the file's location in Finder / File Explorer); a chip is the user's only handle on a deliverable. So in your reply, mention chip-tracked filenames once each (no full home-directory absolute paths; they leak the user's local account name and are visually noisy; the chip already gives "filename + click to open"). And **do not** enumerate scratch files written from inside `bash` (Python here-docs that `open(path,'w')`, shell redirection `>` / `tee`, `curl -o`, scripts run via `run-skill`) under headings like "已归档文件 / Generated files / Outputs / 产出文件" — they have no chip, the user is not expected to manage them, and listing them silently puzzles the reader. Summarise scratch as a count if useful ("scored 575 candidates → top 10"). If an intermediate genuinely needs to be a user-visible deliverable, write it via `write_file` so it gets a chip — don't dual-track via prose.
**Showing images / video to the user** (so they appear inside the chat bubble): write a markdown link directly in the final text, `![alt](chat-media://local/<absolute path with the leading slash removed>)`; do **not** use any tool.
- Images: `.png/.jpg/.jpeg/.webp/.gif`; video: `.mp4/.webm/.mov/.m4v/.ogv`.
-- Path shape: Unix `/Users/...` → `Users/...`; Windows keep the drive letter `C:/Users/...`; encode spaces / non-ASCII with `%20`.
+- Path shape: POSIX absolute paths drop the leading slash; Windows paths keep the drive letter; encode spaces / non-ASCII with `%20`.
- `read_file` on an image is **for you to see** (multimodal input — the user does NOT see it); for the user to see it, you must reference it via markdown.
+
+## Output formats
+
+**Default = Markdown.** Narrative answers, lists, light tables, code fences — markdown covers most replies.
+
+**`:::dashboard`** — fenced JSON block for structured snapshots (KPI rows, alerts, timelines, multi-row data). Renders inline, no tool call:
+
+```
+:::dashboard
+{
+ "schema_version": 1,
+ "root": { "type": "Stack", "props": { "gap": "md" }, "children": [
+ { "type": "Grid", "props": { "columns": 3 }, "children": [
+ { "type": "Metric", "props": { "label": "Hosts", "value": "24", "delta": "+2", "tone": "positive" } },
+ { "type": "Metric", "props": { "label": "Unreachable", "value": "3", "tone": "negative" } },
+ { "type": "Metric", "props": { "label": "Avg RTT", "value": "42ms" } }
+ ] },
+ { "type": "Alert", "props": { "level": "warning", "title": "3 hosts unreachable", "body": "Check network ACL" } },
+ { "type": "Table", "props": {
+ "columns": [ { "key": "host", "label": "Host" }, { "key": "rtt", "label": "RTT", "numeric": true } ],
+ "rows": [ { "host": "10.0.0.1", "rtt": 12 }, { "host": "10.0.0.2", "rtt": 84 } ]
+ } }
+ ] }
+}
+:::
+```
+
+Component types: **layout** `Stack | Grid | Card | Separator`; **content** `Metric | Chart | Table | Alert | Timeline | Code | Markdown | Image`. Common props: `tone: positive|negative|neutral|warning`, `gap: sm|md|lg`, `columns: 1..4`, `level: info|success|warning|error`. Per-component content fields beyond the example above: `Markdown{text}`, `Code{code,lang?}`, `Timeline{items:[{time,label,body?}]}`, `Image{src,alt?,caption?}`, `Chart{kind,data}` (line/bar/area: `[{x,y}]`; pie: `[{label,value}]`). Unknown `type` and unknown field names render empty — stick to the names above. JSON must parse; on doubt prefer markdown over a broken block.
+
+**`create_artifact`** — multi-file web-app bundle rendered in a sandboxed iframe. Use only when behavior matters (forms / dynamic charts / interactive pages); for static layouts `:::dashboard` already covers, prefer that — it's lighter, iOS-renderable, and far cheaper in tokens.
+
+**Tool results are working data, not user prose.** Summarize and act on them; **do not** paste raw JSON / long logs / stack traces back into the reply. Quote at most a few salient lines when verbatim actually clarifies. Multi-row results → `:::dashboard`, not markdown tables hand-built from a JSON dump.
diff --git a/src/main/prompts/chat_skill_setup.md b/src/main/prompts/chat_skill_setup.md
index 62ce288b..3a3b04f5 100644
--- a/src/main/prompts/chat_skill_setup.md
+++ b/src/main/prompts/chat_skill_setup.md
@@ -1,7 +1,7 @@
## Core task
Help the user **design or refine a high-quality, self-contained skill** that an LLM can stably select and invoke in the right scenarios.
-The full authoring rules — `<<<skill-file>>>` block format, frontmatter 3-field rule, name charset, three-part description formula, SKILL.md body structure (When to use / How to call / Return / External deps / Limits / Examples), guide-type vs script-type decision, script invocation template, mutual independence rule, three creation modes (manual / install-from-URL / install-from-dir), and the user-perspective prose rules — live in the `skill-creator` builtin skill. **Read it first**:
+The full authoring rules — `<<<skill-file>>>` block format, frontmatter field rules, name charset, three-part description formula, SKILL.md body structure (When to use / How to call / Return / External deps / Limits / Examples), guide-type vs script-type decision, script invocation template, mutual independence rule, three creation modes (manual / install-from-URL / install-from-dir), and the user-perspective prose rules — live in the `skill-creator` builtin skill. **Read it first**:
```
read_file <ROOT>/skill-creator/SKILL.md
diff --git a/src/main/quality/rules/schema.ts b/src/main/quality/rules/schema.ts
index 9c21c956..62ecd689 100644
--- a/src/main/quality/rules/schema.ts
+++ b/src/main/quality/rules/schema.ts
@@ -23,6 +23,8 @@ const SKILL_NAME_RE = /^[A-Za-z][A-Za-z0-9_-]*(?: [A-Za-z0-9_-]+)*$/;
// around 800.
const MAX_DESC_LEN = 800;
+const CATEGORY_CODE_RE = /^[a-z][a-z0-9_-]{0,79}$/;
+
/**
* Validate SKILL.md frontmatter. Body content is scanned separately by
* red-flags + extractExecutableBlocks.
@@ -84,6 +86,25 @@ export function validateSkillFrontmatter(
}
}
+ const category = typeof frontmatter.category === 'string' ? frontmatter.category.trim() : '';
+ if (!category) {
+ out.push({
+ level: 'MEDIUM',
+ rule: 'frontmatter_category_missing',
+ field: 'frontmatter:category',
+ snippet: '',
+ suggested_fix: 'Add `category:` using the category codes defined in skill-creator; the writer can backfill the default when missing.',
+ });
+ } else if (!CATEGORY_CODE_RE.test(category)) {
+ out.push({
+ level: 'MEDIUM',
+ rule: 'frontmatter_category_invalid',
+ field: 'frontmatter:category',
+ snippet: category.slice(0, 80),
+ suggested_fix: 'Use a safe marketplace category code from skill-creator.',
+ });
+ }
+
return out;
}
@@ -124,12 +145,17 @@ export function validateAgentJsonShape(
const en = typeof agentJson.description_en === 'string' ? agentJson.description_en.trim() : '';
const legacy = typeof agentJson.description === 'string' ? agentJson.description.trim() : '';
if (!zh && !en && !legacy) {
+ // MEDIUM, not EXTREME: agents are commonly created as a stub
+ // (createCustomAgent with no body) and filled in via the inline
+ // edit chat afterwards. Blocking the create breaks that flow.
+ // The commander will simply not pick a description-less agent
+ // until the user fills it in — non-fatal.
out.push({
- level: 'EXTREME',
+ level: 'MEDIUM',
rule: 'agent_description_missing',
field: 'agent.json:description',
snippet: '',
- suggested_fix: 'Agent spec must include `description_zh` and `description_en` so the commander can dispatch correctly in either UI language.',
+ suggested_fix: 'Add `description_zh` and `description_en` so the commander can dispatch this agent in either UI language.',
});
} else {
for (const [field, value] of [
@@ -147,6 +173,25 @@ export function validateAgentJsonShape(
}
}
+ const category = typeof agentJson.category === 'string' ? agentJson.category.trim() : '';
+ if (!category) {
+ out.push({
+ level: 'MEDIUM',
+ rule: 'agent_category_missing',
+ field: 'agent.json:category',
+ snippet: '',
+ suggested_fix: 'Add `category` using the category codes defined in agent-creator; the writer can backfill the default when missing.',
+ });
+ } else if (!CATEGORY_CODE_RE.test(category)) {
+ out.push({
+ level: 'MEDIUM',
+ rule: 'agent_category_invalid',
+ field: 'agent.json:category',
+ snippet: category.slice(0, 80),
+ suggested_fix: 'Use a safe marketplace category code from agent-creator.',
+ });
+ }
+
return out;
}
diff --git a/src/main/util/image-transform.ts b/src/main/util/image-transform.ts
index 6189e9b2..bf4d27b1 100644
--- a/src/main/util/image-transform.ts
+++ b/src/main/util/image-transform.ts
@@ -1,9 +1,9 @@
/**
- * Image preprocessing for vision-model input. Resizes long edge, converts to
- * grayscale, re-encodes as JPEG. Significantly shrinks the byte payload while
- * preserving everything a vision model actually needs (text/shapes/layout).
+ * Shared image preprocessing utilities for main/.
*
- * Pure function, reusable anywhere in main/.
+ * Knowledge-base indexing uses the grayscale JPEG path because vision input
+ * only needs text/shapes/layout. User feedback keeps color and only compresses
+ * upload payloads when doing so is useful.
*/
export interface ImageTransformOpts {
@@ -22,6 +22,39 @@ export interface ImageTransformResult {
height: number;
}
+export interface FeedbackImageTransformOpts {
+ fileName?: string;
+ mimeType?: string;
+ maxBytes?: number;
+ maxDim?: number;
+ compressTriggerBytes?: number;
+}
+
+export type FeedbackImageMimeType = 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';
+
+export interface FeedbackImageTransformResult {
+ buf: Buffer;
+ mimeType: FeedbackImageMimeType;
+ fileName: string;
+ width?: number;
+ height?: number;
+ compressed: boolean;
+}
+
+const FEEDBACK_DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
+const FEEDBACK_DEFAULT_MAX_DIM = 1920;
+const FEEDBACK_DEFAULT_TRIGGER_BYTES = 1536 * 1024;
+const FEEDBACK_JPEG_CONFIGS = [
+ { maxDim: 1920, quality: 82 },
+ { maxDim: 1920, quality: 72 },
+ { maxDim: 1600, quality: 72 },
+ { maxDim: 1600, quality: 62 },
+ { maxDim: 1280, quality: 62 },
+ { maxDim: 1280, quality: 52 },
+ { maxDim: 1024, quality: 48 },
+ { maxDim: 800, quality: 42 },
+];
+
let _jimpPromise: Promise<any> | null = null;
function loadJimp(): Promise<any> {
if (!_jimpPromise) _jimpPromise = import('jimp' as any).then((m: any) => m.Jimp ?? m.default?.Jimp ?? m.default);
@@ -56,3 +89,144 @@ export async function toCompressedGrayJpeg(
height: img.bitmap.height,
};
}
+
+export async function prepareFeedbackUploadImage(
+ buf: Buffer,
+ opts: FeedbackImageTransformOpts = {},
+): Promise<FeedbackImageTransformResult> {
+ if (!buf || !(buf instanceof Buffer) || buf.length === 0) {
+ throw new Error('prepareFeedbackUploadImage: empty or invalid buffer');
+ }
+
+ const maxBytes = Math.max(1, opts.maxBytes ?? FEEDBACK_DEFAULT_MAX_BYTES);
+ const maxDim = Math.max(64, opts.maxDim ?? FEEDBACK_DEFAULT_MAX_DIM);
+ const compressTriggerBytes = Math.max(0, opts.compressTriggerBytes ?? FEEDBACK_DEFAULT_TRIGGER_BYTES);
+ const originalMime = feedbackImageMime(opts.mimeType, opts.fileName);
+ const originalName = normalizeFileName(opts.fileName || `image${extForMime(originalMime)}`);
+
+ if (originalMime === 'image/gif') {
+ if (buf.length > maxBytes) throw imageTooLargeError();
+ return {
+ buf,
+ mimeType: originalMime,
+ fileName: ensureFileExt(originalName, extForMime(originalMime)),
+ compressed: false,
+ };
+ }
+
+ const Jimp: any = await loadJimp();
+ let img: any;
+ try {
+ img = await Jimp.read(buf);
+ } catch {
+ if (buf.length <= maxBytes) {
+ return {
+ buf,
+ mimeType: originalMime,
+ fileName: ensureFileExt(originalName, extForMime(originalMime)),
+ compressed: false,
+ };
+ }
+ throw imageTooLargeError();
+ }
+
+ const originalWidth = img.bitmap.width;
+ const originalHeight = img.bitmap.height;
+ const shouldCompress = buf.length > compressTriggerBytes || Math.max(originalWidth, originalHeight) > maxDim;
+ if (!shouldCompress) {
+ if (buf.length > maxBytes) throw imageTooLargeError();
+ return {
+ buf,
+ mimeType: originalMime,
+ fileName: ensureFileExt(originalName, extForMime(originalMime)),
+ width: originalWidth,
+ height: originalHeight,
+ compressed: false,
+ };
+ }
+
+ let best: ImageTransformResult | null = null;
+ for (const cfg of FEEDBACK_JPEG_CONFIGS) {
+ const candidateMaxDim = Math.min(maxDim, cfg.maxDim);
+ const work = img.clone();
+ if (work.bitmap.width > candidateMaxDim || work.bitmap.height > candidateMaxDim) {
+ work.scaleToFit({ w: candidateMaxDim, h: candidateMaxDim });
+ }
+ const out: Buffer = await work.getBuffer('image/jpeg', { quality: cfg.quality });
+ const candidate: ImageTransformResult = {
+ buf: out,
+ mimeType: 'image/jpeg',
+ width: work.bitmap.width,
+ height: work.bitmap.height,
+ };
+ if (!best || candidate.buf.length < best.buf.length) best = candidate;
+ if (candidate.buf.length <= maxBytes && (buf.length > maxBytes || candidate.buf.length < buf.length)) {
+ return feedbackJpegResult(candidate, originalName);
+ }
+ }
+
+ if (buf.length <= maxBytes) {
+ return {
+ buf,
+ mimeType: originalMime,
+ fileName: ensureFileExt(originalName, extForMime(originalMime)),
+ width: originalWidth,
+ height: originalHeight,
+ compressed: false,
+ };
+ }
+ if (best && best.buf.length <= maxBytes) {
+ return feedbackJpegResult(best, originalName);
+ }
+ throw imageTooLargeError();
+}
+
+function feedbackJpegResult(result: ImageTransformResult, originalName: string): FeedbackImageTransformResult {
+ return {
+ ...result,
+ fileName: replaceFileExt(originalName, '.jpg'),
+ compressed: true,
+ };
+}
+
+function feedbackImageMime(mimeType?: string, fileName?: string): FeedbackImageMimeType {
+ const mt = String(mimeType || '').split(';')[0].trim().toLowerCase();
+ if (mt === 'image/jpg' || mt === 'image/jpeg') return 'image/jpeg';
+ if (mt === 'image/png') return 'image/png';
+ if (mt === 'image/gif') return 'image/gif';
+ if (mt === 'image/webp') return 'image/webp';
+
+ const name = String(fileName || '').toLowerCase();
+ if (name.endsWith('.png')) return 'image/png';
+ if (name.endsWith('.gif')) return 'image/gif';
+ if (name.endsWith('.webp')) return 'image/webp';
+ return 'image/jpeg';
+}
+
+function extForMime(mimeType: FeedbackImageMimeType): string {
+ if (mimeType === 'image/png') return '.png';
+ if (mimeType === 'image/gif') return '.gif';
+ if (mimeType === 'image/webp') return '.webp';
+ return '.jpg';
+}
+
+function normalizeFileName(fileName: string): string {
+ const clean = String(fileName || 'image').replace(/[\\/]/g, '_').trim();
+ return clean || 'image';
+}
+
+function replaceFileExt(fileName: string, ext: string): string {
+ const clean = normalizeFileName(fileName);
+ const base = clean.replace(/\.[^.]*$/, '') || 'image';
+ return `${base}${ext}`;
+}
+
+function ensureFileExt(fileName: string, ext: string): string {
+ return /\.[^.]+$/.test(fileName) ? fileName : `${fileName}${ext}`;
+}
+
+function imageTooLargeError(): Error & { code: string } {
+ const err = new Error('image too large') as Error & { code: string };
+ err.code = 'image_too_large';
+ return err;
+}
diff --git a/src/main/util/markdown-prose-code.ts b/src/main/util/markdown-prose-code.ts
index 15a85f5e..fc12b91a 100644
--- a/src/main/util/markdown-prose-code.ts
+++ b/src/main/util/markdown-prose-code.ts
@@ -1,19 +1,20 @@
// Backend port of the renderer's `_splitMarkdownProseCode` +
// `_findOuterTagRanges` (lives in `src/renderer/modules/strip-structural-blocks.js`).
-// Used to give the post-stream container extractors (`<skill>` here, and
-// long-term `<agent>` once that flow's WIP refactor settles) a prose/code
-// guard: an LLM mentioning `<skill>` inside a fenced ``` block or inline
-// backtick span (e.g., teaching the user the protocol) must NOT cause
-// the backend to falsely "extract" the example as a real container and
-// persist nonexistent files.
+// Used to give the post-stream container extractors (`<skill>` and `<agent>`)
+// a prose/code guard: an LLM mentioning a machine tag inside a non-XML
+// fenced block, inline backtick span, or inline quoted sentence (e.g.,
+// teaching the user the protocol) must NOT cause the backend to falsely
+// "extract" the example as a real container and persist nonexistent files.
+// Explicit ```xml fences remain structural output: the LLM sometimes wraps
+// real XML protocol blocks in Markdown, and those must still be parsed.
//
// Logic mirror is intentional — the renderer pins set A / set B fixtures
// directly in `test/renderer/strip-structural-blocks.test.ts`; the
// backend port is exercised indirectly through
-// `test/main/features/skills.test.ts` (B5/B6/B7 cover the prose/code
-// guard against `extractSkillContainers`). Both copies must stay in
-// sync; if you change one, change the other and extend BOTH fixture
-// sets.
+// `test/main/features/skills.test.ts` and `test/main/features/agents.test.ts`
+// (prose/code guards against `extractSkillContainers` /
+// `extractAgentFieldBlocks`). Both copies must stay in sync; if you change
+// one, change the other and extend BOTH fixture sets.
//
// Why duplicated rather than shared: renderer is vanilla JS without
// imports (PC/CLAUDE.md §8); main is TS with strict layering (§3, no
@@ -24,13 +25,16 @@
export interface ProseCodeSegment {
kind: 'prose' | 'code';
text: string;
+ xmlFence?: boolean;
}
/** Split a markdown buffer into alternating prose / code segments. "Code" =
* fenced ``` / ~~~ blocks (≤3-space indent, info-string allowed) plus
- * inline backtick spans; everything else is prose. Mid-stream unclosed
- * fences and unclosed inline backticks are treated as code through
- * end-of-buffer, matching the renderer's behavior. */
+ * inline backtick spans; everything else is prose. Fenced blocks with an
+ * `xml` info string carry `xmlFence: true` so downstream structural
+ * parsers can still process them. Mid-stream unclosed fences and unclosed
+ * inline backticks are treated as code through end-of-buffer, matching the
+ * renderer's behavior. */
export function splitMarkdownProseCode(text: string): ProseCodeSegment[] {
const segs: ProseCodeSegment[] = [];
if (!text) return segs;
@@ -53,6 +57,8 @@ export function splitMarkdownProseCode(text: string): ProseCodeSegment[] {
if (count >= 3) {
let k = j + count;
while (k < n && text[k] !== '\n') k++;
+ const info = text.slice(j + count, k).trim().toLowerCase();
+ const xmlFence = /^xml(?:\s|$)/.test(info);
let scan = k < n ? k + 1 : n;
let close = -1;
while (scan < n) {
@@ -74,7 +80,7 @@ export function splitMarkdownProseCode(text: string): ProseCodeSegment[] {
}
flushProse(i);
const endIdx = close >= 0 ? close : n;
- segs.push({ kind: 'code', text: text.slice(i, endIdx) });
+ segs.push({ kind: 'code', text: text.slice(i, endIdx), xmlFence });
proseStart = endIdx;
i = endIdx;
continue;
@@ -115,8 +121,50 @@ export function splitMarkdownProseCode(text: string): ProseCodeSegment[] {
return segs;
}
+function isInsideQuotedSpanOnLine(text: string, idx: number): boolean {
+ const lineStart = text.lastIndexOf('\n', Math.max(0, idx - 1)) + 1;
+ const nextNl = text.indexOf('\n', idx);
+ const lineEnd = nextNl < 0 ? text.length : nextNl;
+ const linePrefix = text.slice(lineStart, idx);
+ const closingAsciiDouble = text.indexOf('"', idx);
+ if (closingAsciiDouble >= 0 && closingAsciiDouble < lineEnd) {
+ let open = false;
+ for (let i = 0; i < linePrefix.length; i++) {
+ if (linePrefix[i] !== '"') continue;
+ if (i > 0 && linePrefix[i - 1] === '\\') continue;
+ open = !open;
+ }
+ if (open) return true;
+ }
+
+ const pairs: Array<[string, string]> = [['“', '”'], ['‘', '’'], ['「', '」'], ['『', '』'], ['《', '》']];
+ for (const [openQuote, closeQuote] of pairs) {
+ const lastOpen = text.lastIndexOf(openQuote, idx - 1);
+ if (lastOpen < lineStart) continue;
+ const lastClose = text.lastIndexOf(closeQuote, idx - 1);
+ const nextClose = text.indexOf(closeQuote, idx);
+ if (lastOpen > lastClose && nextClose >= 0 && nextClose < lineEnd) return true;
+ }
+ return false;
+}
+
+function isLineStartOpening(text: string, idx: number): boolean {
+ const lineStart = text.lastIndexOf('\n', Math.max(0, idx - 1)) + 1;
+ for (let i = lineStart; i < idx; i++) {
+ const ch = text[i];
+ if (ch === ' ' || ch === '\t' || ch === '"' || ch === '\'' || ch === '“' || ch === '‘' || ch === '「' || ch === '『' || ch === '《') continue;
+ return false;
+ }
+ return true;
+}
+
+function isInlineQuotedOpening(text: string, idx: number): boolean {
+ return isInsideQuotedSpanOnLine(text, idx) && !isLineStartOpening(text, idx);
+}
+
/** Find every `<TAG>...</TAG>` (or unclosed `<TAG>...EOF`) range whose
- * OPENING tag falls in an outer prose segment. The tagged container is
+ * OPENING tag falls in an outer prose segment or an explicit XML fence.
+ * The tagged container is
* treated as one atomic unit — once the opening tag is in prose, we walk
* to the matching `</TAG>` (or EOF) regardless of what's inside, so
* backticks / fences / quotes authored inside the body don't fragment
@@ -137,7 +185,7 @@ export function findOuterTagRanges(text: string, tagName: string): Array<[number
for (const seg of segs) {
const segStart = pos;
pos += seg.text.length;
- if (seg.kind !== 'prose') continue;
+ if (seg.kind !== 'prose' && !seg.xmlFence) continue;
let from = segStart;
while (from < pos) {
const last = ranges.length ? ranges[ranges.length - 1] : null;
@@ -153,6 +201,10 @@ export function findOuterTagRanges(text: string, tagName: string): Array<[number
from = openIdx + openLeader.length;
continue;
}
+ if (!seg.xmlFence && isInlineQuotedOpening(text, openIdx)) {
+ from = openIdx + openLeader.length;
+ continue;
+ }
const tagEnd = text.indexOf('>', openIdx + openLeader.length);
if (tagEnd < 0) {
ranges.push([openIdx, text.length]);
diff --git a/src/main/util/migrate-kb-to-local.ts b/src/main/util/migrate-kb-to-local.ts
index 198dbba4..b0d31dbb 100644
--- a/src/main/util/migrate-kb-to-local.ts
+++ b/src/main/util/migrate-kb-to-local.ts
@@ -10,10 +10,14 @@
* - New path already exists, old path doesn't: nothing to do (post-migration
* baseline). Stamp and return.
* - New path exists AND old path exists: keep new, rename old to
- * `.kb.legacy-<ts>` so we never delete user data automatically. Log warn
- * so support can investigate. Stamp.
+ * `<uid>/local/contexts/.kb.legacy-<ts>` so we never delete user data
+ * automatically and never leave derived KB data in the cloud sync tree.
+ * Log warn so support can investigate. Stamp.
* - Old path is a file (not a directory): leave it alone (corrupt FS state),
* stamp anyway since the schema says it should be a directory.
+ * - Older builds may already have created
+ * `<uid>/cloud/contexts/.kb.legacy-*`; a second one-shot moves those
+ * backup dirs to `<uid>/local/contexts/`.
*/
import * as fs from 'node:fs';
@@ -29,35 +33,39 @@ import { createLogger } from '../logger';
const log = createLogger('migrate');
const MIGRATION_TAG = 'kb-to-local-contexts-v1';
+const LEGACY_BACKUP_TAG = 'kb-legacy-backups-to-local-v1';
function migrationsFile(uid: string): string {
// userLocalConfigDir = <uid>/local/config; up one to <uid>/local/
return path.join(path.dirname(userLocalConfigDir(uid)), '.migrations');
}
-function alreadyApplied(uid: string): boolean {
+function alreadyApplied(uid: string, tag = MIGRATION_TAG): boolean {
const f = migrationsFile(uid);
if (!fs.existsSync(f)) return false;
try {
const content = fs.readFileSync(f, 'utf8');
- return content.split('\n').some((line) => line.trim() === MIGRATION_TAG);
+ return content.split('\n').some((line) => line.trim() === tag);
} catch {
return false;
}
}
-function stamp(uid: string): void {
+function stamp(uid: string, tag = MIGRATION_TAG): void {
const f = migrationsFile(uid);
try {
fs.mkdirSync(path.dirname(f), { recursive: true });
- fs.appendFileSync(f, `${MIGRATION_TAG}\n`);
+ fs.appendFileSync(f, `${tag}\n`);
} catch (err) {
log.warn(`stamp failed uid=${uid}: ${(err as Error).message}`);
}
}
export function migrateKbToLocalContexts(uid: string): void {
- if (alreadyApplied(uid)) return;
+ if (alreadyApplied(uid)) {
+ migrateLegacyKbBackupsToLocal(uid);
+ return;
+ }
const legacyKb = path.join(userContextsDir(uid), '.kb'); // <uid>/cloud/contexts/.kb
const newKb = userKbDir(uid); // <uid>/local/contexts/.kb
@@ -67,6 +75,7 @@ export function migrateKbToLocalContexts(uid: string): void {
if (!legacyExists) {
stamp(uid);
+ migrateLegacyKbBackupsToLocal(uid);
return;
}
@@ -76,6 +85,7 @@ export function migrateKbToLocalContexts(uid: string): void {
if (!legacyIsDir) {
log.warn(`kb migration: legacy .kb at ${legacyKb} is not a directory; leaving alone`);
stamp(uid);
+ migrateLegacyKbBackupsToLocal(uid);
return;
}
@@ -84,17 +94,18 @@ export function migrateKbToLocalContexts(uid: string): void {
if (newExists) {
const ts = new Date().toISOString().replace(/[:.]/g, '-');
- const sidelined = `${legacyKb}.legacy-${ts}`;
+ const sidelined = uniquePath(path.join(userLocalContextsDir(uid), `.kb.legacy-${ts}`));
log.warn(
`kb migration: both ${legacyKb} and ${newKb} exist; keeping ${newKb}, ` +
`renaming legacy → ${sidelined}`,
);
try {
- fs.renameSync(legacyKb, sidelined);
+ movePathSync(legacyKb, sidelined);
} catch (err) {
log.warn(`kb migration: rename-to-sidelined failed: ${(err as Error).message}`);
}
stamp(uid);
+ migrateLegacyKbBackupsToLocal(uid);
return;
}
@@ -120,6 +131,35 @@ export function migrateKbToLocalContexts(uid: string): void {
}
}
stamp(uid);
+ migrateLegacyKbBackupsToLocal(uid);
+}
+
+function migrateLegacyKbBackupsToLocal(uid: string): void {
+ if (alreadyApplied(uid, LEGACY_BACKUP_TAG)) return;
+
+ const cloudContexts = userContextsDir(uid);
+ const localContexts = userLocalContextsDir(uid);
+ let ok = true;
+ let names: string[] = [];
+ try {
+ names = fs.readdirSync(cloudContexts).filter((name) => name.startsWith('.kb.legacy-'));
+ } catch {
+ stamp(uid, LEGACY_BACKUP_TAG);
+ return;
+ }
+
+ for (const name of names) {
+ const src = path.join(cloudContexts, name);
+ const dst = uniquePath(path.join(localContexts, name));
+ try {
+ movePathSync(src, dst);
+ log.info(`kb migration: moved legacy backup ${src} → ${dst}`);
+ } catch (err) {
+ ok = false;
+ log.warn(`kb migration: move legacy backup failed: ${(err as Error).message}`);
+ }
+ }
+ if (ok) stamp(uid, LEGACY_BACKUP_TAG);
}
function copyDirSync(src: string, dst: string): void {
@@ -132,6 +172,36 @@ function copyDirSync(src: string, dst: string): void {
}
}
+function copyPathSync(src: string, dst: string): void {
+ const st = fs.statSync(src);
+ if (st.isDirectory()) {
+ copyDirSync(src, dst);
+ } else if (st.isFile()) {
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
+ fs.copyFileSync(src, dst);
+ }
+}
+
+function movePathSync(src: string, dst: string): void {
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
+ try {
+ fs.renameSync(src, dst);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'EXDEV') throw err;
+ copyPathSync(src, dst);
+ rmRfSync(src);
+ }
+}
+
+function uniquePath(base: string): string {
+ if (!fs.existsSync(base)) return base;
+ for (let i = 1; i < 1000; i += 1) {
+ const candidate = `${base}-${i}`;
+ if (!fs.existsSync(candidate)) return candidate;
+ }
+ return `${base}-${Date.now()}`;
+}
+
function rmRfSync(p: string): void {
try { fs.rmSync(p, { recursive: true, force: true }); } catch { /* ignore */ }
}
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 435ccf47..56708b15 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -77,14 +77,14 @@
<div class="chat-input-overlay">
<div class="chat-attachments" id="new-chat-attachments" style="display:none"></div>
</div>
- <textarea id="new-chat-input" data-i18n-placeholder="new_chat.input_placeholder" placeholder="Type a message..." rows="2"></textarea>
+ <textarea id="new-chat-input" data-i18n-placeholder="new_chat.input_placeholder" placeholder="Type a message. Use @ to call agents, skills, connectors." rows="2"></textarea>
<div class="chat-bottom-bar">
<button type="button" class="chat-attach-btn" id="new-chat-attach-btn" data-i18n-title="new_chat.attach_title" title="Upload attachment (text / PDF / Word / image / video)">+</button>
<!-- Voice-to-text mic button (stripped in OrkasOpen — see OpenSource/SyncCode/strip-rules.json). -->
<button type="button" class="chat-attach-btn chat-mic-btn" id="new-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="new-chat-recipient-chip" data-i18n-title="chat.recipient_picker_title" title="Switch recipient (commander / agent)">
+ <button type="button" class="chat-recipient-chip" id="new-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="new-chat-recipient-name" data-i18n="chat.recipient_commander">Commander</span>
</button>
@@ -167,14 +167,14 @@
<div class="chat-attachments" id="chat-attachments" style="display:none"></div>
</div>
<div class="chat-quote-preview" id="chat-quote-preview" style="display:none"></div>
- <textarea id="chat-input" data-i18n-placeholder="chat.input_placeholder" placeholder="Continue the conversation..." rows="2"></textarea>
+ <textarea id="chat-input" data-i18n-placeholder="chat.input_placeholder" placeholder="Continue the conversation. Use @ to call agents, skills, connectors." rows="2"></textarea>
<div class="chat-bottom-bar">
<button type="button" class="chat-attach-btn" id="chat-attach-btn" data-i18n-title="chat.attach_title" title="Upload attachment (text / PDF / Word / image / video)">+</button>
<!-- Voice-to-text mic button (stripped in OrkasOpen — see OpenSource/SyncCode/strip-rules.json). -->
<button type="button" class="chat-attach-btn chat-mic-btn" id="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="chat-recipient-chip" data-i18n-title="chat.recipient_picker_title" title="Switch recipient (commander / agent)">
+ <button type="button" class="chat-recipient-chip" id="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="chat-recipient-name" data-i18n="chat.recipient_commander">Commander</span>
</button>
@@ -206,6 +206,22 @@
</div>
<div class="conversation-info-body" id="conversation-info-body"></div>
</aside>
+ <!-- Markdown viewer / editor drawer. Hosts the shared mountMdViewEdit
+ component (modules/md-view-edit.js) for either an assistant-
+ generated .md file (workspace source) or a free-form scratch
+ edit triggered from a chat-selection context menu (ephemeral
+ source). Slides in from the right just like conversation-info,
+ but is its own single-purpose surface. -->
+ <aside class="chat-md-drawer-panel" id="chat-md-drawer-panel" hidden>
+ <div class="chat-md-drawer-header">
+ <div class="chat-md-drawer-title" id="chat-md-drawer-title"></div>
+ <div class="chat-md-drawer-actions detail-actions" id="chat-md-drawer-actions"></div>
+ <button type="button" class="chat-md-drawer-close" id="chat-md-drawer-close"
+ data-i18n-title="common.close" data-i18n-aria-label="common.close"
+ title="Close" aria-label="Close">×</button>
+ </div>
+ <div class="chat-md-drawer-body markdown-body" id="chat-md-drawer-body"></div>
+ </aside>
</div>
</section>
@@ -357,6 +373,10 @@
<div class="agents-detail-label" data-i18n="agents.label_runtime">External agent</div>
<div class="agents-detail-runtime" id="agents-detail-runtime"></div>
</div>
+ <div class="agents-detail-section" id="agents-detail-project-dir-section" style="display:none">
+ <div class="agents-detail-label" data-i18n="agents.label_project_dir">Project directory</div>
+ <div class="agents-detail-project-dir" id="agents-detail-project-dir"></div>
+ </div>
<div class="agents-detail-section">
<div class="agents-detail-label" data-i18n="agents.label_desc">Summary</div>
<div class="agents-detail-desc" id="agents-detail-desc" contenteditable="false"></div>
@@ -365,6 +385,11 @@
<div class="agents-detail-label" data-i18n="agents.label_workflow">Workflow</div>
<div class="agents-detail-workflow markdown-body" id="agents-detail-workflow" contenteditable="false"></div>
</div>
+ <div class="agents-detail-section" id="agents-detail-output-format-section">
+ <div class="agents-detail-label" data-i18n="agents.label_output_format">Output format</div>
+ <div class="agents-detail-output-format" id="agents-detail-output-format"></div>
+ <div class="form-hint muted" data-i18n="agents.output_format_hint">Hint to the agent on how to render replies. Auto = let the model pick per output.</div>
+ </div>
</div>
</div>
</div>
@@ -540,8 +565,10 @@
<section class="panel" id="panel-settings">
<div class="settings-container">
<div class="settings-header">
- <h2 data-i18n="settings.title">Settings</h2>
- <div class="settings-version" id="settings-version"></div>
+ <div class="settings-heading">
+ <h2 data-i18n="settings.title">Settings</h2>
+ <div class="settings-version" id="settings-version"></div>
+ </div>
</div>
<!-- 4-tab restructure (batch 6 + 4 decision; see PC/docs/plans/multi-device-sync.md §4.9).
@@ -872,8 +899,8 @@
<input type="text" id="agent-name-input" data-i18n-placeholder="agent_modal.name_placeholder" placeholder="e.g. Code Review Assistant" />
</div>
<div class="form-row">
- <label data-i18n="agent_modal.category">Category</label>
- <div class="ai-select" id="agent-category-select"></div>
+ <label><span data-i18n="agents.label_output_format">Output format</span> <span class="form-hint" data-i18n="agents.output_format_hint">Tells the agent how to render replies.</span></label>
+ <div class="ai-select" id="agent-output-format-select"></div>
</div>
<div class="form-row">
<label><span data-i18n="agent_modal.desc">Summary</span> <span class="form-hint" data-i18n="agent_modal.desc_hint">One line on what it does — the AI will generate a workflow from this</span></label>
@@ -883,8 +910,8 @@
<!-- External panel: bind a local CLI as the runtime. CLI selector
appears first; name + description are pre-filled from the chosen
- CLI's defaults but stay editable. claude / codex additionally
- expose a project-directory input. -->
+ CLI's defaults but stay editable. claude / codex get a
+ project-directory setting on the detail page after creation. -->
<div class="skill-modal-panel" data-agent-panel="external">
<div class="form-row">
<label data-i18n="agent_modal.ext_cli_label">Agent</label>
@@ -894,10 +921,6 @@
<label data-i18n="agent_modal.ext_name">Name</label>
<input type="text" id="agent-ext-name-input" data-i18n-placeholder="agent_modal.ext_name_placeholder" placeholder="e.g. Claude Code" />
</div>
- <div class="form-row">
- <label data-i18n="agent_modal.category">Category</label>
- <div class="ai-select" id="agent-ext-category-select"></div>
- </div>
<div class="form-row">
<label data-i18n="agent_modal.ext_desc">Summary</label>
<textarea id="agent-ext-desc-input" rows="4" data-i18n-placeholder="agent_modal.ext_desc_placeholder" placeholder="(auto-filled when a CLI is picked; can be overridden)"></textarea>
@@ -931,10 +954,6 @@
<label><span data-i18n="skill_modal.name">Name (English)</span><span class="form-hint" data-i18n="skill_modal.name_hint">Starts with a letter; digits, -, _, and one space allowed</span></label>
<input type="text" id="skill-name" data-i18n-placeholder="skill_modal.name_placeholder" placeholder="e.g. web-summary" />
</div>
- <div class="form-row">
- <label data-i18n="skill_modal.category">Category</label>
- <div class="ai-select" id="skill-category-select"></div>
- </div>
<div class="form-row">
<label data-i18n="skill_modal.description">Summary</label>
<textarea id="skill-description" rows="4" data-i18n-placeholder="skill_modal.desc_placeholder" placeholder="One line on what this skill does and when to use it..."></textarea>
@@ -969,8 +988,13 @@
</div>
</div>
- <!-- Agent picker popup (new-chat only) -->
+ <!-- Agent / skill / connector picker popup -->
<div class="skill-picker" id="agent-picker" style="display:none">
+ <div class="skill-picker-tabs" role="tablist" aria-label="Picker type">
+ <button type="button" class="skill-picker-tab active" data-agent-picker-tab="agents" data-i18n="agent_picker.tab_agents">Agents</button>
+ <button type="button" class="skill-picker-tab" data-agent-picker-tab="skills" data-i18n="agent_picker.tab_skills">Skills</button>
+ <button type="button" class="skill-picker-tab" data-agent-picker-tab="connectors" data-i18n="agent_picker.tab_connectors">Connectors</button>
+ </div>
<div class="skill-picker-header">
<input type="text" id="agent-picker-search" data-i18n-placeholder="agent_picker.search_placeholder" placeholder="Search agents..." autocomplete="off" />
</div>
@@ -1106,6 +1130,9 @@
<script src="./modules/chat-lightbox.js"></script>
<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/context-menu.js"></script>
+ <script src="./modules/chat-md-drawer.js"></script>
<script src="./modules/strip-structural-blocks.js"></script>
<script src="./modules/projects.js"></script>
<script src="./modules/project-detail.js"></script>
@@ -1169,6 +1196,7 @@
</script>
<script src="./vendor/mathjax/tex-chtml.js" defer></script>
<script src="./modules/math.js"></script>
+ <script src="./modules/feedback.js"></script>
<script src="./modules/settings.js"></script>
<script src="./modules/sync_settings.js"></script>
<script src="./modules/sync_refresh.js"></script>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index 965d8789..c8af29a2 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -86,9 +86,19 @@
"connectors.status.error": "Error",
"connectors.errors.connect_failed": "Authorization failed",
"connectors.errors.remove_failed": "Uninstall failed",
+ "connectors.use_label": "Connector: {connector}",
+ "connectors.use_prefix": "Use {connector} connector: {content}",
+ "connectors.no_match": "No matching connectors",
+ "connectors.no_connected": "No connected connectors",
+ "connectors.account_label": "Account: {account}",
"common.save": "Save",
"common.more": "More",
"common.loading": "Loading…",
+ "agents.label_output_format": "Output format",
+ "agents.output_format_hint": "Hint to the agent on how to render replies. New agents default to Markdown only — opt up when Dashboard / Artifact is actually useful.",
+ "agents.output_format_markdown_only": "Markdown only",
+ "agents.output_format_dashboard": "Dashboard (no artifact)",
+ "agents.output_format_artifact": "Artifact (Dashboard + HTML)",
"sidebar.conversations": "Chats",
"sidebar.conv_empty": "No conversations yet",
"sidebar.projects": "Projects",
@@ -99,17 +109,17 @@
"sidebar.settings_title": "Settings",
"new_chat.title": "Command agents to get things done",
"new_chat.subtitle": "Type your question or task",
- "new_chat.input_placeholder": "Type a message...",
+ "new_chat.input_placeholder": "Type a message. Use @ to call agents, skills, connectors.",
"new_chat.attach_title": "Upload attachment (text / PDF / Word / image / video)",
"new_chat.send_title": "Send",
"chat.empty": "No messages yet...",
"chat.queue_label": "Queued",
"chat.queue_hint": "Drag to reorder · Edit · Delete",
- "chat.input_placeholder": "Continue the conversation...",
+ "chat.input_placeholder": "Continue the conversation. Use @ to call agents, skills, connectors.",
"chat.recipient_label": "To: ",
"chat.recipient_commander": "Commander",
"chat.recipient_commander_hint": "Default recipient, no @ needed",
- "chat.recipient_picker_title": "Switch recipient (commander / agent)",
+ "chat.recipient_picker_title": "Choose agent, skill, or connector",
"chat.project_label": "Project: ",
"chat.project_none": "None",
"chat.project_picker_title": "Pick project",
@@ -160,6 +170,12 @@
"chat.preview_unsupported_reveal": "Open Folder",
"chat.preview_cancel": "Close",
"chat.process_info": "Process info",
+ "chat.menu.copy": "Copy",
+ "chat.menu.scratch_edit": "Scratch edit",
+ "chat.md_drawer.scratch_title": "Scratch edit",
+ "chat.md_drawer.close_confirm": "Discard unsaved changes?",
+ "chat.md_drawer.copy_draft": "Copy",
+ "chat.md_drawer.send_to_chat": "Send to chat input",
"conversation_info.toggle_title": "Conversation info",
"conversation_info.title": "Conversation info",
"conversation_info.tab_tasks": "Tasks",
@@ -315,12 +331,15 @@
"skills.clear_chat": "Clear",
"skills.clear_chat_title": "Clear the edit chat for this skill",
"skills.chat_input_placeholder": "Describe what to change...",
+ "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.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",
+ "skills.no_project_skills": "This project has no bound skills.",
"skills.loading": "Loading...",
"skills.load_failed": "Load failed",
"skills.saving": "Saving…",
@@ -355,6 +374,7 @@
"agents.custom_group": "Custom",
"agents.builtin_group": "Platform",
"agents.back": "Back to agents",
+ "agents.update_failed": "Update failed",
"agents.use": "Use",
"agents.use_tooltip": "Use this agent",
"agents.more_actions": "More actions",
@@ -362,6 +382,7 @@
"agents.delete": "Uninstall",
"agents.label_desc": "Summary",
"agents.label_runtime": "External agent",
+ "agents.label_project_dir": "Project directory",
"agents.label_workflow": "Workflow",
"agents.clear_chat": "Clear",
"agents.clear_chat_title": "Clear the edit chat for this agent",
@@ -850,6 +871,12 @@
"agent.external_badge.opencode": "External · OpenCode",
"agent.external_badge.hermes": "External · Hermes",
"agent.cli_missing": "External agent not installed",
+ "agents.project_dir_workspace": "Workspace",
+ "agents.project_dir_custom": "Custom",
+ "agents.project_dir_missing": "Missing",
+ "agents.project_dir_use_workspace": "Use workspace",
+ "agents.project_dir_save_failed": "Failed to save project directory",
+ "agents.project_dir_load_failed": "Failed to load project directory",
"input.dir.none": "(not set)",
"input.dir.pick": "Pick directory…",
"input.dir.change": "Change…",
@@ -875,7 +902,12 @@
"skill_modal.dir_none": "(not picked)",
"skill_modal.err_url_invalid": "URL must start with http(s)://",
"skill_modal.err_dir_missing": "Pick a source folder first",
+ "agent_picker.tab_agents": "Agents",
+ "agent_picker.tab_skills": "Skills",
+ "agent_picker.tab_connectors": "Connectors",
"agent_picker.search_placeholder": "Search agents...",
+ "agent_picker.search_skills_placeholder": "Search skills...",
+ "agent_picker.search_connectors_placeholder": "Search connectors...",
"add_account.title": "Add account",
"oauth_flow.title": "OAuth sign-in",
"oauth_flow.preparing": "Preparing authorization…",
diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.json
index ad0c2c85..6c07024e 100644
--- a/src/renderer/locales/ja.json
+++ b/src/renderer/locales/ja.json
@@ -86,6 +86,11 @@
"connectors.status.error": "エラー",
"connectors.errors.connect_failed": "認証に失敗しました",
"connectors.errors.remove_failed": "アンインストールに失敗しました",
+ "connectors.use_label": "コネクター: {connector}",
+ "connectors.use_prefix": "{connector} コネクターを使用: {content}",
+ "connectors.no_match": "一致するコネクターはありません",
+ "connectors.no_connected": "接続済みコネクターはありません",
+ "connectors.account_label": "アカウント: {account}",
"common.save": "保存",
"common.more": "その他",
"common.loading": "読み込み中…",
@@ -101,17 +106,17 @@
"sidebar.devtools_title": "開発モードでのみ表示",
"new_chat.title": "エージェントに指示して作業を進める",
"new_chat.subtitle": "質問やタスクを入力",
- "new_chat.input_placeholder": "メッセージを入力...",
+ "new_chat.input_placeholder": "メッセージを入力。@ でエージェント、スキル、コネクターを呼び出せます。",
"new_chat.attach_title": "添付ファイルをアップロード(テキスト / PDF / Word / 画像 / 動画)",
"new_chat.send_title": "送信",
"chat.empty": "メッセージはまだありません...",
"chat.queue_label": "キュー",
"chat.queue_hint": "ドラッグで並べ替え・編集・削除",
- "chat.input_placeholder": "会話を続ける...",
+ "chat.input_placeholder": "会話を続ける。@ でエージェント、スキル、コネクターを呼び出せます。",
"chat.recipient_label": "宛先: ",
"chat.recipient_commander": "コマンダー",
"chat.recipient_commander_hint": "デフォルトの宛先です。@ は不要です",
- "chat.recipient_picker_title": "宛先を切り替え(コマンダー / エージェント)",
+ "chat.recipient_picker_title": "エージェント、スキル、コネクターを選択",
"chat.project_label": "プロジェクト: ",
"chat.project_none": "なし",
"chat.project_picker_title": "プロジェクトを選択",
@@ -162,6 +167,12 @@
"chat.preview_unsupported_reveal": "フォルダを開く",
"chat.preview_cancel": "閉じる",
"chat.process_info": "プロセス情報",
+ "chat.menu.copy": "コピー",
+ "chat.menu.scratch_edit": "一時編集",
+ "chat.md_drawer.scratch_title": "一時編集",
+ "chat.md_drawer.close_confirm": "未保存の変更を破棄しますか?",
+ "chat.md_drawer.copy_draft": "コピー",
+ "chat.md_drawer.send_to_chat": "チャット入力に送る",
"conversation_info.toggle_title": "会話情報",
"conversation_info.title": "会話情報",
"conversation_info.tab_tasks": "タスク",
@@ -317,12 +328,15 @@
"skills.clear_chat": "クリア",
"skills.clear_chat_title": "このスキルの編集チャットをクリア",
"skills.chat_input_placeholder": "変更内容を説明...",
+ "skills.use_label": "スキル: {skill}",
"skills.use_prefix": "{skill} スキルを使用: {content}",
"skills.rename_title": "クリックして名前を変更",
"skills.source_custom": "カスタム",
"skills.source_builtin": "組み込み",
"skills.name_invalid": "名前は英字で始めてください。使用可能: 英数字、アンダースコア、ハイフン、単一の内部スペース",
"skills.desc_unset": "(説明なし)",
+ "skills.no_match": "一致するスキルはありません",
+ "skills.no_project_skills": "このプロジェクトにはスキルが関連付けられていません。",
"skills.loading": "読み込み中...",
"skills.load_failed": "読み込みに失敗しました",
"skills.saving": "保存中…",
@@ -355,6 +369,7 @@
"agents.custom_group": "カスタム",
"agents.builtin_group": "プラットフォーム",
"agents.back": "エージェントに戻る",
+ "agents.update_failed": "更新に失敗しました",
"agents.use": "使用",
"agents.use_tooltip": "このエージェントを使用",
"agents.more_actions": "その他の操作",
@@ -362,6 +377,12 @@
"agents.delete": "アンインストール",
"agents.label_desc": "概要",
"agents.label_runtime": "外部エージェント",
+ "agents.label_project_dir": "プロジェクトディレクトリ",
+ "agents.label_output_format": "出力形式",
+ "agents.output_format_hint": "エージェントに返信の表示形式を伝えます。新規エージェントは Markdown のみが既定です。Dashboard / Artifact が有用な場合だけ有効にしてください。",
+ "agents.output_format_markdown_only": "Markdown のみ",
+ "agents.output_format_dashboard": "Dashboard(Artifact なし)",
+ "agents.output_format_artifact": "Artifact(Dashboard + HTML)",
"agents.label_workflow": "ワークフロー",
"agents.clear_chat": "クリア",
"agents.clear_chat_title": "このエージェントの編集チャットをクリア",
@@ -844,6 +865,12 @@
"agent.external_badge.opencode": "外部 · OpenCode",
"agent.external_badge.hermes": "外部 · Hermes",
"agent.cli_missing": "外部エージェントがインストールされていません",
+ "agents.project_dir_workspace": "ワークスペース",
+ "agents.project_dir_custom": "カスタム",
+ "agents.project_dir_missing": "見つかりません",
+ "agents.project_dir_use_workspace": "ワークスペースを使用",
+ "agents.project_dir_save_failed": "プロジェクトディレクトリの保存に失敗しました",
+ "agents.project_dir_load_failed": "プロジェクトディレクトリの読み込みに失敗しました",
"input.dir.none": "(未設定)",
"input.dir.pick": "ディレクトリを選択…",
"input.dir.change": "変更…",
@@ -869,7 +896,12 @@
"skill_modal.dir_none": "(未選択)",
"skill_modal.err_url_invalid": "URL は http(s):// で始まる必要があります",
"skill_modal.err_dir_missing": "先にソースフォルダを選択してください",
+ "agent_picker.tab_agents": "エージェント",
+ "agent_picker.tab_skills": "スキル",
+ "agent_picker.tab_connectors": "コネクター",
"agent_picker.search_placeholder": "エージェントを検索...",
+ "agent_picker.search_skills_placeholder": "スキルを検索...",
+ "agent_picker.search_connectors_placeholder": "コネクターを検索...",
"add_account.title": "アカウントを追加",
"oauth_flow.title": "OAuth サインイン",
"oauth_flow.preparing": "認証を準備中…",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index 60e9c553..e02c1f4b 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -86,9 +86,19 @@
"connectors.status.error": "异常",
"connectors.errors.connect_failed": "授权失败",
"connectors.errors.remove_failed": "卸载失败",
+ "connectors.use_label": "连接器:{connector}",
+ "connectors.use_prefix": "使用 {connector} 连接器:{content}",
+ "connectors.no_match": "无匹配连接器",
+ "connectors.no_connected": "暂无已连接的连接器",
+ "connectors.account_label": "账号:{account}",
"common.save": "保存",
"common.more": "更多",
"common.loading": "加载中…",
+ "agents.label_output_format": "输出排版",
+ "agents.output_format_hint": "提示 agent 如何呈现回复。新建默认仅 Markdown,按需放开 Dashboard / Artifact。",
+ "agents.output_format_markdown_only": "仅 Markdown",
+ "agents.output_format_dashboard": "Dashboard(不含 Artifact)",
+ "agents.output_format_artifact": "Artifact(含 Dashboard + HTML)",
"sidebar.conversations": "对话",
"sidebar.conv_empty": "暂无对话",
"sidebar.projects": "项目",
@@ -99,17 +109,17 @@
"sidebar.settings_title": "设置",
"new_chat.title": "指挥智能体为你干活",
"new_chat.subtitle": "输入你的问题或任务",
- "new_chat.input_placeholder": "输入消息...",
+ "new_chat.input_placeholder": "输入消息。使用 @ 调用智能体、技能、连接器。",
"new_chat.attach_title": "上传附件(文本/PDF/Word/图片/视频)",
"new_chat.send_title": "发送",
"chat.empty": "无对话记录...",
"chat.queue_label": "待发送",
"chat.queue_hint": "可拖动排序 · 编辑 · 删除",
- "chat.input_placeholder": "继续对话...",
+ "chat.input_placeholder": "继续对话。使用 @ 调用智能体、技能、连接器。",
"chat.recipient_label": "给:",
"chat.recipient_commander": "指挥官",
"chat.recipient_commander_hint": "默认接收者,无需 @",
- "chat.recipient_picker_title": "切换接收者(指挥官 / 智能体)",
+ "chat.recipient_picker_title": "选择智能体、技能或连接器",
"chat.project_label": "项目:",
"chat.project_none": "无",
"chat.project_picker_title": "选择项目",
@@ -160,6 +170,12 @@
"chat.preview_unsupported_reveal": "打开所在文件夹",
"chat.preview_cancel": "关闭",
"chat.process_info": "过程信息",
+ "chat.menu.copy": "复制",
+ "chat.menu.scratch_edit": "临时编辑",
+ "chat.md_drawer.scratch_title": "临时编辑",
+ "chat.md_drawer.close_confirm": "未保存的修改将被丢弃,确定关闭?",
+ "chat.md_drawer.copy_draft": "复制",
+ "chat.md_drawer.send_to_chat": "作为消息发送",
"conversation_info.toggle_title": "对话信息",
"conversation_info.title": "对话信息",
"conversation_info.tab_tasks": "任务",
@@ -315,12 +331,15 @@
"skills.clear_chat": "清空",
"skills.clear_chat_title": "清空当前技能的对话记录",
"skills.chat_input_placeholder": "描述需要修改的内容...",
- "skills.use_prefix": "使用 {skill} skill:{content}",
+ "skills.use_label": "技能:{skill}",
+ "skills.use_prefix": "使用 {skill} 技能:{content}",
"skills.rename_title": "点击重命名",
"skills.source_custom": "自定义",
"skills.source_builtin": "内置",
"skills.name_invalid": "名称需以字母开头,可含字母 / 数字 / 下划线 / 横线,词之间允许单个空格",
"skills.desc_unset": "(未设置描述)",
+ "skills.no_match": "无匹配技能",
+ "skills.no_project_skills": "当前项目未绑定技能。",
"skills.loading": "加载中...",
"skills.load_failed": "加载失败",
"skills.saving": "保存中…",
@@ -355,6 +374,7 @@
"agents.custom_group": "自定义",
"agents.builtin_group": "平台",
"agents.back": "返回智能体",
+ "agents.update_failed": "更新失败",
"agents.use": "使用",
"agents.use_tooltip": "使用此智能体",
"agents.more_actions": "更多操作",
@@ -362,6 +382,7 @@
"agents.delete": "卸载",
"agents.label_desc": "简介",
"agents.label_runtime": "外接智能体",
+ "agents.label_project_dir": "项目目录",
"agents.label_workflow": "工作流程",
"agents.clear_chat": "清空",
"agents.clear_chat_title": "清空当前智能体的对话记录",
@@ -850,6 +871,12 @@
"agent.external_badge.opencode": "外接 · OpenCode",
"agent.external_badge.hermes": "外接 · Hermes",
"agent.cli_missing": "外接智能体未安装",
+ "agents.project_dir_workspace": "工作区",
+ "agents.project_dir_custom": "自定义",
+ "agents.project_dir_missing": "目录不存在",
+ "agents.project_dir_use_workspace": "使用工作区",
+ "agents.project_dir_save_failed": "保存项目目录失败",
+ "agents.project_dir_load_failed": "加载项目目录失败",
"input.dir.none": "(未选择)",
"input.dir.pick": "选择目录…",
"input.dir.change": "更换…",
@@ -875,7 +902,12 @@
"skill_modal.dir_none": "(未选择)",
"skill_modal.err_url_invalid": "URL 必须以 http(s):// 开头",
"skill_modal.err_dir_missing": "请先选择源目录",
+ "agent_picker.tab_agents": "智能体",
+ "agent_picker.tab_skills": "技能",
+ "agent_picker.tab_connectors": "连接器",
"agent_picker.search_placeholder": "搜索智能体...",
+ "agent_picker.search_skills_placeholder": "搜索技能...",
+ "agent_picker.search_connectors_placeholder": "搜索连接器...",
"add_account.title": "新增账号",
"oauth_flow.title": "OAuth 登录",
"oauth_flow.preparing": "正在准备授权…",
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 8b9a7685..5485faee 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -16,6 +16,11 @@ function _agentUiIconHtml(name, className) {
// Mirror of `agents.ts::RESERVED_AGENT_NAMES` so the renderer can fail fast
// without a round-trip. Server is still authoritative — this is just UX.
const _RESERVED_AGENT_NAMES = new Set(['指挥官', '总指挥', 'コマンダー', '司令官', 'commander']);
+const _SPEC_CATEGORY_CODE_RE = /^[a-z][a-z0-9_-]{0,79}$/;
+function _normalizeSpecCategoryForHiddenSave(category) {
+ const code = String(category || '').trim().toLowerCase();
+ return _SPEC_CATEGORY_CODE_RE.test(code) ? code : 'general';
+}
/** Look up the localized "External · <Brand>" label for an agent runtime
* type. The external badge (formerly "CLI · X") is the single
* user-facing tag for cli-runtime agents — name surfaces consistently
@@ -377,6 +382,14 @@ window.addEventListener('i18n-change', () => {
}
});
+async function refreshAgentsAfterMarketplaceReconcile() {
+ await loadAgents(true);
+ if (_agentEditing) return;
+ if (_selectedAgent?.id && _selectedAgent.source === 'builtin') {
+ await selectAgent(_selectedAgent.id);
+ }
+}
+
/** Render the per-row "⋯" menu items based on the target agent's source +
* enabled state. Called fresh on each open so the toggle label is right
* and builtin agents see only the enable/disable item. */
@@ -530,6 +543,7 @@ function _renderAgentDetail(agent, editing) {
// without entering edit mode. The header chip was removed because
// it duplicated information the dropdown already exposes.
_renderAgentDetailRuntime(agent);
+ _renderAgentDetailProjectDir(agent);
const localizedDesc = pickDesc(agent, getLang()).trim();
descEl.textContent = localizedDesc;
@@ -580,6 +594,8 @@ function _renderAgentDetail(agent, editing) {
}
_renderAgentEnabledButton({ id: agent.agent_id, enabled: agent.enabled !== false });
+ _renderAgentOutputFormatSection(agent);
+
_toggleAgentFieldEditable(editing);
}
@@ -602,6 +618,7 @@ function _renderAgentOutputFormatSection(agent) {
const canEdit = agent.source === 'custom'
|| (agent.source === 'builtin' && typeof isDevMode === 'function' && false);
+ || (agent.source === 'builtin' && typeof isDevMode === 'function' && false);
slot.innerHTML = '';
const mount = document.createElement('div');
@@ -612,6 +629,9 @@ function _renderAgentOutputFormatSection(agent) {
{ value: 'markdown_only', label: t('agents.output_format_markdown_only') || 'Markdown only' },
{ value: 'dashboard', label: t('agents.output_format_dashboard') || 'Dashboard (no artifact)' },
{ value: 'artifact', label: t('agents.output_format_artifact') || 'Artifact (Dashboard + HTML)' },
+ { value: 'markdown_only', label: t('agents.output_format_markdown_only') },
+ { value: 'dashboard', label: t('agents.output_format_dashboard') },
+ { value: 'artifact', label: t('agents.output_format_artifact') },
];
// Map legacy on-disk values to the new 3-option display. `'allow_artifacts'` is the renamed
// `'artifact'`. `'auto'` / missing show as `'markdown_only'` (the new default); the field on
@@ -637,18 +657,21 @@ function _renderAgentOutputFormatSection(agent) {
if (!res || !res.ok) {
api.setValue(current);
uiAlert((res && res.error) || t('agents.update_failed') || 'Update failed');
+ uiAlert((res && res.error) || t('agents.update_failed'));
} else if (res.agent) {
agent.output_format = res.agent.output_format;
}
} catch (err) {
api.setValue(current);
uiAlert((err && err.message) || 'Update failed');
+ uiAlert((err && err.message) || t('agents.update_failed'));
}
},
});
if (!canEdit) {
// Disable the trigger — read-only display for builtin agents in
// non-dev mode (mirrors the connectors row pattern).
+ // non-dev mode (mirrors the runtime row pattern).
const trigger = mount.querySelector('.ai-select-trigger');
if (trigger) { trigger.setAttribute('disabled', ''); trigger.style.pointerEvents = 'none'; trigger.style.opacity = '0.6'; }
}
@@ -837,6 +860,106 @@ async function _renderAgentDetailRuntime(agent) {
});
}
+/** Project directory setting for external coding agents (claude / codex).
+ * Stored in a local-only main-process config; each conversation copies
+ * the effective value on its first coding-agent dispatch. */
+async function _renderAgentDetailProjectDir(agent) {
+ const section = document.getElementById('agents-detail-project-dir-section');
+ const slot = document.getElementById('agents-detail-project-dir');
+ if (!section || !slot) return;
+ const cli = agent.runtime?.kind === 'cli' ? agent.runtime.cli : '';
+ const supportsProjectDir = typeof cliIsCodingAgent === 'function' && cliIsCodingAgent(cli);
+ if (!supportsProjectDir) {
+ section.style.display = 'none';
+ slot.innerHTML = '';
+ return;
+ }
+ section.style.display = '';
+ slot.dataset.agentId = agent.agent_id;
+
+ const canEdit = agent.source === 'custom'
+ || (agent.source === 'builtin' && typeof isDevMode === 'function' && false);
+
+ const renderInfo = (info) => {
+ if (_selectedAgent?.id !== agent.agent_id || slot.dataset.agentId !== agent.agent_id) return;
+ const mode = info?.mode === 'custom' ? 'custom' : 'workspace';
+ const missing = mode === 'custom' && info.exists === false;
+ const pathText = String(info?.path || info?.workspace_path || '');
+ const badge = mode === 'custom'
+ ? t('agents.project_dir_custom')
+ : t('agents.project_dir_workspace');
+ const status = missing ? t('agents.project_dir_missing') : badge;
+ const cardClass = [
+ 'agent-project-dir-card',
+ mode === 'workspace' ? 'is-workspace' : 'is-custom',
+ missing ? 'is-missing' : '',
+ canEdit ? '' : 'is-disabled',
+ ].filter(Boolean).join(' ');
+ slot.innerHTML = `
+ <div class="${cardClass}">
+ ${_agentUiIconHtml(missing ? 'warning' : 'folder-open', 'agent-project-dir-icon')}
+ <div class="agent-project-dir-main">
+ <div class="agent-project-dir-path" title="${escapeHtml(pathText)}">${escapeHtml(pathText)}</div>
+ <div class="agent-project-dir-mode">${escapeHtml(status)}</div>
+ </div>
+ <div class="agent-project-dir-actions">
+ <button type="button" class="btn btn-sm" data-act="pick" ${canEdit ? '' : 'disabled'}>${escapeHtml(t('input.dir.change'))}</button>
+ ${mode === 'custom' ? `<button type="button" class="btn btn-sm" data-act="reset" ${canEdit ? '' : 'disabled'}>${escapeHtml(t('agents.project_dir_use_workspace'))}</button>` : ''}
+ </div>
+ </div>`;
+ const pickBtn = slot.querySelector('[data-act="pick"]');
+ const resetBtn = slot.querySelector('[data-act="reset"]');
+ const pick = async () => {
+ if (!canEdit) return;
+ try {
+ const picked = await window.orkas.invoke('common.pickDirectory', {
+ title: t('agents.label_project_dir'),
+ });
+ if (!picked || picked.cancelled || !picked.path) return;
+ const saved = await window.orkas.invoke('agents.cliProjectDir.set', {
+ agent_id: agent.agent_id,
+ path: picked.path,
+ });
+ if (!saved || !saved.ok) {
+ await uiAlert((saved && saved.error) || t('agents.project_dir_save_failed'));
+ return;
+ }
+ renderInfo(saved.info);
+ } catch (err) {
+ await uiAlert((err && err.message) || t('agents.project_dir_save_failed'));
+ }
+ };
+ pickBtn?.addEventListener('click', (e) => { e.stopPropagation(); pick(); });
+ resetBtn?.addEventListener('click', async (e) => {
+ e.stopPropagation();
+ if (!canEdit) return;
+ try {
+ const saved = await window.orkas.invoke('agents.cliProjectDir.set', {
+ agent_id: agent.agent_id,
+ path: '',
+ });
+ if (!saved || !saved.ok) {
+ await uiAlert((saved && saved.error) || t('agents.project_dir_save_failed'));
+ return;
+ }
+ renderInfo(saved.info);
+ } catch (err) {
+ await uiAlert((err && err.message) || t('agents.project_dir_save_failed'));
+ }
+ });
+ };
+
+ slot.innerHTML = `<div class="agent-project-dir-card is-loading">${_agentUiIconHtml('folder-open', 'agent-project-dir-icon')}<div class="agent-project-dir-main"><div class="agent-project-dir-path">${escapeHtml(t('common.loading'))}</div></div></div>`;
+ try {
+ const res = await window.orkas.invoke('agents.cliProjectDir.get', { agent_id: agent.agent_id });
+ if (!res || !res.ok || !res.info) throw new Error(res?.error || 'failed');
+ renderInfo(res.info);
+ } catch (err) {
+ _agentsLog.warn('load agent project dir failed', err);
+ slot.innerHTML = `<div class="agents-detail-placeholder">${escapeHtml(t('agents.project_dir_load_failed'))}</div>`;
+ }
+}
+
/** Render the detail-page avatar slot. Custom agents get a clickable avatar
* that opens the picker; builtin agents just show theirs read-only. Each
* picker change is sent as an `agents.update` IPC and the local cache is
@@ -1011,10 +1134,13 @@ async function _flushAgentFieldSave({ validate = false } = {}) {
}
_pendingAgentField = null;
try {
+ const body = { [field]: value };
+ const category = _normalizeSpecCategoryForHiddenSave(_selectedAgent.category);
+ if (category !== _selectedAgent.category) body.category = category;
const res = await apiFetch(`/api/agents/${encodeURIComponent(_selectedAgent.id)}/update`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ [field]: value }),
+ body: JSON.stringify(body),
});
const data = await res.json();
if (!data.ok) {
@@ -1169,15 +1295,29 @@ function openAgentModal() {
mountExternalCliSelect((cli) => _applyExternalCliDefaults(cli)).catch(() => {});
}
- // Marketplace category dropdowns (both tabs). 24h cached in main, fallback to defaults.
- if (typeof mountMarketplaceCategorySelect === 'function') {
- mountMarketplaceCategorySelect('agent-category-select').catch(() => {});
- mountMarketplaceCategorySelect('agent-ext-category-select').catch(() => {});
- }
+ // Output-format dropdown (Create tab only — External/CLI agents don't read the worker prompt
+ // hint). Default `markdown_only` matches the new "opt-in to richer formats" stance documented
+ // in PC/CLAUDE.md §6; detail-page dropdown does the same 3-option set + maps legacy values.
+ _mountAgentOutputFormatCreateSelect();
modal.classList.add('open');
setTimeout(() => document.getElementById('agent-name-input')?.focus(), 50);
}
+
+function _mountAgentOutputFormatCreateSelect() {
+ const slot = document.getElementById('agent-output-format-select');
+ if (!slot) return;
+ // Mount directly on the slot — _aiSelectMount stamps `dataset.value` on the
+ // element it's given, and _saveCreateAgent reads `slot.dataset.value`. An
+ // intermediate wrapper div would put the dataset out of reach of the save.
+ slot.innerHTML = '';
+ const options = [
+ { value: 'markdown_only', label: t('agents.output_format_markdown_only') },
+ { value: 'dashboard', label: t('agents.output_format_dashboard') },
+ { value: 'artifact', label: t('agents.output_format_artifact') },
+ ];
+ _aiSelectMount(slot, { options, value: 'markdown_only' });
+}
window.openAgentModal = openAgentModal;
function closeAgentModal() {
@@ -1222,11 +1362,13 @@ async function _saveCreateAgent({ msgEl }) {
return;
}
- const category = document.getElementById('agent-category-select')?.dataset.value || '';
+ // Output-format pick from the modal's dropdown. Default `markdown_only` if for some reason the
+ // dataset wasn't stamped (defensive — _mountAgentOutputFormatCreateSelect always sets it).
+ const outputFormat = document.getElementById('agent-output-format-select')?.dataset.value || 'markdown_only';
try {
const avatar = randomAgentAvatar();
- const body = { name, description, icon: avatar.icon, color: avatar.color, category };
+ const body = { name, description, icon: avatar.icon, color: avatar.color, category: 'general', output_format: outputFormat };
const res = await apiFetch('/api/agents/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -1296,8 +1438,6 @@ async function _saveExternalAgent({ msgEl }) {
const description_zh = editingZh ? desc : (defaults ? defaults.description_zh : desc);
const description_en = editingZh ? (defaults ? defaults.description_en : desc) : desc;
- const category = document.getElementById('agent-ext-category-select')?.dataset.value || '';
-
try {
const avatar = randomAgentAvatar();
const body = {
@@ -1306,7 +1446,7 @@ async function _saveExternalAgent({ msgEl }) {
description_zh, description_en,
icon: avatar.icon, color: avatar.color,
runtime: { kind: 'cli', cli },
- category,
+ category: 'general',
};
const res = await apiFetch('/api/agents/create', {
method: 'POST',
@@ -1586,6 +1726,40 @@ if (typeof window !== 'undefined') {
// Set on every `_openAgentPicker`; consumed by `_renderAgentPickerList` and
// the search-input change handler so live filtering stays scoped.
let _pickerBoundAgentIds = null;
+let _pickerBoundSkillIds = null;
+let _agentPickerTab = 'agents';
+const _AGENT_PICKER_TABS = new Set(['agents', 'skills', 'connectors']);
+
+function _normalizeAgentPickerTab(tab) {
+ return _AGENT_PICKER_TABS.has(tab) ? tab : 'agents';
+}
+
+function _agentPickerSearchPlaceholder() {
+ if (_agentPickerTab === 'skills') return t('agent_picker.search_skills_placeholder');
+ if (_agentPickerTab === 'connectors') return t('agent_picker.search_connectors_placeholder');
+ return t('agent_picker.search_placeholder');
+}
+
+function _updateAgentPickerChrome() {
+ const picker = document.getElementById('agent-picker');
+ if (!picker) return;
+ picker.querySelectorAll('[data-agent-picker-tab]').forEach((btn) => {
+ const active = btn.dataset.agentPickerTab === _agentPickerTab;
+ btn.classList.toggle('active', active);
+ btn.setAttribute('aria-selected', active ? 'true' : 'false');
+ });
+ const search = document.getElementById('agent-picker-search');
+ if (search) search.placeholder = _agentPickerSearchPlaceholder();
+}
+
+function _setAgentPickerTab(tab, opts = {}) {
+ _agentPickerTab = _normalizeAgentPickerTab(tab);
+ const search = document.getElementById('agent-picker-search');
+ if (search && !opts.keepSearch) search.value = '';
+ _updateAgentPickerChrome();
+ _renderAgentPickerList(search ? search.value : '');
+ if (opts.focusSearch !== false) setTimeout(() => search?.focus(), 0);
+}
function _resolveActiveProjectId(anchorId) {
if (anchorId === 'new-chat-recipient-chip') {
@@ -1616,21 +1790,29 @@ async function _openAgentPicker(anchorBtn) {
// agent silently disappears from the list. Mirror the `setView('agents')`
// force-refresh in `boot.js` here so the picker is also a ground-truth
// surface; cost is one IPC + dir scan per picker open (sub-ms in practice).
- await loadAgents(true);
+ await Promise.all([
+ loadAgents(true),
+ (typeof loadSkills === 'function' ? loadSkills(true) : Promise.resolve()),
+ (typeof loadConnectors === 'function' ? loadConnectors() : Promise.resolve()),
+ ]);
// Refresh project-scope bindings on every open so the picker reflects
// whatever project the user just picked (commander chip) or whatever
// project the active conv belongs to.
_pickerBoundAgentIds = null;
+ _pickerBoundSkillIds = null;
const pid = _resolveActiveProjectId(anchorBtn.id);
if (pid) {
try {
const res = await window.orkas.invoke('projects.bindings.list', { projectId: pid });
- if (res?.ok) _pickerBoundAgentIds = new Set((res.bindings && res.bindings.agents) || []);
+ if (res?.ok) {
+ _pickerBoundAgentIds = new Set((res.bindings && res.bindings.agents) || []);
+ _pickerBoundSkillIds = new Set((res.bindings && res.bindings.skills) || []);
+ }
} catch (_) { /* fall back to global listing */ }
}
// Render first so measurement in _positionPopoverAboveOrBelow reflects
// the real list height (not stale content from a previous open).
- _renderAgentPickerList('');
+ _setAgentPickerTab('agents', { focusSearch: false });
_positionPopoverAboveOrBelow(picker, anchorBtn);
setTimeout(() => document.getElementById('agent-picker-search')?.focus(), 30);
}
@@ -1640,14 +1822,24 @@ function _closeAgentPicker() {
if (picker) picker.style.display = 'none';
// NOTE: callers that close-without-selection (Esc / click-outside) must
// also clear `_atKeyMark` — otherwise the next picker open would consume
- // a stale `@`. Selection callers leave the mark so _triggerAgent can use
- // it before clearing.
+ // a stale `@`. Selection callers leave the mark so _triggerPickerItem can
+ // use it before clearing.
}
function _renderAgentPickerList(filterText) {
const listEl = document.getElementById('agent-picker-list');
const picker = document.getElementById('agent-picker');
+ if (!listEl) return;
const anchorId = picker?.dataset.anchorId || '';
+ _updateAgentPickerChrome();
+ if (_agentPickerTab === 'skills') {
+ _renderSkillPickerList(listEl, filterText, anchorId);
+ return;
+ }
+ if (_agentPickerTab === 'connectors') {
+ _renderConnectorPickerList(listEl, filterText, anchorId);
+ return;
+ }
// Disabled agents are filtered out — picker is a "what can I dispatch right
// now" UI, and re-enabling lives in the management page (Agents view + ⋯ menu).
let agents = (_agentsCache || []).filter((a) => a.enabled !== false);
@@ -1686,7 +1878,7 @@ function _renderAgentPickerList(filterText) {
const commanderName = t('chat.recipient_commander');
const commanderMatchesFilter = !q || commanderName.toLowerCase().includes(q);
if (!filtered.length && !(isRecipientPicker && commanderMatchesFilter)) {
- listEl.innerHTML = `<div class="skill-picker-item" style="color:#9ca3af">${escapeHtml(t('agents.no_match'))}</div>`;
+ listEl.innerHTML = `<div class="skill-picker-empty">${escapeHtml(t('agents.no_match'))}</div>`;
return;
}
const groups = { custom: [], builtin: [] };
@@ -1697,14 +1889,14 @@ function _renderAgentPickerList(filterText) {
list.map(a => {
const aDesc = pickDesc(a, lang).trim();
return `
- <div class="skill-picker-item" data-id="${escapeHtml(a.agent_id)}" data-name="${escapeHtml(a.name || a.agent_id)}">
+ <div class="skill-picker-item" data-kind="agent" data-id="${escapeHtml(a.agent_id)}" data-name="${escapeHtml(a.name || a.agent_id)}">
<div class="skill-picker-item-name">${escapeHtml(a.name || t('agents.unnamed'))}</div>
${aDesc ? `<div class="skill-picker-item-desc">${escapeHtml(aDesc)}</div>` : ''}
</div>`;
}).join('');
};
const commanderHtml = (isRecipientPicker && commanderMatchesFilter)
- ? `<div class="skill-picker-item" data-id="__commander__" data-name="${escapeHtml(commanderName)}">
+ ? `<div class="skill-picker-item" data-kind="agent" data-id="__commander__" data-name="${escapeHtml(commanderName)}">
<div class="skill-picker-item-name">${escapeHtml(commanderName)}</div>
<div class="skill-picker-item-desc">${escapeHtml(t('chat.recipient_commander_hint'))}</div>
</div>`
@@ -1718,10 +1910,97 @@ function _renderAgentPickerList(filterText) {
? `<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);
+ _bindAgentPickerListItems(listEl, anchorId);
+}
+
+function _matchPickerItem(q, name, desc, extra = '') {
+ if (!q) return true;
+ return String(name || '').toLowerCase().includes(q)
+ || String(desc || '').toLowerCase().includes(q)
+ || String(extra || '').toLowerCase().includes(q);
+}
+
+function _pickerMatchScore(q, name) {
+ const n = String(name || '').toLowerCase();
+ if (!q) return 0;
+ if (n === q) return 0;
+ if (n.startsWith(q)) return 1;
+ if (n.includes(q)) return 2;
+ return 3;
+}
+
+function _renderSkillPickerList(listEl, filterText, anchorId) {
+ const lang = getLang();
+ const q = (filterText || '').toLowerCase();
+ let skills = (_skillsCache || []).filter((s) => s.enabled !== false);
+ if (_pickerBoundSkillIds) skills = skills.filter((s) => _pickerBoundSkillIds.has(s.id));
+ const filtered = q
+ ? skills
+ .filter((s) => _matchPickerItem(q, s.name || s.id, pickDesc(s, lang), s.id))
+ .sort((a, b) => _pickerMatchScore(q, a.name || a.id) - _pickerMatchScore(q, b.name || b.id))
+ : skills;
+ if (!filtered.length) {
+ const hint = (!q && _pickerBoundSkillIds && _pickerBoundSkillIds.size === 0)
+ ? `<div class="skill-picker-empty-hint">${escapeHtml(t('skills.no_project_skills'))}</div>`
+ : '';
+ listEl.innerHTML = hint + `<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 groupHtml = (label, list) => {
+ if (!list.length) return '';
+ return `<div class="skill-picker-group-label">${escapeHtml(label)}</div>` +
+ list.map((s) => {
+ const desc = pickDesc(s, lang).trim();
+ const name = s.name || s.id;
+ return `
+ <div class="skill-picker-item" data-kind="skill" data-id="${escapeHtml(s.id)}" data-name="${escapeHtml(name)}">
+ <div class="skill-picker-item-name">${escapeHtml(name)}</div>
+ ${desc ? `<div class="skill-picker-item-desc">${escapeHtml(desc)}</div>` : ''}
+ </div>`;
+ }).join('');
+ };
+ const hint = (!q && _pickerBoundSkillIds && _pickerBoundSkillIds.size === 0)
+ ? `<div class="skill-picker-empty-hint">${escapeHtml(t('skills.no_project_skills'))}</div>`
+ : '';
+ listEl.innerHTML = hint + groupHtml(t('skills.source_custom'), groups.custom) + groupHtml(t('skills.source_builtin'), groups.builtin);
+ _bindAgentPickerListItems(listEl, anchorId);
+}
+
+function _renderConnectorPickerList(listEl, filterText, anchorId) {
+ const q = (filterText || '').toLowerCase();
+ const items = (typeof listUsableConnectorsForPicker === 'function')
+ ? listUsableConnectorsForPicker()
+ : [];
+ const filtered = q
+ ? items
+ .filter((c) => _matchPickerItem(q, c.name || c.id, c.description, `${c.id} ${c.account || ''}`))
+ .sort((a, b) => _pickerMatchScore(q, a.name || a.id) - _pickerMatchScore(q, b.name || b.id))
+ : items;
+ if (!filtered.length) {
+ listEl.innerHTML = `<div class="skill-picker-empty">${escapeHtml(q ? t('connectors.no_match') : t('connectors.no_connected'))}</div>`;
+ return;
+ }
+ listEl.innerHTML = `<div class="skill-picker-group-label">${escapeHtml(t('connectors.group.connected'))}</div>` +
+ filtered.map((c) => {
+ const descParts = [];
+ if (c.description) descParts.push(c.description);
+ if (c.account) descParts.push(t('connectors.account_label', { account: c.account }));
+ return `
+ <div class="skill-picker-item" data-kind="connector" data-id="${escapeHtml(c.id)}" data-name="${escapeHtml(c.name || c.id)}">
+ <div class="skill-picker-item-name">${escapeHtml(c.name || c.id)}</div>
+ ${descParts.length ? `<div class="skill-picker-item-desc">${escapeHtml(descParts.join(' · '))}</div>` : ''}
+ </div>`;
+ }).join('');
+ _bindAgentPickerListItems(listEl, anchorId);
+}
+
+function _bindAgentPickerListItems(listEl, anchorId) {
for (const el of listEl.querySelectorAll('[data-id]')) {
el.addEventListener('click', async () => {
_closeAgentPicker();
- await _triggerAgent(el.dataset.id, el.dataset.name, anchorId);
+ await _triggerPickerItem(el.dataset.kind || 'agent', el.dataset.id, el.dataset.name, anchorId);
});
el.addEventListener('mouseenter', () => {
const all = listEl.querySelectorAll('.skill-picker-item[data-id]');
@@ -1755,13 +2034,33 @@ function _moveAgentPickerActive(delta) {
_setAgentPickerActive(next);
}
+function _targetFromPickerAnchor(anchorId) {
+ return anchorId === 'new-chat-recipient-chip' ? 'new-chat' : 'conversation';
+}
+
+async function _triggerPickerItem(kind, itemId, itemName, anchorId) {
+ const target = _targetFromPickerAnchor(anchorId);
+ if (kind === 'skill') {
+ setChatSkill(target, itemName || itemId);
+ _consumeAtKeyChar();
+ const inputId = target === 'new-chat' ? 'new-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';
+ _focusInput(document.getElementById(inputId));
+ return;
+ }
+ await _triggerAgent(itemId, itemName, anchorId);
+}
+
// Route an agent selection to the right behaviour based on which button
// triggered the picker:
-// - conversation toolbar → send/queue "run <name>" in the CURRENT conv.
-// Never opens a new conv. No hidden backend injection — the model reads
-// the visible message and follows chat_commander.md rule 0.
-// - new-chat toolbar → create a new normal conv + run agent (useAgent)
-// Selection is one-shot (no persistent chip).
+// - 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';
if (isRecipientAnchor) {
@@ -1810,6 +2109,14 @@ function _focusInput(input) {
function bindAgentPickers() {
// Re-bindable helper: wire the recipient chips on both chat panels +
// under anchorIds. Guarded with dataset.bound so a second call is a no-op.
+ document.querySelectorAll('[data-agent-picker-tab]').forEach((btn) => {
+ if (btn.dataset.bound === '1') return;
+ btn.dataset.bound = '1';
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _setAgentPickerTab(btn.dataset.agentPickerTab || 'agents');
+ });
+ });
const searchInput = document.getElementById('agent-picker-search');
searchInput?.addEventListener('input', () => {
_renderAgentPickerList(searchInput.value);
@@ -1848,9 +2155,9 @@ function bindAgentPickers() {
});
}
- // `@` keystroke in either chat textarea opens the recipient picker. The
- // typed `@` itself is removed on a successful pick (see _consumeAtKeyChar)
- // so the chip is the single source of truth for recipient.
+ // `@` keystroke in either chat textarea opens the agent / skill / connector
+ // picker. The typed `@` itself is removed on a successful pick so the chips
+ // are the single source of truth for the selected route/context.
const onAtKey = (anchorId) => (e) => {
if (e.key !== '@') return;
const btn = document.getElementById(anchorId);
@@ -1862,8 +2169,7 @@ function bindAgentPickers() {
inputId: ta.id || '',
posAfter: typeof ta.selectionStart === 'number' ? ta.selectionStart : 0,
};
- if (!_agentsCache) loadAgents().then(() => _openAgentPicker(btn));
- else _openAgentPicker(btn);
+ _openAgentPicker(btn);
}, 0);
};
// Backspace right after a `@<name>` token (with or without the trailing
@@ -1917,6 +2223,13 @@ function bindAgentPickers() {
_atKeyMark = null;
_closeAgentPicker();
});
+ window.addEventListener('i18n-change', () => {
+ _updateAgentPickerChrome();
+ if (picker.style.display !== 'none') {
+ const search = document.getElementById('agent-picker-search');
+ _renderAgentPickerList(search ? search.value : '');
+ }
+ });
}
}
diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.js
index 9c30be58..f32751a7 100644
--- a/src/renderer/modules/boot.js
+++ b/src/renderer/modules/boot.js
@@ -15,6 +15,7 @@ async function bootApp() {
await loadProjects();
await loadConversations();
await loadAgents();
+ await loadSkills();
// Warm the commander avatar cache so the first chat render doesn't fall
// back to the default for a frame.
if (typeof _ensureCommanderAvatarLoaded === 'function') _ensureCommanderAvatarLoaded();
diff --git a/src/renderer/modules/chat-md-drawer.js b/src/renderer/modules/chat-md-drawer.js
new file mode 100644
index 00000000..7010bb6f
--- /dev/null
+++ b/src/renderer/modules/chat-md-drawer.js
@@ -0,0 +1,157 @@
+// ─── 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
+// ephemeral — context-menu "临时编辑" on a chat selection
+//
+// Single-instance: reopening always closes the previous mount. The drawer's
+// own close button (header) goes through the same dirty-check as opening a
+// fresh source over an unsaved one.
+
+const _chatMdDrawerLog = createLogger('chat-md-drawer');
+
+let _cmdState = null; // { controller, source, title, dirty }
+
+function openChatMdDrawer({ source, initialMode, title }) {
+ if (!source || typeof source.kind !== 'string') {
+ _chatMdDrawerLog.warn('openChatMdDrawer called without source.kind');
+ return;
+ }
+ const panel = document.getElementById('chat-md-drawer-panel');
+ const titleEl = document.getElementById('chat-md-drawer-title');
+ const bodyEl = document.getElementById('chat-md-drawer-body');
+ const actionsEl = document.getElementById('chat-md-drawer-actions');
+ if (!panel || !bodyEl || !actionsEl) {
+ _chatMdDrawerLog.warn('chat-md-drawer DOM missing — drawer container not in index.html');
+ return;
+ }
+
+ // Replacing an open mount: ask before discarding unsaved edits.
+ if (_cmdState && _cmdState.controller && _cmdState.dirty) {
+ const proceed = window.confirm(t('chat.md_drawer.close_confirm'));
+ if (!proceed) return;
+ }
+ _teardownCmd();
+
+ const resolvedTitle = title || _defaultTitle(source);
+ if (titleEl) titleEl.textContent = resolvedTitle;
+ panel.classList.add('is-open');
+ panel.hidden = false;
+
+ _cmdState = { controller: null, source, title: resolvedTitle, dirty: false };
+
+ _cmdState.controller = mountMdViewEdit({
+ bodyEl,
+ actionsEl,
+ source,
+ initialMode: source.kind === 'ephemeral' ? 'edit' : (initialMode || 'view'),
+ callbacks: {
+ onDirtyChange: (dirty) => { if (_cmdState) _cmdState.dirty = !!dirty; },
+ onReveal: () => {
+ if (source.kind !== 'workspace') return;
+ try {
+ const payload = { path: source.absPath };
+ if (source.cid) payload.cid = source.cid;
+ window.orkas.invoke('workspace.revealPath', payload);
+ } catch (err) {
+ _chatMdDrawerLog.warn('revealPath failed', err);
+ }
+ },
+ // The drawer does not surface a delete action; setting it here would
+ // be ignored (capability defaults already skip delete for workspace).
+ onSendToChatInput: (text) => {
+ const ok = _sendDraftToChatInput(text);
+ if (ok) closeChatMdDrawer({ force: true });
+ },
+ },
+ });
+
+ _bindCloseHandlers();
+}
+
+function closeChatMdDrawer({ force = false } = {}) {
+ if (!_cmdState) return;
+ if (!force && _cmdState.dirty) {
+ const proceed = window.confirm(t('chat.md_drawer.close_confirm'));
+ if (!proceed) return;
+ }
+ const panel = document.getElementById('chat-md-drawer-panel');
+ if (panel) {
+ panel.classList.remove('is-open');
+ panel.hidden = true;
+ }
+ _teardownCmd();
+}
+
+function isChatMdDrawerOpen() {
+ return !!_cmdState;
+}
+
+function _teardownCmd() {
+ if (_cmdState && _cmdState.controller) {
+ try { _cmdState.controller.destroy(); }
+ catch (err) { _chatMdDrawerLog.warn('controller.destroy threw', err); }
+ }
+ _cmdState = null;
+}
+
+function _defaultTitle(source) {
+ if (source.kind === 'workspace' && source.absPath) {
+ return source.absPath.split(/[\\/]/).pop() || source.absPath;
+ }
+ if (source.kind === 'ephemeral') {
+ return t('chat.md_drawer.scratch_title');
+ }
+ return '';
+}
+
+// ── Close button / Esc dismisser ────────────────────────────────────────
+
+let _cmdHandlersBound = false;
+function _bindCloseHandlers() {
+ if (_cmdHandlersBound) return;
+ _cmdHandlersBound = true;
+ const closeBtn = document.getElementById('chat-md-drawer-close');
+ if (closeBtn) closeBtn.addEventListener('click', () => closeChatMdDrawer());
+ document.addEventListener('keydown', (e) => {
+ // IME guard (CLAUDE.md §8): don't intercept Escape while the user is
+ // committing a composition candidate.
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key !== 'Escape' || !_cmdState) return;
+ // If the drawer body has focus and is inside a textarea, let Escape
+ // exit the textarea selection rather than close the drawer (matches
+ // the behavior of the main chat composer).
+ const active = document.activeElement;
+ if (active && active.tagName === 'TEXTAREA' && active.closest('#chat-md-drawer-panel')) return;
+ closeChatMdDrawer();
+ });
+}
+
+// ── Send draft to chat input ────────────────────────────────────────────
+
+function _sendDraftToChatInput(text) {
+ const input = document.getElementById('chat-input');
+ if (!input) {
+ _chatMdDrawerLog.warn('chat-input not found — drawer "send to chat" no-op');
+ return false;
+ }
+ // Prepend a newline when there's already content so the snippet doesn't
+ // smash into the existing draft.
+ const existing = input.value || '';
+ const joiner = existing && !existing.endsWith('\n') ? '\n' : '';
+ input.value = `${existing}${joiner}${text}`;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ input.focus();
+ // Move caret to end so the user sees the inserted block.
+ try {
+ const end = input.value.length;
+ input.setSelectionRange(end, end);
+ } catch (_) { /* old jsdom — ignore */ }
+ return true;
+}
+
+// Expose to the global namespace so cross-module callers can open the drawer
+// without ESM imports (per CLAUDE.md §8).
+window.openChatMdDrawer = openChatMdDrawer;
+window.closeChatMdDrawer = closeChatMdDrawer;
+window.isChatMdDrawerOpen = isChatMdDrawerOpen;
diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.js
index 011c4d4f..a35f5c21 100644
--- a/src/renderer/modules/connectors.js
+++ b/src/renderer/modules/connectors.js
@@ -78,6 +78,24 @@ function _deriveBundleInstance(entry) {
};
}
+function listUsableConnectorsForPicker() {
+ const catalogById = new Map((_connectorsState.catalog || []).map((entry) => [entry.id, entry]));
+ const lang = (typeof getLang === 'function') ? getLang() : 'en';
+ return (_connectorsState.instances || [])
+ .filter((inst) => inst && inst.status && inst.status.kind === 'connected' && inst.enabled !== false)
+ .map((inst) => {
+ const entry = catalogById.get(inst.id) || _entryFromInstance(inst);
+ const account = inst.oauth_grant && inst.oauth_grant.account_label ? inst.oauth_grant.account_label : '';
+ return {
+ id: inst.id,
+ name: inst.display_name || entry.display_name || inst.id,
+ description: pickDesc(entry, lang),
+ account,
+ };
+ })
+ .sort((a, b) => (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base', numeric: true }));
+}
+
function _renderConnectorsGrid() {
const gridView = document.getElementById('connectors-grid-view');
if (!gridView) return;
diff --git a/src/renderer/modules/context-menu.js b/src/renderer/modules/context-menu.js
new file mode 100644
index 00000000..beb00803
--- /dev/null
+++ b/src/renderer/modules/context-menu.js
@@ -0,0 +1,133 @@
+// ─── Generic right-click context menu ───
+// Small floating menu anchored at the cursor; items are { label, onClick,
+// disabled? }. There's exactly one menu instance at a time — opening a new
+// menu closes the previous one. Dismissers: outside click, Escape, scroll,
+// resize, and the i18n-change broadcast (label text may need refreshing).
+//
+// IME guard (CLAUDE.md §8): the up/down/Enter shortcuts early-return when a
+// composition is active so a half-typed Chinese candidate doesn't trigger
+// the wrong menu item.
+
+const _ctxMenuLog = createLogger('context-menu');
+
+let _ctxMenuEl = null;
+let _ctxMenuItems = [];
+let _ctxMenuActiveIdx = -1;
+let _ctxMenuOpen = false;
+
+function showContextMenu(event, items) {
+ closeContextMenu();
+ if (!Array.isArray(items) || items.length === 0) return;
+ _ctxMenuItems = items.filter((it) => it && typeof it.label === 'string' && typeof it.onClick === 'function');
+ if (_ctxMenuItems.length === 0) return;
+
+ const menu = document.createElement('div');
+ menu.className = 'context-menu';
+ menu.setAttribute('role', 'menu');
+ menu.innerHTML = _ctxMenuItems.map((it, idx) =>
+ `<button type="button" class="context-menu-item${it.disabled ? ' is-disabled' : ''}"`
+ + ` data-context-menu-idx="${idx}" role="menuitem" tabindex="-1"`
+ + ` ${it.disabled ? 'disabled' : ''}>${escapeHtml(it.label)}</button>`
+ ).join('');
+ document.body.appendChild(menu);
+ _ctxMenuEl = menu;
+ _ctxMenuOpen = true;
+ _ctxMenuActiveIdx = -1;
+
+ // Place at cursor; flip when overflowing viewport. Read offset after
+ // appending so the menu has real dimensions.
+ const x = event.clientX || 0;
+ const y = event.clientY || 0;
+ const rect = menu.getBoundingClientRect();
+ const vw = window.innerWidth;
+ const vh = window.innerHeight;
+ const left = x + rect.width > vw - 4 ? Math.max(4, x - rect.width) : x;
+ const top = y + rect.height > vh - 4 ? Math.max(4, y - rect.height) : y;
+ menu.style.left = `${left}px`;
+ menu.style.top = `${top}px`;
+
+ menu.querySelectorAll('.context-menu-item').forEach((btn) => {
+ btn.addEventListener('click', (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const idx = Number(btn.dataset.contextMenuIdx);
+ const it = _ctxMenuItems[idx];
+ closeContextMenu();
+ if (it && !it.disabled) {
+ try { it.onClick(); }
+ catch (err) { _ctxMenuLog.warn('item onClick threw', err); }
+ }
+ });
+ btn.addEventListener('mouseenter', () => {
+ const idx = Number(btn.dataset.contextMenuIdx);
+ _setActiveIdx(idx);
+ });
+ });
+}
+
+function closeContextMenu() {
+ if (!_ctxMenuOpen) return;
+ _ctxMenuOpen = false;
+ _ctxMenuActiveIdx = -1;
+ if (_ctxMenuEl && _ctxMenuEl.parentNode) _ctxMenuEl.parentNode.removeChild(_ctxMenuEl);
+ _ctxMenuEl = null;
+ _ctxMenuItems = [];
+}
+
+function _setActiveIdx(idx) {
+ if (!_ctxMenuEl) return;
+ if (idx < 0 || idx >= _ctxMenuItems.length) {
+ _ctxMenuActiveIdx = -1;
+ } else {
+ _ctxMenuActiveIdx = idx;
+ }
+ _ctxMenuEl.querySelectorAll('.context-menu-item').forEach((btn, i) => {
+ btn.classList.toggle('is-active', i === _ctxMenuActiveIdx);
+ });
+}
+
+// ── Dismissers ─────────────────────────────────────────────────────────
+
+document.addEventListener('mousedown', (e) => {
+ if (!_ctxMenuOpen) return;
+ if (_ctxMenuEl && _ctxMenuEl.contains(e.target)) return;
+ closeContextMenu();
+}, true);
+
+document.addEventListener('keydown', (e) => {
+ if (!_ctxMenuOpen) return;
+ // IME composition guard — Chinese / Japanese / Korean Enter commits a
+ // candidate; don't fire menu actions while a composition is active.
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Escape') { e.preventDefault(); closeContextMenu(); return; }
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ let next = _ctxMenuActiveIdx + 1;
+ while (next < _ctxMenuItems.length && _ctxMenuItems[next].disabled) next += 1;
+ if (next < _ctxMenuItems.length) _setActiveIdx(next);
+ return;
+ }
+ if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ let prev = _ctxMenuActiveIdx - 1;
+ while (prev >= 0 && _ctxMenuItems[prev].disabled) prev -= 1;
+ if (prev >= 0) _setActiveIdx(prev);
+ return;
+ }
+ if (e.key === 'Enter') {
+ if (_ctxMenuActiveIdx < 0) return;
+ const it = _ctxMenuItems[_ctxMenuActiveIdx];
+ if (!it || it.disabled) return;
+ e.preventDefault();
+ closeContextMenu();
+ try { it.onClick(); }
+ catch (err) { _ctxMenuLog.warn('item onClick threw on Enter', err); }
+ }
+});
+
+window.addEventListener('scroll', () => closeContextMenu(), true);
+window.addEventListener('resize', () => closeContextMenu());
+window.addEventListener('i18n-change', () => closeContextMenu());
+
+window.showContextMenu = showContextMenu;
+window.closeContextMenu = closeContextMenu;
diff --git a/src/renderer/modules/contexts.js b/src/renderer/modules/contexts.js
index 90442fde..0097f114 100644
--- a/src/renderer/modules/contexts.js
+++ b/src/renderer/modules/contexts.js
@@ -7,7 +7,8 @@ const _contextsLog = createLogger('contexts');
let _ctxTree = []; // tree of {name, path, type:'dir'|'file', children?, bytes?, mtime?}
let _ctxExpanded = new Set(); // dir paths that are open
-let _ctxActive = null; // {id, content} — currently opened file in right-pane
+let _ctxActive = null; // {id} — currently opened file in right-pane
+let _ctxMveController = null; // active mountMdViewEdit controller for the right-pane md viewer
let _ctxPendingRename = null; // {path} — flagged for inline-rename on the
// next renderCtxTree() (set by the "new
// text file" action after creating an
@@ -950,7 +951,12 @@ async function revealCtxFile(rel) {
}
function _prepCtxViewerShell(rel) {
- _ctxActive = { id: rel, content: '' };
+ _ctxActive = { id: rel };
+ // Tear down the previous md mount before switching files — otherwise the
+ // outgoing controller's textarea-input listeners would still react to the
+ // about-to-be-replaced DOM and the drafts map could record updates against
+ // the wrong rel.
+ if (_ctxMveController) { try { _ctxMveController.destroy(); } catch (_) {} _ctxMveController = null; }
const empty = document.getElementById('contexts-editor-empty');
const wrap = document.getElementById('contexts-viewer-wrap');
const pathEl = document.getElementById('contexts-editor-path');
@@ -969,21 +975,50 @@ function _prepCtxViewerShell(rel) {
};
}
+// Per-file in-progress edit state, keyed by relpath. Survives switching to
+// another KB file or to another sidebar tab — coming back to the file
+// restores edit mode + the unsaved draft instead of dropping to read mode.
+// Lifetime = renderer session (cleared on Save / Cancel / Delete; re-keyed
+// on Rename). Not persisted across app restarts. Fed via the
+// `onDraftChange` callback below.
+const _ctxDrafts = new Map();
+
+function _ctxClearDraft(path) {
+ const key = path || (_ctxActive && _ctxActive.id);
+ if (key) _ctxDrafts.delete(key);
+}
+
function _showCtxTextViewer(rel, content) {
const els = _prepCtxViewerShell(rel);
if (!els) return;
- _ctxActive.content = content;
- if (_ctxDrafts.has(rel)) {
- // There's an in-progress edit for this file from earlier in the
- // session — restore it (textarea or preview, whichever the user was
- // in) instead of dropping to read mode and clobbering the draft.
- _enterCtxEdit();
- } else {
- _renderCtxViewerMd(els.bodyEl, els.actionsEl);
- }
+ _ctxMveController = mountMdViewEdit({
+ bodyEl: els.bodyEl,
+ actionsEl: els.actionsEl,
+ source: { kind: 'context', rel },
+ // Skip the read round-trip — caller already has the bytes.
+ initialContent: content,
+ // Restore in-progress edits if the user was previously typing in this
+ // file. mountMdViewEdit forces edit mode when `initialDraft` is present.
+ initialDraft: _ctxDrafts.get(rel) || null,
+ callbacks: {
+ // Mirror draft state into the per-file Map so it survives switching
+ // to another file in the tree and back.
+ onDraftChange: (draft) => {
+ if (draft === null) _ctxDrafts.delete(rel);
+ else _ctxDrafts.set(rel, draft);
+ },
+ onReveal: () => revealCtxFile(rel),
+ onDelete: () => _deleteCtxFromViewer(),
+ onSaved: async () => { await loadContexts(); },
+ },
+ });
els.bodyEl.scrollTop = 0;
}
+function _enterCtxEdit() {
+ if (_ctxMveController) _ctxMveController.setMode('edit');
+}
+
function _showCtxImageViewer(rel, base64, mediaType, bytes) {
const els = _prepCtxViewerShell(rel);
if (!els) return;
@@ -1029,542 +1064,6 @@ function _showCtxBinaryViewer(rel, kind) {
els.actionsEl.querySelector('#ctx-viewer-del').addEventListener('click', _deleteCtxFromViewer);
}
-function _renderCtxViewerMd(bodyEl, actionsEl) {
- if (!_ctxActive) return;
- bodyEl = bodyEl || document.getElementById('contexts-viewer-body');
- actionsEl = actionsEl || document.getElementById('contexts-viewer-actions');
- const content = _ctxActive.content || '';
- bodyEl.innerHTML = `<div class="ctx-viewer-md markdown-body">${renderMarkdown(content)}</div>`;
- // After md render, walk the emitted `.task-item` checkboxes (renderMarkdown
- // emits them `disabled`) and wire them up to write back to the file. Order
- // of `.task-item` lis in DOM matches the order of `^(\s*)- \[( |x|X)\] `
- // lines in source by construction (renderMarkdown does not reorder).
- _ctxBindTaskCheckboxes(bodyEl);
- actionsEl.innerHTML = `
- <button class="btn btn-sm" id="ctx-viewer-edit">${escapeHtml(t('contexts.viewer.edit'))}</button>
- <button class="btn btn-sm" id="ctx-viewer-reveal">${escapeHtml(t('contexts.viewer.open_system'))}</button>
- <button class="btn btn-sm btn-danger" id="ctx-viewer-del">${escapeHtml(t('contexts.viewer.delete'))}</button>
- `;
- actionsEl.querySelector('#ctx-viewer-edit').addEventListener('click', _enterCtxEdit);
- actionsEl.querySelector('#ctx-viewer-reveal').addEventListener('click', () => revealCtxFile(_ctxActive.id));
- actionsEl.querySelector('#ctx-viewer-del').addEventListener('click', _deleteCtxFromViewer);
-}
-
-// Regex shared by checkbox-binding (preview side) and the editor's Todo
-// toolbar button. Captures: 1=indent, 2=mark ( /x/X), 3=rest of line.
-const _CTX_TODO_LINE_RE = /^(\s*)- \[( |x|X)\] (.*)$/;
-
-// Scan source content for task-list lines. Returns `[{ lineIdx, checked }, ...]`
-// in source order. The Nth entry corresponds to the Nth `.task-item` in the
-// rendered DOM (renderMarkdown preserves source order for list items).
-function _ctxScanTaskLines(content) {
- const lines = content.split('\n');
- const out = [];
- for (let i = 0; i < lines.length; i++) {
- const m = lines[i].match(_CTX_TODO_LINE_RE);
- if (m) out.push({ lineIdx: i, checked: m[2].toLowerCase() === 'x' });
- }
- return out;
-}
-
-function _ctxBindTaskCheckboxes(rootEl) {
- if (!rootEl || !_ctxActive) return;
- const tasks = _ctxScanTaskLines(_ctxActive.content || '');
- const boxes = rootEl.querySelectorAll('.task-item input[type="checkbox"]');
- // Defensive: if the two counts diverge (e.g., user has malformed markdown
- // that renderMarkdown rescued differently), bail out rather than mis-wire.
- if (boxes.length !== tasks.length) return;
- boxes.forEach((box, i) => {
- box.removeAttribute('disabled');
- const li = box.closest('li.task-item');
- if (tasks[i].checked && li) li.classList.add('is-done');
- box.addEventListener('change', () => _ctxToggleTask(tasks[i].lineIdx, li, box));
- });
-}
-
-async function _ctxToggleTask(lineIdx, liEl, boxEl) {
- if (!_ctxActive) return;
- const lines = (_ctxActive.content || '').split('\n');
- const m = (lines[lineIdx] || '').match(_CTX_TODO_LINE_RE);
- if (!m) return;
- const wasChecked = m[2].toLowerCase() === 'x';
- const nextMark = wasChecked ? ' ' : 'x';
- lines[lineIdx] = `${m[1]}- [${nextMark}] ${m[3]}`;
- const next = lines.join('\n');
- // Optimistic UI — flip the `is-done` style + the box state immediately;
- // revert if the save round-trip fails.
- if (liEl) liEl.classList.toggle('is-done', !wasChecked);
- if (boxEl) boxEl.checked = !wasChecked;
- try {
- const res = await apiFetch('/api/contexts/update', {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ path: _ctxActive.id, content: next }),
- });
- const data = await res.json();
- if (!data.ok) throw new Error(data.error || 'save_failed');
- _ctxActive.content = next;
- } catch (e) {
- if (liEl) liEl.classList.toggle('is-done', wasChecked);
- if (boxEl) boxEl.checked = wasChecked;
- await uiAlert(t('contexts.todo.save_failed', { reason: e.message || e }));
- }
-}
-
-// Editor mode = textarea + markdown toolbar; preview mode = renderMarkdown of
-// the current draft. The draft is only persisted to disk on Save — the
-// in-memory _ctxActive.content stays at the last-saved value, so Cancel can
-// revert without re-fetch.
-let _ctxEditPreview = false;
-let _ctxEditDraft = '';
-// Per-file in-progress edit state, keyed by relpath. Survives switching to
-// another KB file or to another sidebar tab — coming back to the file
-// restores edit mode + the unsaved draft instead of dropping to read mode.
-// Lifetime = renderer session (cleared on Save / Cancel / Delete; re-keyed
-// on Rename). Not persisted across app restarts.
-const _ctxDrafts = new Map();
-
-function _ctxStashDraft() {
- if (!_ctxActive) return;
- _ctxDrafts.set(_ctxActive.id, { content: _ctxEditDraft, isPreview: _ctxEditPreview });
-}
-
-function _ctxClearDraft(path) {
- const key = path || (_ctxActive && _ctxActive.id);
- if (key) _ctxDrafts.delete(key);
-}
-
-// Toolbar definition. `kind` keys map to `_ctxApplyMd()` cases; SVG icons
-// come from icons.js; `label` is the i18n key for the title tooltip.
-const _CTX_EDITOR_TOOLBAR = [
- { kind: 'h1', icon: 'H1', label: 'contexts.editor.tb.h1' },
- { kind: 'h2', icon: 'H2', label: 'contexts.editor.tb.h2' },
- { kind: 'h3', icon: 'H3', label: 'contexts.editor.tb.h3' },
- { kind: 'sep' },
- { kind: 'bold', icon: 'B', label: 'contexts.editor.tb.bold', cls: 'is-bold' },
- { kind: 'italic', icon: 'I', label: 'contexts.editor.tb.italic', cls: 'is-italic' },
- { kind: 'strike', icon: 'S', label: 'contexts.editor.tb.strike', cls: 'is-strike' },
- { kind: 'sep' },
- { kind: 'ul', iconName: 'list', label: 'contexts.editor.tb.ul' },
- { kind: 'ol', iconName: 'list-ordered', label: 'contexts.editor.tb.ol' },
- { kind: 'quote', iconName: 'quote', label: 'contexts.editor.tb.quote' },
- { kind: 'sep' },
- { kind: 'code', iconName: 'code', label: 'contexts.editor.tb.code' },
- { kind: 'codeblock', iconName: 'code-block', label: 'contexts.editor.tb.codeblock' },
- { kind: 'sep' },
- { kind: 'link', iconName: 'link', label: 'contexts.editor.tb.link' },
- { kind: 'image', iconName: 'image', label: 'contexts.editor.tb.image' },
- { kind: 'sep' },
- { kind: 'todo', iconName: 'square', label: 'contexts.editor.tb.todo' },
-];
-
-function _enterCtxEdit() {
- if (!_ctxActive) return;
- const draft = _ctxDrafts.get(_ctxActive.id);
- if (draft) {
- // Returning to a file we were editing — restore the unsaved draft +
- // whichever sub-mode (textarea vs preview) the user was in.
- _ctxEditPreview = !!draft.isPreview;
- _ctxEditDraft = draft.content || '';
- } else {
- _ctxEditPreview = false;
- _ctxEditDraft = _ctxActive.content || '';
- // Stash an empty-changes entry so "I clicked Edit but typed nothing"
- // also survives a file/tab switch — the user explicitly entered edit
- // mode and the round-trip back should land them right where they were.
- _ctxStashDraft();
- }
- _ctxRenderEditor();
-}
-
-function _ctxRenderEditor() {
- const bodyEl = document.getElementById('contexts-viewer-body');
- const actionsEl = document.getElementById('contexts-viewer-actions');
- if (!bodyEl || !actionsEl) return;
- const toolbarHtml = _CTX_EDITOR_TOOLBAR.map(item => {
- if (item.kind === 'sep') return `<span class="ctx-editor-toolbar-sep" aria-hidden="true"></span>`;
- const disabled = _ctxEditPreview ? 'disabled' : '';
- const extraCls = item.cls ? ` ${item.cls}` : '';
- const icon = item.iconName && typeof window !== 'undefined' && typeof window.uiIconHtml === 'function'
- ? window.uiIconHtml(item.iconName, 'ui-icon ctx-editor-svg-icon')
- : escapeHtml(item.icon || '');
- return `<button type="button" class="btn btn-sm btn-icon ctx-editor-tb-btn${extraCls}" data-kind="${item.kind}" title="${escapeHtml(t(item.label))}" ${disabled}>${icon}</button>`;
- }).join('');
- const toggleKey = _ctxEditPreview ? 'contexts.editor.tb.edit_back' : 'contexts.editor.tb.preview';
- const toggleIcon = typeof window !== 'undefined' && typeof window.uiIconHtml === 'function'
- ? window.uiIconHtml(_ctxEditPreview ? 'pencil' : 'eye', 'ui-icon ctx-editor-toggle-icon')
- : '';
- const draft = _ctxEditDraft;
- const bodyHtml = _ctxEditPreview
- ? `<div class="ctx-viewer-md markdown-body ctx-editor-preview">${draft.trim() ? renderMarkdown(draft) : `<div class="ctx-viewer-msg">${escapeHtml(t('contexts.editor.preview_empty'))}</div>`}</div>`
- : `<textarea class="ctx-viewer-editor" id="ctx-viewer-textarea" spellcheck="false">${escapeHtml(draft)}</textarea>`;
- bodyEl.innerHTML = `
- <div class="ctx-editor-toolbar" role="toolbar">
- ${toolbarHtml}
- <span class="ctx-editor-toolbar-spacer"></span>
- <button type="button" class="btn btn-sm ctx-editor-toggle" id="ctx-editor-toggle" title="${escapeHtml(t(toggleKey))}">${toggleIcon}<span>${escapeHtml(t(toggleKey))}</span></button>
- </div>
- <div class="ctx-editor-body">${bodyHtml}</div>
- `;
- actionsEl.innerHTML = `
- <button class="btn btn-sm btn-primary" id="ctx-viewer-save">${escapeHtml(t('contexts.viewer.save'))}</button>
- <button class="btn btn-sm" id="ctx-viewer-cancel">${escapeHtml(t('contexts.viewer.cancel'))}</button>
- `;
- actionsEl.querySelector('#ctx-viewer-save').addEventListener('click', _saveCtxEdit);
- actionsEl.querySelector('#ctx-viewer-cancel').addEventListener('click', () => {
- _ctxClearDraft();
- _ctxEditPreview = false;
- _ctxEditDraft = '';
- _renderCtxViewerMd();
- });
- bodyEl.querySelector('#ctx-editor-toggle').addEventListener('click', _ctxTogglePreview);
- bodyEl.querySelectorAll('.ctx-editor-tb-btn').forEach(btn => {
- btn.addEventListener('mousedown', (e) => {
- // Prevent the textarea from losing focus on click (otherwise the cursor
- // position is lost and the inserted snippet lands at the end).
- e.preventDefault();
- });
- btn.addEventListener('click', () => {
- if (_ctxEditPreview) return;
- const ta = document.getElementById('ctx-viewer-textarea');
- if (!ta) return;
- _ctxApplyMd(ta, btn.dataset.kind);
- });
- });
- const ta = bodyEl.querySelector('#ctx-viewer-textarea');
- if (ta) {
- ta.addEventListener('keydown', (e) => _ctxOnKey(ta, e));
- ta.addEventListener('input', () => { _ctxEditDraft = ta.value; _ctxStashDraft(); });
- ta.focus();
- }
-}
-
-function _ctxTogglePreview() {
- const ta = document.getElementById('ctx-viewer-textarea');
- if (ta) _ctxEditDraft = ta.value;
- _ctxEditPreview = !_ctxEditPreview;
- _ctxStashDraft();
- _ctxRenderEditor();
-}
-
-// Wrap-style ops toggle: if the selection is already wrapped with `mark`,
-// unwrap it; otherwise insert the wrap (with the placeholder pre-selected
-// when the selection is empty).
-function _ctxWrapSelection(ta, mark, placeholder) {
- const start = ta.selectionStart;
- let end = ta.selectionEnd;
- const value = ta.value;
- // Trailing-newline clamp: when a user "selects a line" (triple-click /
- // Shift+Down) the selection often includes the trailing `\n`. Wrapping
- // that range would emit `**Hello\n**`, leaving the closing mark stranded
- // on the next line.
- while (end > start && value[end - 1] === '\n') end -= 1;
- const sel = value.slice(start, end);
- const before = value.slice(0, start);
- const after = value.slice(end);
- const markLen = mark.length;
- // Unwrap if the selection itself is wrapped, OR if the wrap marks are
- // immediately around the selection.
- if (sel.startsWith(mark) && sel.endsWith(mark) && sel.length >= markLen * 2) {
- const inner = sel.slice(markLen, sel.length - markLen);
- _ctxReplaceRange(ta, start, end, inner, start, start + inner.length);
- return;
- }
- if (
- before.endsWith(mark) &&
- after.startsWith(mark)
- ) {
- const newStart = start - markLen;
- const newEnd = end + markLen;
- _ctxReplaceRange(ta, newStart, newEnd, sel, newStart, newStart + sel.length);
- return;
- }
- const inner = sel || placeholder;
- const wrapped = `${mark}${inner}${mark}`;
- // If the selection was empty, leave the caret in the middle so the
- // placeholder is selected — the next keystroke replaces it.
- const innerStart = start + markLen;
- const innerEnd = innerStart + inner.length;
- _ctxReplaceRange(ta, start, end, wrapped, innerStart, innerEnd);
-}
-
-// Compute the line span (lineStart..lineEnd) covered by the current selection.
-// **Trailing-newline clamp**: if the selection ends right after a `\n`, treat
-// the selection as ending at the position before that `\n`. Without this,
-// double-clicking / triple-clicking / Shift+Down to select a single line
-// (which on most platforms grabs the trailing newline too) makes
-// `indexOf('\n', selEnd)` find the NEXT line's terminator and the operation
-// silently affects the line below.
-function _ctxLineSpan(value, selStart, selEnd) {
- let effEnd = selEnd;
- if (effEnd > selStart && value[effEnd - 1] === '\n') effEnd -= 1;
- const lineStart = value.lastIndexOf('\n', selStart - 1) + 1;
- let lineEnd = value.indexOf('\n', effEnd);
- if (lineEnd === -1) lineEnd = value.length;
- return { lineStart, lineEnd };
-}
-
-// Heading op: replace any existing `^#+ ` prefix with the target level, or
-// strip the prefix entirely if every line is already at the target level.
-// Without this, applying H2 to a line that's already H1 would prepend a
-// second `## ` and produce `## # Hello`.
-function _ctxApplyHeading(ta, level) {
- const target = '#'.repeat(level) + ' ';
- const value = ta.value;
- const { lineStart, lineEnd } = _ctxLineSpan(value, ta.selectionStart, ta.selectionEnd);
- const block = value.slice(lineStart, lineEnd);
- const lines = block.split('\n');
- const stripHeading = (line) => line.replace(/^#{1,6} /, '');
- const isTarget = (line) => line === '' || line.startsWith(target);
- // Toggle: every line already at this level → strip headings entirely.
- if (lines.every(isTarget)) {
- const rebuilt = lines.map(stripHeading).join('\n');
- _ctxReplaceRange(ta, lineStart, lineEnd, rebuilt, lineStart, lineStart + rebuilt.length);
- return;
- }
- const rebuilt = lines.map(line => line === '' ? line : `${target}${stripHeading(line)}`).join('\n');
- _ctxReplaceRange(ta, lineStart, lineEnd, rebuilt, lineStart, lineStart + rebuilt.length);
-}
-
-// Todo three-state cycle (line-batch). The first non-empty selected line
-// decides the target state for the whole batch:
-// - `- [ ] foo` → `- [x] foo` (mark batch as done)
-// - `- [x] foo` → `foo` (strip todo prefix entirely)
-// - anything else → `- [ ] foo` (turn into a todo; first strips any
-// existing `- ` bullet so `- foo`
-// doesn't become `- [ ] - foo`)
-function _ctxApplyTodo(ta) {
- const value = ta.value;
- const { lineStart, lineEnd } = _ctxLineSpan(value, ta.selectionStart, ta.selectionEnd);
- const block = value.slice(lineStart, lineEnd);
- const lines = block.split('\n');
- const placeholder = t('contexts.editor.placeholder.todo');
- // Pick the mode from the first non-empty line.
- const firstNonEmpty = lines.find(l => l.trim().length > 0) || '';
- let mode;
- if (/^(\s*)- \[ \] /.test(firstNonEmpty)) mode = 'check';
- else if (/^(\s*)- \[[xX]\] /.test(firstNonEmpty)) mode = 'strip';
- else mode = 'mark';
- const rebuilt = lines.map(line => {
- if (line.trim().length === 0) return line;
- const indent = (line.match(/^(\s*)/) || ['', ''])[1];
- const rest = line.slice(indent.length);
- if (mode === 'check') {
- const m = rest.match(/^- \[ \] (.*)$/);
- return m ? `${indent}- [x] ${m[1]}` : line;
- }
- if (mode === 'strip') {
- return `${indent}${rest.replace(/^- \[[ xX]\] /, '')}`;
- }
- // mode === 'mark': turn the line into a todo. Drop any existing bullet
- // prefix (`- ` / `* ` / `+ ` / `1. `) so we don't double up.
- const body = rest.replace(/^([-*+]|\d+\.) +/, '') || placeholder;
- return `${indent}- [ ] ${body}`;
- }).join('\n');
- _ctxReplaceRange(ta, lineStart, lineEnd, rebuilt, lineStart, lineStart + rebuilt.length);
-}
-
-// Line-prefix ops: apply `prefix(idx)` to each selected line (or the caret
-// line); toggle off if every line already carries the same prefix.
-function _ctxLinePrefix(ta, prefixFn) {
- const value = ta.value;
- const { lineStart, lineEnd } = _ctxLineSpan(value, ta.selectionStart, ta.selectionEnd);
- const block = value.slice(lineStart, lineEnd);
- const lines = block.split('\n');
- // Toggle: if every non-empty line starts with the prefix (idx 0), strip it.
- const firstPrefix = prefixFn(0);
- const allMatch = lines.every(line => line.length === 0 || line.startsWith(firstPrefix));
- let rebuilt;
- if (allMatch && firstPrefix) {
- rebuilt = lines.map(line => line.startsWith(firstPrefix) ? line.slice(firstPrefix.length) : line).join('\n');
- } else {
- rebuilt = lines.map((line, idx) => `${prefixFn(idx)}${line}`).join('\n');
- }
- _ctxReplaceRange(ta, lineStart, lineEnd, rebuilt, lineStart, lineStart + rebuilt.length);
-}
-
-// Drop-in block insert (codeblock / link / image).
-function _ctxInsertBlock(ta, opts) {
- const { text, selStart, selEnd } = opts;
- const start = ta.selectionStart;
- const end = ta.selectionEnd;
- _ctxReplaceRange(ta, start, end, text, start + selStart, start + selEnd);
-}
-
-function _ctxReplaceRange(ta, from, to, replacement, newSelStart, newSelEnd) {
- ta.setRangeText(replacement, from, to, 'preserve');
- ta.selectionStart = newSelStart;
- ta.selectionEnd = newSelEnd;
- _ctxEditDraft = ta.value;
- // setRangeText doesn't fire `input`, so toolbar ops bypass the input
- // handler's draft stash — capture explicitly.
- _ctxStashDraft();
- ta.focus();
-}
-
-function _ctxApplyMd(ta, kind) {
- switch (kind) {
- case 'bold': return _ctxWrapSelection(ta, '**', t('contexts.editor.placeholder.bold'));
- case 'italic': return _ctxWrapSelection(ta, '*', t('contexts.editor.placeholder.italic'));
- case 'strike': return _ctxWrapSelection(ta, '~~', t('contexts.editor.placeholder.strike'));
- case 'code': return _ctxWrapSelection(ta, '`', t('contexts.editor.placeholder.code'));
- case 'h1': return _ctxApplyHeading(ta, 1);
- case 'h2': return _ctxApplyHeading(ta, 2);
- case 'h3': return _ctxApplyHeading(ta, 3);
- case 'quote': return _ctxLinePrefix(ta, () => '> ');
- case 'ul': return _ctxLinePrefix(ta, () => '- ');
- case 'ol': return _ctxLinePrefix(ta, (i) => `${i + 1}. `);
- case 'todo': return _ctxApplyTodo(ta);
- case 'codeblock': {
- const start = ta.selectionStart, end = ta.selectionEnd;
- const sel = ta.value.slice(start, end);
- const body = sel || t('contexts.editor.placeholder.code');
- // Ensure surrounding blank lines when the caret is mid-paragraph.
- const before = ta.value.slice(0, start);
- const after = ta.value.slice(end);
- const leadNl = before.length === 0 || before.endsWith('\n\n') ? '' : (before.endsWith('\n') ? '\n' : '\n\n');
- const tailNl = after.length === 0 || after.startsWith('\n\n') ? '' : (after.startsWith('\n') ? '\n' : '\n\n');
- const text = `${leadNl}\`\`\`\n${body}\n\`\`\`${tailNl}`;
- const innerStart = start + leadNl.length + 4; // after ```\n
- const innerEnd = innerStart + body.length;
- return _ctxInsertBlock(ta, { text, selStart: innerStart - start, selEnd: innerEnd - start });
- }
- case 'link': {
- const start = ta.selectionStart, end = ta.selectionEnd;
- const sel = ta.value.slice(start, end);
- const linkText = sel || t('contexts.editor.placeholder.link_text');
- const url = t('contexts.editor.placeholder.link_url');
- const text = `[${linkText}](${url})`;
- // Select the URL placeholder so the user can paste / type their URL.
- const urlStart = 1 + linkText.length + 2; // after "[text]("
- const urlEnd = urlStart + url.length;
- return _ctxInsertBlock(ta, { text, selStart: urlStart, selEnd: urlEnd });
- }
- case 'image': {
- const start = ta.selectionStart, end = ta.selectionEnd;
- const sel = ta.value.slice(start, end);
- const alt = sel || t('contexts.editor.placeholder.image_alt');
- const url = t('contexts.editor.placeholder.image_url');
- const text = `![${alt}](${url})`;
- const urlStart = 2 + alt.length + 2;
- const urlEnd = urlStart + url.length;
- return _ctxInsertBlock(ta, { text, selStart: urlStart, selEnd: urlEnd });
- }
- }
-}
-
-// Strip a leading list/quote marker; return null if the line isn't a list line.
-function _ctxParseListPrefix(line) {
- const m = line.match(/^(\s*)([-*+]|\d+\.)(\s+)/);
- if (!m) return null;
- return { indent: m[1], marker: m[2], gap: m[3], total: m[0] };
-}
-
-function _ctxOnKey(ta, e) {
- // IME composition guard (CLAUDE.md §8) — Chinese / Japanese / Korean Enter
- // commits a candidate; don't fire shortcuts or list-continuation while a
- // composition is active.
- if (e.isComposing || e.keyCode === 229) return;
-
- const mod = e.metaKey || e.ctrlKey;
- if (mod && !e.shiftKey && !e.altKey) {
- const k = (e.key || '').toLowerCase();
- if (k === 'b') { e.preventDefault(); return _ctxApplyMd(ta, 'bold'); }
- if (k === 'i') { e.preventDefault(); return _ctxApplyMd(ta, 'italic'); }
- if (k === 'k') { e.preventDefault(); return _ctxApplyMd(ta, 'link'); }
- if (k === 's') { e.preventDefault(); return _saveCtxEdit(); }
- }
-
- if (e.key === 'Tab') {
- e.preventDefault();
- const start = ta.selectionStart;
- const end = ta.selectionEnd;
- const value = ta.value;
- const multiLine = value.slice(start, end).includes('\n');
- if (multiLine) {
- // Use the same trailing-newline-clamped span as the toolbar line ops,
- // so selecting "row1\nrow2\n" doesn't drag row3's leading column into
- // the indent batch.
- const { lineStart, lineEnd } = _ctxLineSpan(value, start, end);
- const block = value.slice(lineStart, lineEnd);
- const lines = block.split('\n');
- let rebuilt;
- if (e.shiftKey) {
- rebuilt = lines.map(l => l.replace(/^( {1,2}|\t)/, '')).join('\n');
- } else {
- rebuilt = lines.map(l => ` ${l}`).join('\n');
- }
- _ctxReplaceRange(ta, lineStart, lineEnd, rebuilt, lineStart, lineStart + rebuilt.length);
- return;
- }
- if (e.shiftKey) {
- const lineStart = value.lastIndexOf('\n', start - 1) + 1;
- const head = value.slice(lineStart, lineStart + 2);
- const strip = head === ' ' ? 2 : (head[0] === '\t' ? 1 : 0);
- if (strip) {
- const newStart = Math.max(lineStart, start - strip);
- _ctxReplaceRange(ta, lineStart, lineStart + strip, '', newStart, Math.max(newStart, end - strip));
- }
- return;
- }
- _ctxReplaceRange(ta, start, end, ' ', start + 2, start + 2);
- return;
- }
-
- if (e.key === 'Enter') {
- const value = ta.value;
- const start = ta.selectionStart;
- const end = ta.selectionEnd;
- if (start !== end) return; // non-empty selection: default behavior (replace)
- const lineStart = value.lastIndexOf('\n', start - 1) + 1;
- const lineSoFar = value.slice(lineStart, start);
- const parsed = _ctxParseListPrefix(lineSoFar);
- if (!parsed) return;
- // Empty list line → break out (remove the marker entirely).
- if (lineSoFar === parsed.total) {
- e.preventDefault();
- _ctxReplaceRange(ta, lineStart, start, '', lineStart, lineStart);
- return;
- }
- e.preventDefault();
- let nextMarker = parsed.marker;
- if (/^\d+\.$/.test(parsed.marker)) {
- const n = parseInt(parsed.marker, 10);
- nextMarker = `${n + 1}.`;
- }
- const insert = `\n${parsed.indent}${nextMarker}${parsed.gap}`;
- _ctxReplaceRange(ta, start, start, insert, start + insert.length, start + insert.length);
- return;
- }
-}
-
-async function _saveCtxEdit() {
- if (!_ctxActive) return;
- const ta = document.getElementById('ctx-viewer-textarea');
- // Textarea is only present in edit mode; preview mode saves from the draft
- // captured at the toggle point. Always sync the textarea value into the
- // draft first so the two paths converge.
- if (ta) _ctxEditDraft = ta.value;
- const next = _ctxEditDraft;
- try {
- const res = await apiFetch('/api/contexts/update', {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ path: _ctxActive.id, content: next }),
- });
- const data = await res.json();
- if (!data.ok) { await uiAlert(data.error || t('contexts.save_failed')); return; }
- _ctxActive.content = next;
- _ctxClearDraft();
- _ctxEditPreview = false;
- _ctxEditDraft = '';
- _renderCtxViewerMd();
- await loadContexts();
- } catch (e) {
- await uiAlert(t('contexts.save_failed_with', { reason: e.message || e }));
- }
-}
-
async function _deleteCtxFromViewer() {
if (!_ctxActive) return;
const rel = _ctxActive.id;
@@ -1582,6 +1081,7 @@ async function _deleteCtxFromViewer() {
}
function _clearCtxViewer() {
+ if (_ctxMveController) { try { _ctxMveController.destroy(); } catch (_) {} _ctxMveController = null; }
_ctxActive = null;
const empty = document.getElementById('contexts-editor-empty');
const wrap = document.getElementById('contexts-viewer-wrap');
diff --git a/src/renderer/modules/conversation-info.js b/src/renderer/modules/conversation-info.js
index b8eb0050..54e37e7e 100644
--- a/src/renderer/modules/conversation-info.js
+++ b/src/renderer/modules/conversation-info.js
@@ -328,7 +328,6 @@ const ConversationInfo = (() => {
const dirHtml = dirs.map(([name, child]) => `
<details class="conversation-info-dir" style="--depth:${depth}" open>
<summary class="conversation-info-dir-summary">
- <span class="conversation-info-dir-icon">▸</span>
<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>
<span class="conversation-info-dir-name">${escapeHtml(name)}</span>
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index 021b68bc..67242b37 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -77,16 +77,59 @@ function _highlightMentionsIn(rootEl) {
}
}
+function _skillsForDisplayNameRewrite() {
+ return (typeof _skillsCache !== 'undefined' && Array.isArray(_skillsCache)) ? _skillsCache : [];
+}
+
+function _htmlMayContainKnownSkillIdForDisplay(html, skills) {
+ if (!html || !Array.isArray(skills) || !skills.length) return false;
+ return skills.some((s) => {
+ const id = typeof s?.id === 'string' ? s.id : '';
+ const name = typeof s?.name === 'string' ? s.name : '';
+ return id && name && id !== name && html.indexOf(id) >= 0;
+ });
+}
+
+function _replaceKnownSkillIdsIn(rootEl, skills) {
+ if (!rootEl || typeof _replaceKnownSkillIdsForDisplay !== 'function') return;
+ if (!Array.isArray(skills) || !skills.length) return;
+ const walker = document.createTreeWalker(rootEl, NodeFilter.SHOW_TEXT, {
+ acceptNode(node) {
+ let p = node.parentNode;
+ while (p && p !== rootEl) {
+ if (p.tagName && _MENTION_SKIP.has(p.tagName)) return NodeFilter.FILTER_REJECT;
+ p = p.parentNode;
+ }
+ const text = node.nodeValue || '';
+ return _replaceKnownSkillIdsForDisplay(text, skills) !== text
+ ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
+ },
+ });
+ const targets = [];
+ let n;
+ while ((n = walker.nextNode())) targets.push(n);
+ for (const node of targets) {
+ node.nodeValue = _replaceKnownSkillIdsForDisplay(node.nodeValue || '', skills);
+ }
+}
+
// Wrap `renderMarkdownFull` so every chat-bubble render passes through the
// mention highlighter. Same signature as the underlying function so call
// sites just swap.
function _renderMessageMarkdown(text) {
- const html = renderMarkdownFull(String(text || ''));
+ const skills = _skillsForDisplayNameRewrite();
+ const raw = String(text || '');
+ const displayText = (skills.length && typeof _simplifyKnownSkillFollowPhrasesForDisplay === 'function')
+ ? _simplifyKnownSkillFollowPhrasesForDisplay(raw, skills)
+ : raw;
+ const html = renderMarkdownFull(displayText);
+ const needsSkillRewrite = _htmlMayContainKnownSkillIdForDisplay(html, skills);
// Mention highlighting requires DOM walking — do it on a detached
// container, then return its innerHTML for the bubble to embed.
- if (!html || html.indexOf('@') < 0) return html;
+ if (!html || (html.indexOf('@') < 0 && !needsSkillRewrite)) return html;
const tmp = document.createElement('div');
tmp.innerHTML = html;
+ if (needsSkillRewrite) _replaceKnownSkillIdsIn(tmp, skills);
_highlightMentionsIn(tmp);
return tmp.innerHTML;
}
@@ -167,11 +210,50 @@ function _initAllMentionMirrors() {
const newChatInput = document.getElementById('new-chat-input');
if (newChatInput) _initMentionMirror(newChatInput);
}
+
+const CHAT_INPUT_RESERVE_FALLBACK = 140;
+let _chatInputReserveLast = 0;
+let _chatInputReserveObserver = null;
+function _updateChatInputReserve() {
+ const pane = document.querySelector('#panel-conversation .chat-main-pane')
+ || document.querySelector('#panel-conversation .chat-container');
+ const wrap = document.querySelector('#panel-conversation .chat-input-wrapper');
+ if (!pane || !wrap) return;
+ const measured = Math.ceil(wrap.offsetHeight || 0);
+ const reserve = Math.max(CHAT_INPUT_RESERVE_FALLBACK, measured);
+ if (reserve === _chatInputReserveLast) return;
+ _chatInputReserveLast = reserve;
+ pane.style.setProperty('--chat-input-reserve', `${reserve}px`);
+
+ const history = document.getElementById('chat-history');
+ requestAnimationFrame(() => {
+ if (!history || !history.isConnected) return;
+ if (history.querySelector(':scope > .chat-scroll-spacer')) _setChatScrollOffset(true, history);
+ if (history._stickyEnabled === true) _stickBottomIfPinned(history);
+ });
+}
+
+function _initChatInputReserveObserver() {
+ const wrap = document.querySelector('#panel-conversation .chat-input-wrapper');
+ if (!wrap || wrap.dataset.reserveObserver === '1') return;
+ wrap.dataset.reserveObserver = '1';
+ _updateChatInputReserve();
+ if (typeof ResizeObserver === 'function') {
+ _chatInputReserveObserver = new ResizeObserver(() => _updateChatInputReserve());
+ _chatInputReserveObserver.observe(wrap);
+ }
+ window.addEventListener('resize', _updateChatInputReserve);
+}
+
if (typeof window !== 'undefined') {
if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', _initAllMentionMirrors, { once: true });
+ document.addEventListener('DOMContentLoaded', () => {
+ _initAllMentionMirrors();
+ _initChatInputReserveObserver();
+ }, { once: true });
} else {
_initAllMentionMirrors();
+ _initChatInputReserveObserver();
}
}
@@ -358,6 +440,7 @@ function onEnterConversationView() {
// doesn't bleed into this one (and a quote left in this conv reappears
// when the user navigates back).
_renderQuotePreview();
+ _updateChatInputReserve();
}
// Called by queue-draft.js::_forgetConvLocal when a conv is deleted so we
@@ -398,10 +481,111 @@ function _forgetCidRecipient(cid) {
// terminal step's assignee wins when no live step is running".
const _autoEvalInflight = new Set(); // cid set
const _latestInFlight = new Map(); // cid → string[] (mirrors state_changed.state.in_flight)
+const _runtimeRecoveryTimers = new Map(); // cid → timeout id
// 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();
+
+function _stopRuntimeActorRecovery(cid) {
+ const timer = _runtimeRecoveryTimers.get(cid);
+ if (timer) clearTimeout(timer);
+ _runtimeRecoveryTimers.delete(cid);
+}
+
+async function _syncPendingActorsFromRuntime(cid) {
+ if (!cid || !isConvPending(cid)) return false;
+ const state = pendingConvs.get(cid);
+ if (!state || state.aborted) return false;
+ // Runtime polling is recovery for renderer reload / lost local controller
+ // cases. A live send-stream controller is already the authoritative event
+ // source; letting this path finish it can manufacture empty loading bubbles
+ // or clear pending in the middle of a plan handoff.
+ if (state.controller) return false;
+ const loadingEl = state.loadingEl;
+ let data = null;
+ try {
+ const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/runtime`);
+ data = await res.json();
+ } catch (_) {
+ return false;
+ }
+ if (!data || data.ok === false) return false;
+ if (!isConvPending(cid) || pendingConvs.get(cid)?.aborted) return false;
+ const inFlight = Array.isArray(data.in_flight)
+ ? data.in_flight.filter(Boolean).map(String)
+ : [];
+ const processing = data.processing === true || inFlight.length > 0;
+ if (window.PlanRail) {
+ try {
+ window.PlanRail.setInFlight(cid, inFlight);
+ window.PlanRail.refresh(cid, { force: true });
+ } catch (_) {}
+ }
+ if (window.ConversationInfo) {
+ try { window.ConversationInfo.refresh(cid, { silent: true }); } catch (_) {}
+ }
+ if (!processing) {
+ _latestInFlight.set(cid, []);
+ setGroupConversationBusy(cid, false);
+ _updateConvSidebarBadge(cid, false);
+ if (cid === currentCid) {
+ _scheduleHistoryReconcileAfterStream(cid, { force: true });
+ _settleDanglingActorPlaceholders(cid);
+ if (loadingEl && loadingEl.parentElement) _removeEmptyStreamingPlaceholder(loadingEl);
+ _updateConvSendUI(cid);
+ }
+ _finishStreamingMsg(cid);
+ return true;
+ }
+
+ setGroupConversationBusy(cid, true);
+ _latestInFlight.set(cid, inFlight);
+ _updateConvSidebarBadge(cid, true);
+ startPolling(cid);
+ if (cid === currentCid) _updateConvSendUI(cid);
+ if (!inFlight.length) return false;
+
+ // Names/avatars are local data; warm members before revealing so the
+ // placeholder does not flash as an unknown agent.
+ try { await _refreshGroupMembers(cid); } catch (_) { /* best effort */ }
+ if (!isConvPending(cid) || pendingConvs.get(cid)?.aborted) return false;
+ if (cid !== currentCid) return true;
+ for (const actorId of inFlight) {
+ _ensureActorPlaceholder(cid, actorId, loadingEl);
+ }
+ return true;
+}
+
+function _startRuntimeActorRecovery(cid) {
+ if (!cid) return;
+ _stopRuntimeActorRecovery(cid);
+ let attempts = 0;
+ const tick = async () => {
+ attempts += 1;
+ if (!isConvPending(cid) || pendingConvs.get(cid)?.aborted) {
+ _stopRuntimeActorRecovery(cid);
+ return;
+ }
+ const recovered = await _syncPendingActorsFromRuntime(cid);
+ if (!isConvPending(cid) || pendingConvs.get(cid)?.aborted) {
+ _stopRuntimeActorRecovery(cid);
+ return;
+ }
+ // Keep this alive for genuinely long plan steps. The timer is tied to
+ // pending state and stops as soon as the controller / runtime settles;
+ // capping at two minutes stranded long agent runs with a permanent
+ // loading bubble after their final message landed on disk.
+ if (attempts >= 1800) {
+ _stopRuntimeActorRecovery(cid);
+ return;
+ }
+ const delay = recovered ? 1000 : (attempts < 4 ? 250 : 1000);
+ _runtimeRecoveryTimers.set(cid, setTimeout(tick, delay));
+ };
+ _runtimeRecoveryTimers.set(cid, setTimeout(tick, 150));
+}
+
async function _evaluateAutoRecipient(cid) {
if (!cid || cid !== currentCid) return;
if (_autoEvalInflight.has(cid)) return;
@@ -596,6 +780,81 @@ function setCommanderAvatarCache(avatar) {
_commanderAvatarCache = { icon: avatar.icon, color: avatar.color };
}
}
+function _isAgentActor(fromId) {
+ return !!fromId && !GROUP_RESERVED.has(String(fromId));
+}
+
+function _actorLinkAttrs(fromId) {
+ return _isAgentActor(fromId)
+ ? ` data-actor-agent-id="${escapeHtml(String(fromId))}" role="button" tabindex="0"`
+ : '';
+}
+
+async function _openActorAgentDetail(actorId) {
+ const aid = String(actorId || '').trim();
+ if (!_isAgentActor(aid)) return;
+ setView('agents');
+ try {
+ const res = await apiFetch(`/api/agents/${encodeURIComponent(aid)}`);
+ const data = await res.json();
+ if (!data?.ok || !data?.agent) return;
+ } catch (err) {
+ _convLog.warn('open message actor failed', { agent_id: aid, error: String(err && err.message || err) });
+ return;
+ }
+ if (typeof _showAgentsDetailView === 'function') await _showAgentsDetailView(aid);
+ else if (typeof selectAgent === 'function') await selectAgent(aid);
+}
+
+function _hydrateActorHeaderLinks(root) {
+ if (!root) return;
+ const links = root.querySelectorAll('[data-actor-agent-id]');
+ for (const el of links) {
+ if (el.dataset.actorLinkBound === '1') continue;
+ el.dataset.actorLinkBound = '1';
+ if (!el.hasAttribute('role')) el.setAttribute('role', 'button');
+ if (!el.hasAttribute('tabindex')) el.setAttribute('tabindex', '0');
+ el.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _openActorAgentDetail(el.dataset.actorAgentId);
+ });
+ el.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key !== 'Enter' && e.key !== ' ') return;
+ e.preventDefault();
+ e.stopPropagation();
+ _openActorAgentDetail(el.dataset.actorAgentId);
+ });
+ }
+}
+
+function _decorateActorHeader(root, actorId) {
+ if (!root) return;
+ const aid = String(actorId || '');
+ const linkable = _isAgentActor(aid);
+ const targets = [
+ root.querySelector('.chat-msg-header .chat-msg-from'),
+ root.querySelector('.chat-msg-header .avatar-circle'),
+ ].filter(Boolean);
+ for (const el of targets) {
+ if (linkable) {
+ el.dataset.actorAgentId = aid;
+ el.classList.add('is-agent-link');
+ if (el.classList.contains('avatar-circle')) el.classList.add('is-clickable');
+ el.setAttribute('role', 'button');
+ el.setAttribute('tabindex', '0');
+ } else {
+ delete el.dataset.actorAgentId;
+ el.classList.remove('is-agent-link');
+ if (el.classList.contains('avatar-circle')) el.classList.remove('is-clickable');
+ el.removeAttribute('role');
+ el.removeAttribute('tabindex');
+ delete el.dataset.actorLinkBound;
+ }
+ }
+ if (linkable) _hydrateActorHeaderLinks(root);
+}
+
/** Render the message row avatar. `fromId` is known to be non-'user'. */
function _renderActorAvatarHtml(fromId) {
if (fromId === 'commander') {
@@ -619,7 +878,12 @@ function _renderActorAvatarHtml(fromId) {
if (m) { icon = icon || m.icon; color = color || m.color; }
}
}
- return renderAvatarHtml(icon, color, { size: 28, seed: fromId || 'agent' });
+ return renderAvatarHtml(icon, color, {
+ size: 28,
+ seed: fromId || 'agent',
+ clickable: _isAgentActor(fromId),
+ dataAttrs: _isAgentActor(fromId) ? { 'actor-agent-id': String(fromId) } : {},
+ });
}
/** Resolve an actor id (commander / user / agent_id) to a human-readable
* display name. **Never returns the raw agent_id** — UI shouldn't expose
@@ -1114,8 +1378,18 @@ function _hydrateMessageProducedChips(msgDiv) {
e.stopPropagation();
const p = chip.dataset.producedPath;
if (!p) return;
- // chat-file-viewer dispatches by extension to in-app preview overlay
- // or, on unsupported kinds, an "open folder?" fallback dialog.
+ // 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);
@@ -1124,6 +1398,12 @@ function _hydrateMessageProducedChips(msgDiv) {
});
}
+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
@@ -1515,9 +1795,13 @@ async function loadConversationHistory(cid) {
const processingFresh = convMeta.processing === true
&& convMeta.processing_since
&& (Date.now() - new Date(convMeta.processing_since).getTime()) < 15 * 60 * 1000;
+ const inFlightActors = Array.isArray(convMeta.in_flight)
+ ? convMeta.in_flight.filter(Boolean).map(String)
+ : [];
const wasPendingBeforeHistoryRecovery = isConvPending(cid);
if (processingFresh && !wasPendingBeforeHistoryRecovery) {
setGroupConversationBusy(cid, true);
+ _latestInFlight.set(cid, inFlightActors);
_updateConvSidebarBadge(cid, true);
startPolling(cid);
if (cid === currentCid) _updateConvSendUI(cid);
@@ -1526,6 +1810,14 @@ async function loadConversationHistory(cid) {
pollMsgCounts.set(cid, history.length);
const loadingEl = _createStreamingAssistantMessage(container, { hiddenUntilActor: true });
pendingConvs.set(cid, { loadingEl, needsIndicator: false });
+ for (const actorId of inFlightActors) {
+ _ensureActorPlaceholder(cid, actorId, loadingEl);
+ }
+ // Opening/reloading into an already-running plan still needs the
+ // group event stream; runtime polling can recover placeholders, but
+ // it cannot replay live text deltas.
+ _observeConversationRunFromPlanAction(cid, { attachExisting: true });
+ _startRuntimeActorRecovery(cid);
_updateConvSendUI(cid);
} else if (isConvPending(cid)) {
// User navigated away and back during an in-flight request. The stream
@@ -1549,6 +1841,16 @@ async function loadConversationHistory(cid) {
const loadingEl = _createStreamingAssistantMessage(container, { hiddenUntilActor: true });
state.loadingEl = loadingEl;
}
+ for (const actorId of inFlightActors) {
+ _ensureActorPlaceholder(cid, actorId, state.loadingEl);
+ }
+ if (!state.controller) {
+ // Same recovery path for a detached pending state: reconnect to the
+ // live group event stream so the bubble streams instead of waiting
+ // for the final history reconcile.
+ _observeConversationRunFromPlanAction(cid, { attachExisting: true });
+ _startRuntimeActorRecovery(cid);
+ }
state.needsIndicator = false;
startPolling(cid); // ensure polling is running as backup
}
@@ -1565,6 +1867,102 @@ async function loadConversationHistory(cid) {
}
}
+function _messageRecordHasMountedSidecars(gm, el, opts = {}) {
+ if (!gm || !el) return true;
+ if (gm.form && !el.querySelector('.chat-input-form')) return false;
+ if (opts.checkMutableState !== false
+ && gm.form?.submitted
+ && !el.querySelector('.chat-input-form.is-submitted')) return false;
+ if (gm.plan_announcement && !el.querySelector('.chat-plan-announce')) return false;
+ if (Array.isArray(gm.produced) && gm.produced.length && !el.querySelector('.chat-msg-produced')) return false;
+ if ((_normalizeCreatedAgents(gm) || _normalizeCreatedSkills(gm)) && !el.querySelector('.chat-msg-created-agent-chip')) return false;
+ if (Array.isArray(gm.artifacts) && gm.artifacts.length && !el.querySelector('.chat-artifact-host')) return false;
+ if (Array.isArray(gm.marketplace_requests) && gm.marketplace_requests.length && !el.querySelector('.chat-marketplace-request')) return false;
+ if (Array.isArray(gm.process) && gm.process.length && !el.querySelector('.stream-process')) return false;
+ return true;
+}
+
+function _scheduleHistoryReconcileAfterStream(cid, opts = {}) {
+ if (!cid) return;
+ setTimeout(async () => {
+ if (cid !== currentCid || (!opts.force && isConvPending(cid))) return;
+ const container = document.getElementById('chat-history');
+ if (!container) return;
+ try {
+ const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/history?limit=500`);
+ const data = await res.json();
+ if (!data.ok || !Array.isArray(data.history)) return;
+ const visible = data.history.filter((gm) => !(gm && gm.dispatch));
+ for (const gm of visible.slice(-8)) {
+ if (!gm || !gm.id) continue;
+ const el = container.querySelector(`.chat-message[data-msg-id="${CSS.escape(String(gm.id))}"]`);
+ if (!el || !_messageRecordHasMountedSidecars(gm, el)) {
+ loadConversationHistory(cid);
+ return;
+ }
+ }
+ } catch (_) { /* history reconcile is a best-effort UI repair */ }
+ }, 80);
+}
+
+async function _recoverPolledVisibleMessages(cid, rawMessages) {
+ if (!cid || cid !== currentCid || !Array.isArray(rawMessages)) return false;
+ const container = document.getElementById('chat-history');
+ if (!container) return false;
+ let changed = false;
+ try { await _refreshGroupMembers(cid); } catch (_) { /* best effort */ }
+ const visible = rawMessages.filter((gm) => gm && !gm.dispatch && gm.from !== 'user');
+ for (const gm of visible) {
+ if (!gm.id) continue;
+ const existing = container.querySelector(`.chat-message[data-msg-id="${CSS.escape(String(gm.id))}"]`);
+ if (existing) {
+ if (!_messageRecordHasMountedSidecars(gm, existing, { checkMutableState: false })) {
+ loadConversationHistory(cid);
+ return true;
+ }
+ continue;
+ }
+ const ph = _consumeActorPlaceholder(cid, String(gm.from || ''));
+ if (ph && ph.parentElement) {
+ _finalizeActorPlaceholder(ph, gm, cid, true);
+ changed = true;
+ continue;
+ }
+ const legacy = _groupMsgToLegacy(gm);
+ const bubble = appendChatMessage(legacy, true, { cid, archive: true });
+ if (bubble) bubble.dataset.fromActor = String(gm.from || '');
+ changed = true;
+ }
+ if (changed) {
+ try { if (window.PlanRail) window.PlanRail.refresh(cid, { force: true }); } catch (_) {}
+ try { if (window.ConversationInfo) window.ConversationInfo.refresh(cid); } catch (_) {}
+ }
+ return changed;
+}
+
+function _claimPersistedUserMessage(cid, gm) {
+ if (!cid || cid !== currentCid || !gm || gm.from !== 'user' || !gm.id) return false;
+ const container = document.getElementById('chat-history');
+ if (!container) return false;
+ const existing = container.querySelector(`.chat-message[data-msg-id="${CSS.escape(String(gm.id))}"]`);
+ if (existing) return true;
+
+ const pairCandidates = Array.from(
+ container.querySelectorAll('.chat-message.user[data-conv-pair="1"]:not([data-msg-id])'),
+ );
+ const fallbackCandidates = Array.from(
+ container.querySelectorAll('.chat-message.user:not([data-msg-id])'),
+ );
+ const target = pairCandidates[pairCandidates.length - 1]
+ || fallbackCandidates[fallbackCandidates.length - 1];
+ if (!target) return false;
+
+ target.dataset.msgId = String(gm.id);
+ target.dataset.fromActor = 'user';
+ if (gm.ts) target.dataset.ts = String(_msTs(gm.ts));
+ return true;
+}
+
// Jump to bottom without smooth animation. Use when opening a conversation —
// the last message should appear immediately, no scrolling effect.
function _scrollToBottomNoAnim(container) {
@@ -1698,11 +2096,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
// `_stripSurvivingStructuralBlocks` in strip-structural-blocks.js).
let displayContent = rawContent;
if (!isHtmlSnippet) {
- if (role === 'user') {
- displayContent = _stripMarketplaceInstallResultTagForDisplay(
- _stripArtifactResultTagForDisplay(_stripSubmissionTagForDisplay(rawContent)),
- );
- }
+ if (role === 'user') displayContent = _stripUserStructuralBlocksForDisplay(rawContent);
else if (role === 'assistant') displayContent = _stripSurvivingStructuralBlocks(rawContent);
}
const contentHtml = isHtmlSnippet
@@ -1737,10 +2131,11 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
: _groupActorLabel(message._from || (message._from_label ? '' : ''))
|| message._from_label
|| (t('chat.from_agent_unknown'));
- const avatarHtml = role === 'user' ? '' : _renderActorAvatarHtml(message._from);
+ const headerActorId = role === 'user' ? '' : String(message._from || '');
+ const avatarHtml = role === 'user' ? '' : _renderActorAvatarHtml(headerActorId);
const headerHtml = role === 'user'
? `<div class="chat-msg-header chat-msg-header-user"><span class="chat-msg-time">${formatTime(message.time || new Date().toISOString())}</span></div>`
- : `<div class="chat-msg-header">${avatarHtml}<span class="chat-msg-from">${escapeHtml(headerName)}</span><span class="chat-msg-time">${formatTime(message.time || new Date().toISOString())}</span></div>`;
+ : `<div class="chat-msg-header">${avatarHtml}<span class="chat-msg-from${_isAgentActor(headerActorId) ? ' is-agent-link' : ''}"${_actorLinkAttrs(headerActorId)}>${escapeHtml(headerName)}</span><span class="chat-msg-time">${formatTime(message.time || new Date().toISOString())}</span></div>`;
const planAnnHtml = message._plan_announcement
? `<div class="chat-plan-announce">${_uiIconHtml('clipboard-list', 'ui-icon chat-plan-announce-icon')}<span>${escapeHtml(t('chat.plan_announce'))}</span></div>` : '';
// Below-bubble action row holds produced-file chips + created-agent chip
@@ -1770,6 +2165,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
}
if (attachmentsHtml) _hydrateMessageAttachmentThumbs(msgDiv, opts.cid || currentCid);
if (producedHtml) _hydrateMessageProducedChips(msgDiv);
+ _hydrateActorHeaderLinks(msgDiv);
if (createdAgentHtml) _hydrateMessageCreatedAgentChip(msgDiv);
if (createdSkillHtml) _hydrateMessageCreatedSkillChip(msgDiv);
// Interactive input-form widget (assistant messages only). Appended inside
@@ -1831,8 +2227,10 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
// Mount the input-form widget into a bubble. Wires the widget's submit
// callback to (a) flag the assistant form as submitted server-side and
-// (b) fire the composed user message through the normal send pipeline,
-// so conversation state stays consistent regardless of scene.
+// (b) fire the composed user message through the normal send-stream pipeline.
+// That IPC handler subscribes to the group bus before enqueuing the user
+// message, so form-driven plan handoffs use the same event path as normal
+// sends instead of a second observer stream.
function _mountChatInputForm(host, msgDiv, message, opts) {
const cid = opts.cid || currentCid;
if (!cid) return;
@@ -1846,11 +2244,10 @@ function _mountChatInputForm(host, msgDiv, message, opts) {
// the encoded submission text + recipient agent_id so the
// renderer doesn't have to re-encode (XML format must match
// bus's submission decoder exactly).
- // 2. Send the returned text via the normal send pipeline. This
- // paints the user bubble locally + opens the IPC stream so the
- // agent's reply (deltas, process events, final message) actually
- // reaches the UI. Skipping step 2 was the "click submit, no
- // reaction" bug — backend dispatched but no listener received.
+ // 2. Send the returned text through `/send/stream`. The main-process
+ // stream handler subscribes before calling send(), and send()
+ // includes the user-step plan reconcile, so the downstream agent
+ // dispatch cannot race past the UI listener.
const msgId = msgDiv.dataset.msgId || (message._msg_id || '');
if (!msgId) {
_convLog.warn('form submit missing msgId');
@@ -1877,7 +2274,7 @@ function _mountChatInputForm(host, msgDiv, message, opts) {
const extra = (Array.isArray(attachments) && attachments.length)
? { attachments }
: undefined;
- try { await sendInCurrentConversation(submissionText, extra); }
+ try { await sendInConversation(cid, submissionText, extra); }
catch (err) { _convLog.error('form replay send failed', err); }
},
});
@@ -1904,19 +2301,20 @@ function _marketplaceRequestAgentAvatarHtml(req) {
}
const _MARKETPLACE_REQUEST_CATEGORY_LABELS = {
- education: { zh: '教育', en: 'Education' },
- ecommerce: { zh: '电商', en: 'E-commerce' },
- rnd: { zh: '产研', en: 'R&D' },
- writing: { zh: '写作', en: 'Writing' },
- data: { zh: '数据', en: 'Data' },
- general: { zh: '通用', en: 'General' },
+ education: { zh: '教育', en: 'Education', ja: '教育' },
+ ecommerce: { zh: '电商', en: 'E-commerce', ja: 'EC' },
+ rnd: { zh: '产研', en: 'R&D', ja: '研究開発' },
+ writing: { zh: '写作', en: 'Writing', ja: 'ライティング' },
+ data: { zh: '数据', en: 'Data', ja: 'データ' },
+ general: { zh: '通用', en: 'General', ja: '汎用' },
};
function _marketplaceRequestCategoryLabel(code, lang) {
if (!code) return '';
const row = _MARKETPLACE_REQUEST_CATEGORY_LABELS[String(code)] || null;
if (!row) return String(code);
- return lang === 'zh' ? row.zh : row.en;
+ const base = _baseLang(lang);
+ return row[base] || row.en;
}
function _marketplaceRequestAuthorBadgeHtml(createUid) {
@@ -2142,6 +2540,7 @@ function _renderQuotePreview() {
if (!q) {
wrap.style.display = 'none';
wrap.innerHTML = '';
+ _updateChatInputReserve();
return;
}
// fromName resolved at render time (not at click time) so renames after
@@ -2165,6 +2564,7 @@ function _renderQuotePreview() {
${fileChips ? `<div class="chat-quote-files">${fileChips}</div>` : ''}
`;
wrap.style.display = '';
+ _updateChatInputReserve();
const closeBtn = wrap.querySelector('.chat-quote-close');
if (closeBtn) closeBtn.addEventListener('click', () => _clearQuote(currentCid));
}
@@ -2301,7 +2701,7 @@ async function handleNewChatSubmit() {
const raw = (input.value || '').trim();
if (!raw) return;
if (!ensureModelConfigured()) return;
- const skill = consumeChatSkill('new-chat');
+ const useSelection = consumeChatUseSelection('new-chat');
// Snapshot the new-chat recipient *now* so a stray view-change between
// here and conv-create doesn't reset it before we can transfer.
_pendingNewChatRecipient = { ..._newChatRecipient };
@@ -2310,7 +2710,7 @@ async function handleNewChatSubmit() {
if (typeof _captureCommanderProjectForNewChat === 'function') {
_captureCommanderProjectForNewChat();
}
- const content = applyRecipientPrefix(transformWithSkill(raw, skill), 'new-chat');
+ const content = applyRecipientPrefix(transformWithChatUse(raw, useSelection), 'new-chat');
const draftItems = _chatAttachList(DRAFT_CID);
if (draftItems.some((a) => a.status === 'uploading')) {
await uiAlert(t('chat.attach_still_uploading'));
@@ -2319,13 +2719,20 @@ async function handleNewChatSubmit() {
const draftNames = draftItems.filter((a) => a.status !== 'error').map((a) => a.name);
_convLog.info('new chat submit', {
content_length: content.length,
- skill: skill || null,
+ use: useSelection ? useSelection.kind : null,
+ attachments: draftNames.length,
+ });
+ from: 'new_chat',
+ length: content.length,
+ has_skill: !!(useSelection && useSelection.kind === 'skill'),
+ has_connector: !!(useSelection && useSelection.kind === 'connector'),
attachments: draftNames.length,
});
- // Mirror the selected skill onto the conversation input so subsequent messages
- // in the same thread stay consistent until the user removes the chip.
- if (skill) setChatSkill('conversation', skill);
+ // Mirror the selected skill / connector onto the conversation input so
+ // subsequent messages in the same thread stay consistent until the user
+ // removes the chip.
+ if (useSelection) setChatUseSelection('conversation', useSelection);
const newBtn = document.getElementById('new-chat-send-btn');
if (newBtn) newBtn.disabled = true;
@@ -2417,7 +2824,7 @@ async function handleChatSubmit() {
if (!raw && !_getQuote(currentCid)) return;
if (!ensureModelConfigured()) return;
const cid = currentCid;
- const skill = _chatSkill['conversation'] || '';
+ const useSelection = getChatUseSelection('conversation');
const attachList = _chatAttachList(cid);
if (attachList.some((a) => a.status === 'uploading')) {
await uiAlert(t('chat.attach_still_uploading'));
@@ -2425,10 +2832,18 @@ async function handleChatSubmit() {
}
const attachments = attachList.filter((a) => a.status !== 'error').map((a) => a.name);
_convLog.info('chat submit', { cid, length: raw.length, skill: skill || null, attachments: attachments.length });
+ _convLog.info('chat submit', { cid, length: raw.length, use: useSelection ? useSelection.kind : null, attachments: attachments.length });
+ from: 'conversation',
+ length: raw.length,
+ has_skill: !!(useSelection && useSelection.kind === 'skill'),
+ has_connector: !!(useSelection && useSelection.kind === 'connector'),
+ attachments: attachments.length,
+ });
// If this conversation is already streaming OR has queued items waiting,
// enqueue the new message instead of sending it now. Keep the raw text +
- // skill so the prefix is applied fresh when it's actually sent.
+ // selected skill / connector so the prefix is applied fresh when it's
+ // actually sent.
// Quote is baked into the queued content here (rather than carried as a
// sidecar field on the queue entry) — by the time the queue dispatches,
// the user may have already cleared/replaced the quote in the preview;
@@ -2439,7 +2854,7 @@ async function handleChatSubmit() {
await uiAlert(t('chat.attach_queue_blocked'));
return;
}
- enqueueMessage(cid, applyQuotePrefix(raw, 'conversation'), skill);
+ enqueueMessage(cid, applyQuotePrefix(raw, 'conversation'), useSelection);
_clearQuote(cid);
input.value = '';
autoGrow(input, 200);
@@ -2447,7 +2862,7 @@ async function handleChatSubmit() {
return;
}
- const content = applyRecipientPrefix(applyQuotePrefix(transformWithSkill(raw, skill), 'conversation'), 'conversation');
+ const content = applyRecipientPrefix(applyQuotePrefix(transformWithChatUse(raw, useSelection), 'conversation'), 'conversation');
_clearQuote(cid);
input.value = '';
autoGrow(input, 200);
@@ -2481,6 +2896,7 @@ function _makeConvChatController(cid) {
archive: true,
scrollPin: true,
bindInput: false, // main chat owns its input wiring (queue-aware)
+ actorIdentity: true,
},
hooks: {
onUserAppended(userMsgEl, _content, _id) {
@@ -2525,6 +2941,7 @@ function _makeConvChatController(cid) {
// the new turn just added and the queued user message would render
// off-screen until later layout shifts pushed it into view.
_finishStreamingMsg(id);
+ _scheduleHistoryReconcileAfterStream(id);
// Only drop the map entry if it still refers to *this* controller.
// On abort we dispatch the next queued message synchronously from
// `onAbort`, which assigns a new controller into `_convChatCtrls`
@@ -2537,9 +2954,12 @@ function _makeConvChatController(cid) {
return ctrl;
}
-async function sendInCurrentConversation(content, extra) {
- const cid = currentCid;
- if (!cid || isConvPending(cid)) return;
+async function sendInConversation(cid, content, extra) {
+ if (!cid) return;
+ if (isConvPending(cid)) {
+ enqueueMessage(cid, content, '', { direct: true, extra });
+ return;
+ }
// Scroll-pin spacer is owned by the controller (features.scrollPin) —
// appending it here would land *before* userMsg/asstMsg in DOM order,
@@ -2550,6 +2970,197 @@ async function sendInCurrentConversation(content, extra) {
await ctrl.send(content, extra);
}
+async function sendInCurrentConversation(content, extra) {
+ return sendInConversation(currentCid, content, extra);
+}
+
+function _removeEmptyStreamingPlaceholder(ph) {
+ if (!ph || !ph.parentElement || ph.dataset.finalized === '1') return;
+ const processBody = ph.querySelector('[data-role="process"]');
+ const hasProcess = !!processBody && processBody.children.length > 0;
+ const finalBody = ph.querySelector('[data-role="final"]');
+ const hasFinal = !!finalBody && (finalBody.textContent || '').trim().length > 0;
+ const hasAbortNote = !!ph.querySelector('.stream-aborted-note');
+ if (hasProcess || hasFinal || hasAbortNote) return;
+ for (const [key, val] of Array.from(_groupPlaceholders.entries())) {
+ if (val === ph) _groupPlaceholders.delete(key);
+ }
+ ph.remove();
+}
+
+function _settleDanglingActorPlaceholders(cid) {
+ if (!cid) return;
+ for (const [key, ph] of Array.from(_groupPlaceholders.entries())) {
+ if (!key.startsWith(`${cid}:`)) continue;
+ _groupPlaceholders.delete(key);
+ if (!ph || !ph.parentElement || ph.dataset.finalized === '1') continue;
+ const processBody = ph.querySelector('[data-role="process"]');
+ const hasProcess = !!processBody && processBody.children.length > 0;
+ const finalBody = ph.querySelector('[data-role="final"]');
+ const finalText = ph.dataset.finalText || ph.dataset.streamBuf || (finalBody?.textContent || '');
+ const hasFinal = String(finalText || '').trim().length > 0;
+ if (!hasProcess && !hasFinal) {
+ ph.remove();
+ continue;
+ }
+ _streamingSetFinal(ph, finalText || '', { archive: false });
+ ph.dataset.finalized = '1';
+ }
+}
+
+function _nowForStreamYield() {
+ return (typeof performance !== 'undefined' && typeof performance.now === 'function')
+ ? performance.now()
+ : Date.now();
+}
+
+function _makeStreamPaintYield() {
+ let eventsSinceYield = 0;
+ let lastYieldAt = _nowForStreamYield();
+ return function maybeYieldToPaint() {
+ eventsSinceYield += 1;
+ const now = _nowForStreamYield();
+ if (eventsSinceYield < 32 && now - lastYieldAt < 24) return null;
+ eventsSinceYield = 0;
+ lastYieldAt = now;
+ return new Promise((resolve) => {
+ let settled = false;
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ resolve();
+ };
+ if (typeof requestAnimationFrame === 'function') requestAnimationFrame(finish);
+ setTimeout(finish, 16);
+ });
+ };
+}
+
+function _observeConversationRunFromPlanAction(cid, opts = {}) {
+ if (!cid) return null;
+ const attachExisting = !!opts.attachExisting;
+ const existingState = pendingConvs.get(cid);
+ if (_convChatCtrls.has(cid) || existingState?.controller) return null;
+ if (!attachExisting && (pendingConvs.has(cid) || isGroupConversationBusy(cid))) return null;
+
+ const controller = new AbortController();
+ let msgEl = null;
+ let sawActivity = attachExisting;
+ let settled = false;
+ let activated = false;
+
+ const ctrl = {
+ abort: () => {
+ try { controller.abort(); } catch (_) {}
+ },
+ };
+
+ const activate = () => {
+ if (activated || controller.signal.aborted) return;
+ const existing = pendingConvs.get(cid) || {};
+ if (existing.aborted) return;
+ activated = true;
+ const container = document.getElementById('chat-history');
+ msgEl = existing.loadingEl || (cid === currentCid
+ ? _createStreamingAssistantMessage(container, { hiddenUntilActor: true })
+ : null);
+ _convChatCtrls.set(cid, ctrl);
+ pendingConvs.set(cid, {
+ ...existing,
+ loadingEl: msgEl,
+ needsIndicator: false,
+ controller: ctrl,
+ aborted: false,
+ });
+ setGroupConversationBusy(cid, true);
+ _updateConvSidebarBadge(cid, true);
+ startPolling(cid);
+ if (cid === currentCid) _updateConvSendUI(cid);
+ };
+
+ const noActivityTimer = setTimeout(() => {
+ if (!sawActivity && !settled) ctrl.abort();
+ }, 30000);
+
+ if (attachExisting) activate();
+
+ (async () => {
+ try {
+ const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/events/stream`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ untilIdle: true }),
+ signal: controller.signal,
+ });
+ if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder('utf-8');
+ let buffer = '';
+ const maybeYieldToPaint = _makeStreamPaintYield();
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ let idx;
+ while ((idx = buffer.indexOf('\n\n')) >= 0) {
+ const rawEvent = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 2);
+ const dataLines = rawEvent.split('\n')
+ .filter((l) => l.startsWith('data:'))
+ .map((l) => l.slice(5).trimStart());
+ if (!dataLines.length) continue;
+ let evData;
+ try { evData = JSON.parse(dataLines.join('\n')); }
+ catch (_) { continue; }
+ if (!evData || evData.type === 'done') continue;
+ if (controller.signal.aborted || pendingConvs.get(cid)?.aborted) continue;
+ if (evData.type === 'process') {
+ sawActivity = true;
+ }
+ if (evData.type === 'artifact_created') sawActivity = true;
+ if (evData.type === 'message' && evData.msg && evData.msg.from !== 'user') sawActivity = true;
+ if (evData.type === 'state_changed') {
+ const st = evData.state || {};
+ const inFlight = Array.isArray(st.in_flight) ? st.in_flight : [];
+ if (st.status === 'running' || inFlight.length > 0) sawActivity = true;
+ }
+ if (sawActivity) activate();
+ _handleGroupBusEvent(cid, msgEl, evData, { archive: true });
+ const paintWait = maybeYieldToPaint();
+ if (paintWait) await paintWait;
+ }
+ }
+ } catch (err) {
+ if (err?.name !== 'AbortError' && !controller.signal.aborted) {
+ _convLog.warn(`plan recovery event stream failed cid=${cid}: ${err && err.message}`);
+ if (msgEl && msgEl.parentElement && msgEl.dataset.finalized !== '1') {
+ _streamingSetError(msgEl, err?.message || String(err));
+ }
+ }
+ } finally {
+ settled = true;
+ clearTimeout(noActivityTimer);
+ if (_convChatCtrls.get(cid) === ctrl) _convChatCtrls.delete(cid);
+ if (activated) {
+ 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 });
+ }
+ }
+ })();
+
+ return { cancel: ctrl.abort };
+}
+
+window.ConversationRuntime = {
+ ...(window.ConversationRuntime || {}),
+ observePlanRecoveryRun: _observeConversationRunFromPlanAction,
+ recoverPolledMessages: _recoverPolledVisibleMessages,
+};
+
// Append/remove a sized spacer as the last child of the messages container
// so a short user message can still scroll to the very top while the reply
// is streaming. A real DOM element (not padding) is used so flex-column
@@ -2977,6 +3588,7 @@ function _streamingMarkAborted(msg) {
}
function _finishStreamingMsg(cid) {
+ _stopRuntimeActorRecovery(cid);
pendingConvs.delete(cid);
if (isGroupConversationBusy(cid)) startPolling(cid);
else stopPolling(cid);
@@ -3036,6 +3648,7 @@ function _scrollToMessageTop(msgEl, containerId = 'chat-history') {
// features: {
// archive: bool // attach archive button on final
// scrollPin: bool // pin newly-sent user message to top of viewport
+// actorIdentity: bool // group-chat only: wait for actor before showing placeholder
// }
// hooks: {
// beforeSend(content, id) → transformedContent | null // cancel by returning null
@@ -3052,7 +3665,7 @@ function _scrollToMessageTop(msgEl, containerId = 'chat-history') {
//
// Returns { loadHistory, send, abort, clear, isBusy }
function createChatController(config) {
- const features = { archive: false, scrollPin: true, bindInput: true, queue: false, ...(config.features || {}) };
+ const features = { archive: false, scrollPin: true, bindInput: true, queue: false, actorIdentity: false, ...(config.features || {}) };
const hooks = config.hooks || {};
let pending = null; // { controller, msgEl, userMsgEl, aborted, errored }
@@ -3065,6 +3678,7 @@ function createChatController(config) {
const sendBtnEl = typeof config.sendBtnEl === 'string'
? document.getElementById(config.sendBtnEl)
: config.sendBtnEl;
+ let idlePlaceholder = inputEl ? (inputEl.placeholder || '') : '';
// ── Optional queue module (features.queue enabled) ──────────────────
// Mirrors the main-chat queue (stacked while a reply is streaming,
@@ -3280,9 +3894,15 @@ function createChatController(config) {
sendBtnEl.disabled = false;
sendBtnEl.title = busy ? t('chat.stop_reply') : t('chat.send_title');
if (inputEl) {
- inputEl.placeholder = busy
- ? t('chat.replying')
- : (inputEl.dataset.placeholder || inputEl.placeholder);
+ const replyingText = t('chat.replying');
+ if (busy) {
+ if (inputEl.placeholder && inputEl.placeholder !== replyingText) {
+ idlePlaceholder = inputEl.placeholder;
+ }
+ inputEl.placeholder = replyingText;
+ } else {
+ inputEl.placeholder = idlePlaceholder || inputEl.placeholder;
+ }
}
}
@@ -3359,7 +3979,7 @@ function createChatController(config) {
);
if (hooks.onUserAppended) hooks.onUserAppended(userMsgEl, content, id);
- const msgEl = _createStreamingAssistantMessage(historyEl, { hiddenUntilActor: true });
+ const msgEl = _createStreamingAssistantMessage(historyEl, { hiddenUntilActor: !!features.actorIdentity });
if (hooks.onAssistantStart) hooks.onAssistantStart(msgEl, id);
// On send, pin the user's message to the top of the viewport once;
@@ -3390,6 +4010,7 @@ function createChatController(config) {
const reader = res.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
+ const maybeYieldToPaint = _makeStreamPaintYield();
while (true) {
const { value, done } = await reader.read();
if (done) break;
@@ -3415,6 +4036,8 @@ function createChatController(config) {
pending.errored = true;
if (hooks.onError) hooks.onError(ev.text, msgEl, id);
}
+ const paintWait = maybeYieldToPaint();
+ if (paintWait) await paintWait;
} catch (_) { /* skip malformed */ }
}
}
@@ -3610,6 +4233,7 @@ function _setPlaceholderActor(ph, actorId, opts = {}) {
? _renderActorAvatarHtml(actorId)
: '';
}
+ _decorateActorHeader(ph, actorId);
if (ph.dataset.identityPending === '1') {
if (ready) {
ph.style.display = '';
@@ -3626,12 +4250,13 @@ function _refreshActorPlaceholders(cid, actorId) {
if (!key.startsWith(`${cid}:`)) continue;
const id = ph?.dataset?.fromActor || key.slice(`${cid}:`.length);
if (actorId && id !== actorId) continue;
- _setPlaceholderActor(ph, id, { cid, force: true });
+ _setPlaceholderActor(ph, id, { cid, force: true, allowFallback: !!id && id !== 'commander' });
}
}
function _ensureActorPlaceholder(cid, actorId, fallbackPh) {
const k = _phKey(cid, actorId);
+ const allowFallback = !!actorId && actorId !== 'commander';
let ph = _groupPlaceholders.get(k);
if (ph && ph.parentElement) return ph;
// Adopt the controller's initial placeholder for the first actor seen,
@@ -3645,14 +4270,14 @@ function _ensureActorPlaceholder(cid, actorId, fallbackPh) {
if (fallbackPh && fallbackPh.parentElement
&& fallbackPh.dataset.finalized !== '1'
&& (!fallbackPh.dataset.fromActor || fallbackPh.dataset.fromActor === actorId)) {
- _setPlaceholderActor(fallbackPh, actorId, { cid });
+ _setPlaceholderActor(fallbackPh, actorId, { cid, allowFallback });
_groupPlaceholders.set(k, fallbackPh);
return fallbackPh;
}
const container = document.getElementById('chat-history');
if (!container) return null;
ph = _createStreamingAssistantMessage(container, { hiddenUntilActor: true });
- _setPlaceholderActor(ph, actorId, { cid });
+ _setPlaceholderActor(ph, actorId, { cid, allowFallback });
_groupPlaceholders.set(k, ph);
if (actorId && actorId !== 'commander' && !_knownGroupActorLabel(cid, actorId)) {
_refreshGroupMembers(cid).then(() => _refreshActorPlaceholders(cid, actorId)).catch(() => {});
@@ -3681,6 +4306,14 @@ function _consumeActorPlaceholder(cid, actorId) {
// the GroupMessage so the bubble matches the persisted record.
function _finalizeActorPlaceholder(ph, gm, cid, archive) {
if (!ph || !gm) return;
+ if (gm.id) {
+ const container = document.getElementById('chat-history');
+ const existing = container?.querySelector(`.chat-message[data-msg-id="${CSS.escape(String(gm.id))}"]`);
+ if (existing && existing !== ph) {
+ ph.remove();
+ return;
+ }
+ }
ph.dataset.fromActor = String(gm.from || '');
ph.dataset.msgId = String(gm.id || '');
@@ -3802,6 +4435,7 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
// Group-chat bus event router. Each event is one of:
// { type: 'message', cid, msg: GroupMessage }
// { type: 'process', cid, actor, data: { type, text?, event? } }
+// { type: 'artifact_created', cid, actor, artifact: { id, title, agent_id } }
// { type: 'plan_changed', cid }
// { type: 'state_changed', cid, state: { status, in_flight } }
// { type: 'member_joined', cid, actor }
@@ -3833,9 +4467,14 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
if (evData.type === 'message') {
const gm = evData.msg;
if (!gm) return;
- // Skip echoing the user's own send — already rendered as the user
- // bubble by the input handler.
- if (gm.from === 'user') return;
+ // The user's own send is already rendered optimistically by the input
+ // handler. Still stamp it with the persisted message id once the bus echoes
+ // the write, so history reconciliation can prove the DOM matches jsonl
+ // instead of forcing a late reload.
+ if (gm.from === 'user') {
+ _claimPersistedUserMessage(cid, gm);
+ return;
+ }
// Internal plan-step dispatch (commander → agent) — agent slice gets
// it for context, user view ignores. See loadConversationHistory's
// matching filter for refresh consistency.
@@ -3945,6 +4584,22 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
} else if (data.type === 'event') {
_renderAgentEvent(target, data.event);
}
+ } else if (evData.type === 'artifact_created') {
+ const actor = String(evData.actor || evData.artifact?.agent_id || '');
+ const artifact = evData.artifact || {};
+ if (!actor || !artifact.id) return;
+ if (!isGroupConversationBusy(cid)) {
+ setGroupConversationBusy(cid, true);
+ _updateConvSidebarBadge(cid, true);
+ startPolling(cid);
+ if (cid === currentCid) _updateConvSendUI(cid);
+ }
+ const target = _ensureActorPlaceholder(cid, actor, streamingMsg);
+ const bubble = target?.querySelector?.('.chat-bubble');
+ if (bubble && typeof window.mountMessageArtifacts === 'function') {
+ window.mountMessageArtifacts(bubble, [artifact], cid);
+ _stickBottomFromMsg(target);
+ }
} else if (evData.type === 'plan_changed') {
// Plan step transitions are the trigger for the input-box auto-target:
// when an interactive agent's step enters in_progress, the user's next
@@ -3982,8 +4637,11 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
_updateConvSidebarBadge(cid, false);
if (cid === currentCid) _updateConvSendUI(cid);
} else if (evData.type === 'aborted') {
+ _stopRuntimeActorRecovery(cid);
setGroupConversationBusy(cid, false);
_latestInFlight.set(cid, []);
+ _refreshTaskSurfacesAfterAbort(cid);
+ _scheduleHistoryReconcileAfterStream(cid, { force: true });
// Only drop EMPTY placeholders here (queued-but-not-yet-running workers
// whose queue got cleared by bus.abort never fire runTurn → no follow-up
// message/turn_silent → their dancing-dot placeholder would be orphaned
@@ -4115,44 +4773,6 @@ function _mountCreatedSkillChip(msg, payload) {
try { if (typeof loadSkills === 'function') loadSkills(true); } catch (_) {}
}
-// Hide the `<agent-input-submission form_id=... agent_id=...>{json}
-// </agent-input-submission>` XML tag from a user message body at render
-// time. The tag is required in the stored raw text so the LLM can parse
-// back the submitted values, but it's noise for the human reader — the
-// bulleted summary above it already tells them what they confirmed.
-function _stripSubmissionTagForDisplay(text) {
- if (!text || text.indexOf('<agent-input-submission') < 0) return text;
- // Atomic-container strip with prose/code guard via strip-structural-blocks.js.
- // Same class of fragmentation / set-B leak as `<agent>` — see that
- // file's header for the invariant matrix.
- const out = _stripOuterTagBlocks(text, 'agent-input-submission');
- if (out === text) return text;
- return out.replace(/\n{3,}/g, '\n\n').trimEnd();
-}
-
-// Hide the `<artifact-result artifact_id=... agent_id=...>{json}
-// </artifact-result>` tag from a user message body at render time. The tag
-// is the machine payload an interactive artifact posted back (the LLM parses
-// it); the human reader only needs the one-line summary above it. Same
-// atomic-container strip + prose/code guard as the submission tag.
-function _stripArtifactResultTagForDisplay(text) {
- if (!text || text.indexOf('<artifact-result') < 0) return text;
- const out = _stripOuterTagBlocks(text, 'artifact-result');
- if (out === text) return text;
- return out.replace(/\n{3,}/g, '\n\n').trimEnd();
-}
-
-// Hide the `<marketplace-install-result>` machine payload that gets replayed
-// after the user clicks a marketplace install/skip card. The visible summary
-// line remains, while the commander still receives the raw structured tag in
-// message history and can continue the task.
-function _stripMarketplaceInstallResultTagForDisplay(text) {
- if (!text || text.indexOf('<marketplace-install-result') < 0) return text;
- const out = _stripOuterTagBlocks(text, 'marketplace-install-result');
- if (out === text) return text;
- return out.replace(/\n{3,}/g, '\n\n').trimEnd();
-}
-
// `_splitMarkdownProseCode`, `_findOuterAgentRanges`, `_stripSurvivingAgentBlocks`,
// `_replaceOuterAgentBlocks` are defined in `./strip-structural-blocks.js` (loaded earlier
// in `index.html`). They live in their own file so vitest can pin the set-A /
@@ -4749,6 +5369,7 @@ function _streamingUpdateLive(msg, prefix, text, appendDelta) {
// Update the loading element (wherever it currently lives in DOM) with the reply.
function _resolveConvReply(cid, text, isError) {
const state = pendingConvs.get(cid);
+ _stopRuntimeActorRecovery(cid);
pendingConvs.delete(cid);
setGroupConversationBusy(cid, false);
stopPolling(cid);
@@ -4837,15 +5458,37 @@ function _renderConvDisabledBanner(cid) {
if (cid === currentCid) _updateConvSendUI(cid);
}
+function _refreshTaskSurfacesAfterAbort(cid) {
+ if (!cid) return;
+ try {
+ if (window.PlanRail) {
+ window.PlanRail.setInFlight(cid, []);
+ window.PlanRail.refresh(cid, { force: true });
+ }
+ } catch (_) {}
+ try {
+ if (window.ConversationInfo) window.ConversationInfo.refresh(cid, { silent: true });
+ } catch (_) {}
+}
+
function abortConvStream(cid) {
const state = pendingConvs.get(cid);
+ _stopRuntimeActorRecovery(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
// background. Fire-and-forget — no need to block the UI on the response.
- try { apiFetch(`/api/conversations/${cid}/abort`, { method: 'POST' }); } catch (_) {}
+ try {
+ apiFetch(`/api/conversations/${cid}/abort`, { method: 'POST' })
+ .catch(() => {})
+ .finally(() => {
+ _refreshTaskSurfacesAfterAbort(cid);
+ _scheduleHistoryReconcileAfterStream(cid, { force: true });
+ });
+ } catch (_) {}
if (!state) {
_updateConvSidebarBadge(cid, false);
+ _refreshTaskSurfacesAfterAbort(cid);
if (cid === currentCid) _updateConvSendUI(cid);
return;
}
@@ -4862,6 +5505,7 @@ function abortConvStream(cid) {
stopPolling(cid);
if (state.loadingEl && state.loadingEl.isConnected) state.loadingEl.remove();
_updateConvSidebarBadge(cid, false);
+ _refreshTaskSurfacesAfterAbort(cid);
if (cid === currentCid) _updateConvSendUI(cid);
return;
}
@@ -4926,3 +5570,57 @@ function _refreshAllConvBadges() {
if (cid) _updateConvSidebarBadge(cid);
});
}
+
+// ─── Chat-history right-click menu (selection-only) ───────────────────────
+// Two items: Copy / 临时编辑. Without an active selection we let the
+// browser's default context menu show (which still carries the Devtools
+// "Inspect" entry that we rely on in dev). Wired once via event delegation
+// on the chat-history root — works for every bubble, present and future.
+function _initChatSelectionMenu() {
+ const container = document.getElementById('chat-history');
+ if (!container) return;
+ if (container.dataset.selectionMenuBound === '1') return;
+ container.dataset.selectionMenuBound = '1';
+ container.addEventListener('contextmenu', (e) => {
+ const sel = window.getSelection();
+ const text = sel && !sel.isCollapsed ? sel.toString() : '';
+ if (!text.trim()) return;
+ // Only intercept when the cursor target is inside a rendered message.
+ // Right-click on the empty area between bubbles falls through to the
+ // browser default. Class is `.chat-message` (see appendChatMessage in
+ // this file) — not `.chat-msg` (that's the attachment / produced-chip
+ // namespace).
+ if (!(e.target instanceof Element) || !e.target.closest('.chat-message')) return;
+ e.preventDefault();
+ const snapshot = String(text); // copy now — getSelection() can be cleared by the click
+ if (typeof showContextMenu !== 'function') return;
+ showContextMenu(e, [
+ {
+ label: t('chat.menu.copy'),
+ onClick: () => {
+ try { navigator.clipboard.writeText(snapshot); }
+ catch (_) { /* swallow — older Electron/old clipboard API */ }
+ },
+ },
+ {
+ label: t('chat.menu.scratch_edit'),
+ onClick: () => {
+ if (typeof openChatMdDrawer !== 'function') return;
+ openChatMdDrawer({
+ source: { kind: 'ephemeral', initialText: snapshot },
+ initialMode: 'edit',
+ title: t('chat.md_drawer.scratch_title'),
+ });
+ },
+ },
+ ]);
+ });
+}
+
+if (typeof window !== 'undefined') {
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', _initChatSelectionMenu, { once: true });
+ } else {
+ _initChatSelectionMenu();
+ }
+}
diff --git a/src/renderer/modules/ipc-shim.js b/src/renderer/modules/ipc-shim.js
index c94dc53d..44ec4182 100644
--- a/src/renderer/modules/ipc-shim.js
+++ b/src/renderer/modules/ipc-shim.js
@@ -64,6 +64,7 @@ const _IPC_ROUTES = [
['POST', /^\/api\/conversations\/([^/]+)\/send\/stream$/, 'conversations.sendStream', ['cid'], { stream: true }],
['POST', /^\/api\/conversations\/([^/]+)\/abort$/, 'groupChat.abort', ['cid']],
['GET', /^\/api\/conversations\/([^/]+)\/members$/, 'groupChat.listMembers', ['cid']],
+ ['GET', /^\/api\/conversations\/([^/]+)\/runtime$/, 'groupChat.runtimeStatus', ['cid']],
['GET', /^\/api\/conversations\/([^/]+)\/plan$/, 'groupChat.readPlan', ['cid']],
['POST', /^\/api\/conversations\/([^/]+)\/plan\/steps\/(\d+)\/retry$/, 'groupChat.retryStep', ['cid', 'stepIndex']],
['POST', /^\/api\/conversations\/([^/]+)\/plan\/steps\/(\d+)\/skip$/, 'groupChat.skipStep', ['cid', 'stepIndex']],
diff --git a/src/renderer/modules/local-agents.js b/src/renderer/modules/local-agents.js
index 725c301e..804a7c36 100644
--- a/src/renderer/modules/local-agents.js
+++ b/src/renderer/modules/local-agents.js
@@ -12,7 +12,7 @@
// and edit. `description_zh` + `description_en` are stored side-by-
// side on the agent so locale switches are zero-cost; `name` is a
// single brand label (the user can rename to disambiguate two
-// instances of the same CLI bound to different project_dirs).
+// instances of the same CLI bound to different project directories).
//
// Detection pre-warms 500ms after script load so the first modal
// open doesn't pay the cold detection cost.
@@ -63,8 +63,8 @@ function getCliDefaults(cliType) {
}
/** True when the CLI is one of claude / codex (the coding agents that
- * expose a project-dir form input). Mirrors `cliSupportsProjectDir`
- * in features/agents.ts — keep in sync. */
+ * expose a project-directory setting). Mirrors
+ * `cliIsCodingAgent` in features/agents.ts — keep in sync. */
function cliIsCodingAgent(cliType) {
const d = getCliDefaults(cliType);
return !!(d && d.isCoding);
@@ -97,7 +97,7 @@ let _extCliSelectApi = null;
* selected"; detected CLIs follow. `onChange` fires with the chosen
* `LocalCliType` (string) or null when the user reverts to the "not
* selected" sentinel — agents.js wires
- * this to the auto-fill / project-dir-row toggling logic.
+ * this to the auto-fill logic.
*
* Idempotent: re-mounting just resets options + value so a re-open of
* the modal picks up newly-installed CLIs.
diff --git a/src/renderer/modules/marketplace.js b/src/renderer/modules/marketplace.js
index 9fead6a6..0f91001f 100644
--- a/src/renderer/modules/marketplace.js
+++ b/src/renderer/modules/marketplace.js
@@ -253,11 +253,27 @@ async function _mpInitReconcileWatch() {
// switch tabs. Force re-fetch (loadAgents(true) / loadSkills(true)) bypasses the renderer
// module-level lists cache; the marketplace listed-state hydrates from those.
if (status.state === 'done' && prevState === 'running' && status.pulled > 0) {
- try { if (typeof loadAgents === 'function') loadAgents(true); } catch { /* ignore */ }
- try { if (typeof loadSkills === 'function') loadSkills(true); } catch { /* ignore */ }
- // If marketplace panel is open right now, also re-run the install-state hydration
- // so card buttons flip from Install to Installed without a tab switch.
- if (isMarketplaceOpen()) _mpLoadAll();
+ Promise.resolve().then(async () => {
+ try {
+ if (typeof refreshAgentsAfterMarketplaceReconcile === 'function') {
+ await refreshAgentsAfterMarketplaceReconcile();
+ } else if (typeof loadAgents === 'function') {
+ await loadAgents(true);
+ }
+ } catch { /* ignore */ }
+ try {
+ if (typeof refreshSkillsAfterMarketplaceReconcile === 'function') {
+ await refreshSkillsAfterMarketplaceReconcile();
+ } else if (typeof loadSkills === 'function') {
+ await loadSkills(true);
+ }
+ } catch { /* ignore */ }
+ // If marketplace panel is open right now, also re-run the install-state hydration
+ // so card buttons flip from Install to Installed without a tab switch.
+ if (isMarketplaceOpen()) {
+ try { await _mpLoadAll(); } catch { /* ignore */ }
+ }
+ }).catch(() => { /* ignore */ });
}
});
} catch { /* push channel not allowed (shouldn't happen) — silently degrade to no banner */ }
@@ -367,6 +383,7 @@ async function _mpLoadAll() {
_mpState.installedSkillIds = new Set(((instSkills && instSkills.skills) || []).map((s) => s.id));
_mpPersistInstalled();
await _mpLoadListings();
+ await _mpRefreshOpenDetailFromListings();
} catch (err) {
// A failed refresh must NOT wipe what's already on screen — surface as a body-level error
// only when the visible tab has nothing to show; otherwise log + keep the stale view.
@@ -382,6 +399,24 @@ function _mpPersistCategoriesCache(list) {
try { localStorage.setItem(MP_CATEGORIES_LS_KEY, JSON.stringify(list)); } catch { /* ignore */ }
}
+async function _mpRefreshOpenDetailFromListings() {
+ if (!_mpState || _mpState.view !== 'detail' || !_mpState.detailKind || !_mpState.detailItem) return;
+ const kind = _mpState.detailKind;
+ const list = kind === 'agent' ? _mpState.agents : _mpState.skills;
+ const fresh = list.find((x) => x.id === _mpState.detailItem.id);
+ if (!fresh) return;
+ const prev = _mpState.detailItem;
+ const changed = prev.version !== fresh.version
+ || prev.published_at !== fresh.published_at
+ || prev.updated_at !== fresh.updated_at;
+ if (!changed) {
+ _mpState.detailItem = { ...prev, ...fresh };
+ _mpRenderDetail();
+ return;
+ }
+ await _mpOpenDetail(kind, fresh, { preserveSkillState: true });
+}
+
// Module-load: kick off the reconcile-status watch so the banner in `agents-grid-view` /
// `skills-grid-view` lights up DURING boot reconcile, not only after the user enters
// marketplace. Idempotent — `_mpInitReconcileWatch` runs once and a second call no-ops.
@@ -736,34 +771,43 @@ function _mpCategoryLabel(code, lang) {
}
// ─── Detail view rendering ───
-async function _mpOpenDetail(kind, item) {
+async function _mpOpenDetail(kind, item, opts = {}) {
+ const prevSelected = opts.preserveSkillState ? (_mpState.detailSkillSelected || 'SKILL.md') : 'SKILL.md';
+ const prevSourceOpen = opts.preserveSkillState ? !!_mpState.detailSkillSourceOpen : false;
_mpState.detailKind = kind;
_mpState.detailItem = item;
_mpState.detailLoading = true;
_mpState.detailError = '';
_mpState.detailAgentJson = null;
_mpState.detailSkillFiles = [];
- _mpState.detailSkillSelected = 'SKILL.md';
+ _mpState.detailSkillSelected = prevSelected;
_mpState.detailSkillFileText = '';
+ _mpState.detailSkillSourceOpen = prevSourceOpen;
_mpShowDetailView();
_mpRenderDetail();
try {
if (kind === 'agent') {
const detail = await window.orkas.invoke('marketplace.detailAgent', {
- id: item.id, version: item.version, published_at: item.published_at,
+ id: item.id, version: item.version,
+ published_at: item.published_at, updated_at: item.updated_at,
});
if (!detail || detail.ok === false) throw new Error((detail && detail.error) || 'detail failed');
_mpState.detailAgentJson = detail.agent_json;
} else {
const detail = await window.orkas.invoke('marketplace.detailSkill', {
- id: item.id, version: item.version, published_at: item.published_at,
+ id: item.id, version: item.version,
+ published_at: item.published_at, updated_at: item.updated_at,
});
if (!detail || detail.ok === false) throw new Error((detail && detail.error) || 'detail failed');
const files = await window.orkas.invoke('marketplace.cacheSkillFiles', { id: item.id });
_mpState.detailSkillFiles = (files && files.list) || [];
- if (_mpState.detailSkillFiles.find((f) => f.path === 'SKILL.md')) {
- const r = await window.orkas.invoke('marketplace.cacheSkillRead', { id: item.id, file: 'SKILL.md' });
+ const selected = _mpState.detailSkillFiles.find((f) => f.path === _mpState.detailSkillSelected)
+ ? _mpState.detailSkillSelected
+ : 'SKILL.md';
+ _mpState.detailSkillSelected = selected;
+ if (_mpState.detailSkillFiles.find((f) => f.path === selected)) {
+ const r = await window.orkas.invoke('marketplace.cacheSkillRead', { id: item.id, file: selected });
_mpState.detailSkillFileText = (r && r.content) || '';
}
}
@@ -992,7 +1036,8 @@ async function _mpInstall(kind, id) {
try {
const channel = kind === 'agent' ? 'marketplace.installAgent' : 'marketplace.installSkill';
const r = await window.orkas.invoke(channel, {
- id, version: item.version, published_at: item.published_at,
+ id, version: item.version,
+ published_at: item.published_at, updated_at: item.updated_at,
});
if (!r || r.ok === false) throw new Error((r && r.error) || 'install failed');
if (kind === 'agent') _mpState.installedAgentIds.add(id);
diff --git a/src/renderer/modules/md-view-edit.js b/src/renderer/modules/md-view-edit.js
new file mode 100644
index 00000000..eb5a6fc6
--- /dev/null
+++ b/src/renderer/modules/md-view-edit.js
@@ -0,0 +1,752 @@
+// ─── Shared markdown viewer/editor ───
+// Single implementation behind both knowledge-base file editing (contexts.js)
+// and chat-side scratch / generated-md editing (chat-md-drawer.js). Two body
+// modes — `view` (renderMarkdown + clickable task lists) and `edit` (textarea
+// + markdown toolbar + preview toggle) — and a `source.kind` dispatch table
+// for read / write / delete that lets each host plug its own backend in
+// without forking the renderer code.
+//
+// Why this lives in its own module:
+// - the KB pane and the chat drawer have different chrome (file tree vs.
+// drawer header), but the markdown editing surface MUST behave identically
+// (CLAUDE.md §8 reuse rule). Forking the toolbar / keyboard / draft logic
+// across two callers has bitten us before — kept here as one file with
+// parameterized I/O.
+//
+// API:
+// mountMdViewEdit({ bodyEl, actionsEl, source, capabilities?, initialMode?,
+// initialContent?, initialDraft?, callbacks? })
+// → { destroy, refreshContent, getMode, setMode, isDirty,
+// getDraft, setDraftAsContent, getSource }
+//
+// source: { kind: 'context', rel: string }
+// | { kind: 'workspace', absPath: string, cid?: string }
+// | { kind: 'ephemeral', initialText: string }
+//
+// Capabilities default per kind:
+// context → edit/save/delete/reveal/taskCheckbox = true
+// workspace → edit/save/reveal/taskCheckbox = true; delete = false
+// ephemeral → edit forced (no view); save/delete/reveal = false;
+// actionsEl exposes copyDraft + sendToChatInput instead
+//
+// What the caller still owns:
+// - the surrounding container (path / title / close chrome). mountMdViewEdit
+// never touches anything outside bodyEl + actionsEl.
+// - cross-mount draft persistence (KB needs per-file survival across file
+// switches; chat doesn't). Pass / consume `initialDraft` + `onDraftChange`.
+
+const _mveLog = createLogger('md-view-edit');
+
+const _MVE_TODO_LINE_RE = /^(\s*)- \[( |x|X)\] (.*)$/;
+
+// Toolbar definition. `kind` keys map to `_mveApplyMd()` cases; SVG icons
+// come from icons.js; `label` is the i18n key for the tooltip. Keys are the
+// historical `contexts.editor.tb.*` set — kept as-is so the three locales
+// don't churn just for a rename. Same goes for `contexts.editor.placeholder.*`
+// strings used by `_mveApplyMd`.
+const _MVE_EDITOR_TOOLBAR = [
+ { kind: 'h1', icon: 'H1', label: 'contexts.editor.tb.h1' },
+ { kind: 'h2', icon: 'H2', label: 'contexts.editor.tb.h2' },
+ { kind: 'h3', icon: 'H3', label: 'contexts.editor.tb.h3' },
+ { kind: 'sep' },
+ { kind: 'bold', icon: 'B', label: 'contexts.editor.tb.bold', cls: 'is-bold' },
+ { kind: 'italic', icon: 'I', label: 'contexts.editor.tb.italic', cls: 'is-italic' },
+ { kind: 'strike', icon: 'S', label: 'contexts.editor.tb.strike', cls: 'is-strike' },
+ { kind: 'sep' },
+ { kind: 'ul', iconName: 'list', label: 'contexts.editor.tb.ul' },
+ { kind: 'ol', iconName: 'list-ordered', label: 'contexts.editor.tb.ol' },
+ { kind: 'quote', iconName: 'quote', label: 'contexts.editor.tb.quote' },
+ { kind: 'sep' },
+ { kind: 'code', iconName: 'code', label: 'contexts.editor.tb.code' },
+ { kind: 'codeblock', iconName: 'code-block', label: 'contexts.editor.tb.codeblock' },
+ { kind: 'sep' },
+ { kind: 'link', iconName: 'link', label: 'contexts.editor.tb.link' },
+ { kind: 'image', iconName: 'image', label: 'contexts.editor.tb.image' },
+ { kind: 'sep' },
+ { kind: 'todo', iconName: 'square', label: 'contexts.editor.tb.todo' },
+];
+
+function _mveDefaultCapabilities(kind) {
+ if (kind === 'context') {
+ return { edit: true, save: true, delete: true, reveal: true, taskCheckbox: true };
+ }
+ if (kind === 'workspace') {
+ return { edit: true, save: true, delete: false, reveal: true, taskCheckbox: true };
+ }
+ // ephemeral
+ return { edit: true, save: false, delete: false, reveal: false, taskCheckbox: false };
+}
+
+function mountMdViewEdit(opts) {
+ const bodyEl = opts.bodyEl;
+ const actionsEl = opts.actionsEl;
+ if (!bodyEl || !actionsEl) {
+ _mveLog.warn('mountMdViewEdit called without bodyEl/actionsEl', { hasBody: !!bodyEl, hasActions: !!actionsEl });
+ return _mveNoopController();
+ }
+ const source = opts.source;
+ if (!source || typeof source.kind !== 'string') {
+ _mveLog.warn('mountMdViewEdit called without source.kind');
+ return _mveNoopController();
+ }
+
+ const caps = Object.assign(
+ _mveDefaultCapabilities(source.kind),
+ opts.capabilities || {},
+ );
+ const callbacks = opts.callbacks || {};
+
+ // ── State ─────────────────────────────────────────────────────────────
+ const state = {
+ source,
+ caps,
+ callbacks,
+ bodyEl,
+ actionsEl,
+ // Canonical content (from disk / source). Ephemeral seeds this with
+ // initialText; the "is dirty" check compares draft vs. this.
+ content: '',
+ // Modes:
+ // 'view' — renderMarkdown of content + (optional) clickable tasks
+ // 'edit' — textarea + toolbar (preview is a sub-toggle of edit)
+ mode: 'view',
+ draft: '',
+ preview: false,
+ destroyed: false,
+ // Suppress an automatic re-render after an external setMode call so the
+ // caller can chain `setMode('edit')` then push focus / scroll
+ // synchronously without fighting the controller.
+ _suppressRender: false,
+ };
+
+ // Ephemeral starts in edit mode with the seeded text — no view mode for
+ // it (a "view" of pre-loaded text the user is about to mutate would be
+ // surprising; the textarea+preview toggle covers the read case).
+ if (source.kind === 'ephemeral') {
+ state.content = source.initialText || '';
+ state.draft = state.content;
+ state.mode = 'edit';
+ } else if (typeof opts.initialContent === 'string') {
+ // Caller (KB) already fetched the content — skip the round-trip.
+ state.content = opts.initialContent;
+ state.mode = opts.initialMode === 'edit' ? 'edit' : 'view';
+ } else {
+ state.mode = opts.initialMode === 'edit' ? 'edit' : 'view';
+ }
+
+ // Optional inherited draft (KB per-file survival).
+ if (opts.initialDraft && typeof opts.initialDraft.content === 'string') {
+ state.draft = opts.initialDraft.content;
+ state.preview = !!opts.initialDraft.isPreview;
+ state.mode = 'edit';
+ }
+
+ // Render after first paint. If we're not ephemeral and the caller didn't
+ // pre-fill content, fetch it now. Errors land in `_mveRenderError`.
+ if (source.kind !== 'ephemeral' && typeof opts.initialContent !== 'string') {
+ _mveLoadAndRender(state);
+ } else {
+ _mveRender(state);
+ }
+
+ // ── Controller ────────────────────────────────────────────────────────
+ function destroy() {
+ state.destroyed = true;
+ if (bodyEl) bodyEl.innerHTML = '';
+ if (actionsEl) actionsEl.innerHTML = '';
+ }
+
+ async function refreshContent() {
+ if (state.destroyed) return;
+ if (state.source.kind === 'ephemeral') return;
+ await _mveLoadAndRender(state);
+ }
+
+ function getMode() { return state.mode; }
+ function setMode(m) {
+ if (state.destroyed) return;
+ if (m !== 'view' && m !== 'edit') return;
+ if (m === 'edit') _mveEnterEdit(state);
+ else _mveRenderView(state);
+ }
+ function isDirty() { return state.mode === 'edit' && state.draft !== state.content; }
+ function getDraft() { return { content: state.draft, isPreview: state.preview }; }
+ function getSource() { return state.source; }
+
+ // Replace the canonical content with the current draft and re-render in
+ // view mode. Used by the "send to chat input" flow where the host wants
+ // to mark the draft as consumed without persisting it.
+ function setDraftAsContent() {
+ state.content = state.draft;
+ state.mode = 'view';
+ state.preview = false;
+ _mveRender(state);
+ }
+
+ return { destroy, refreshContent, getMode, setMode, isDirty, getDraft, setDraftAsContent, getSource };
+}
+
+function _mveNoopController() {
+ return {
+ destroy() {},
+ refreshContent() {},
+ getMode() { return 'view'; },
+ setMode() {},
+ isDirty() { return false; },
+ getDraft() { return { content: '', isPreview: false }; },
+ setDraftAsContent() {},
+ getSource() { return null; },
+ };
+}
+
+// ── Source dispatch ──────────────────────────────────────────────────────
+
+async function _mveReadSource(source) {
+ if (source.kind === 'ephemeral') {
+ return { ok: true, content: source.initialText || '' };
+ }
+ if (source.kind === 'context') {
+ try {
+ const res = await apiFetch(`/api/contexts/read?path=${encodeURIComponent(source.rel)}`);
+ const data = await res.json();
+ if (!data.ok) return { ok: false, error: data.error || 'read_failed' };
+ return { ok: true, content: String(data.content || '') };
+ } catch (e) {
+ return { ok: false, error: e.message || String(e) };
+ }
+ }
+ if (source.kind === 'workspace') {
+ try {
+ const payload = { path: source.absPath };
+ if (source.cid) payload.cid = source.cid;
+ const res = await window.orkas.invoke('produced.readText', payload);
+ if (!res || !res.ok) return { ok: false, error: (res && res.error) || 'read_failed', detail: res };
+ return { ok: true, content: String(res.text || '') };
+ } catch (e) {
+ return { ok: false, error: e.message || String(e) };
+ }
+ }
+ return { ok: false, error: 'unknown source kind' };
+}
+
+async function _mveWriteSource(source, content) {
+ if (source.kind === 'context') {
+ try {
+ const res = await apiFetch('/api/contexts/update', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path: source.rel, content }),
+ });
+ const data = await res.json();
+ if (!data.ok) return { ok: false, error: data.error || 'save_failed' };
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: e.message || String(e) };
+ }
+ }
+ if (source.kind === 'workspace') {
+ try {
+ const payload = { path: source.absPath, content };
+ if (source.cid) payload.cid = source.cid;
+ const res = await window.orkas.invoke('produced.writeText', payload);
+ if (!res || !res.ok) return { ok: false, error: (res && res.error) || 'save_failed' };
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: e.message || String(e) };
+ }
+ }
+ return { ok: false, error: 'source is not writable' };
+}
+
+// ── Rendering ────────────────────────────────────────────────────────────
+
+async function _mveLoadAndRender(state) {
+ const res = await _mveReadSource(state.source);
+ if (state.destroyed) return;
+ if (!res.ok) {
+ _mveRenderError(state, res.error || 'read_failed');
+ return;
+ }
+ state.content = res.content;
+ if (!state.draft) state.draft = state.content;
+ if (state.callbacks.onContentLoaded) {
+ try { state.callbacks.onContentLoaded(state.content); }
+ catch (e) { _mveLog.warn('onContentLoaded threw', e); }
+ }
+ _mveRender(state);
+}
+
+function _mveRender(state) {
+ if (state.destroyed) return;
+ if (state.mode === 'edit') _mveRenderEditor(state);
+ else _mveRenderView(state);
+}
+
+function _mveRenderError(state, msg) {
+ const body = state.bodyEl;
+ body.innerHTML = `<div class="ctx-viewer-msg">${escapeHtml(t('contexts.viewer.read_failed', { reason: msg }) || `Failed to read file: ${msg}`)}</div>`;
+ state.actionsEl.innerHTML = '';
+}
+
+function _mveRenderView(state) {
+ state.mode = 'view';
+ const bodyEl = state.bodyEl;
+ const actionsEl = state.actionsEl;
+ const content = state.content || '';
+ bodyEl.innerHTML = `<div class="ctx-viewer-md markdown-body">${renderMarkdown(content)}</div>`;
+ 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>`);
+ actionsEl.innerHTML = actions.join('');
+
+ actionsEl.querySelector('[data-mve-action="edit"]')?.addEventListener('click', () => _mveEnterEdit(state));
+ actionsEl.querySelector('[data-mve-action="reveal"]')?.addEventListener('click', () => state.callbacks.onReveal?.());
+ actionsEl.querySelector('[data-mve-action="delete"]')?.addEventListener('click', () => state.callbacks.onDelete?.());
+
+ _mveEmitDirty(state);
+}
+
+function _mveEnterEdit(state) {
+ state.mode = 'edit';
+ // Only seed the draft from canonical content if we don't have a draft yet
+ // — caller-provided initialDraft and prior edit state both reach here.
+ if (!state.draft) state.draft = state.content || '';
+ _mveRenderEditor(state);
+ _mveEmitDirty(state);
+}
+
+function _mveRenderEditor(state) {
+ const bodyEl = state.bodyEl;
+ const actionsEl = state.actionsEl;
+ const toolbarHtml = _MVE_EDITOR_TOOLBAR.map(item => {
+ if (item.kind === 'sep') return `<span class="ctx-editor-toolbar-sep" aria-hidden="true"></span>`;
+ const disabled = state.preview ? 'disabled' : '';
+ const extraCls = item.cls ? ` ${item.cls}` : '';
+ const icon = item.iconName && typeof window !== 'undefined' && typeof window.uiIconHtml === 'function'
+ ? window.uiIconHtml(item.iconName, 'ui-icon ctx-editor-svg-icon')
+ : escapeHtml(item.icon || '');
+ return `<button type="button" class="btn btn-sm btn-icon ctx-editor-tb-btn${extraCls}" data-kind="${item.kind}" title="${escapeHtml(t(item.label))}" ${disabled}>${icon}</button>`;
+ }).join('');
+ const toggleKey = state.preview ? 'contexts.editor.tb.edit_back' : 'contexts.editor.tb.preview';
+ const toggleIcon = typeof window !== 'undefined' && typeof window.uiIconHtml === 'function'
+ ? window.uiIconHtml(state.preview ? 'pencil' : 'eye', 'ui-icon ctx-editor-toggle-icon')
+ : '';
+ const draft = state.draft;
+ const bodyHtml = state.preview
+ ? `<div class="ctx-viewer-md markdown-body ctx-editor-preview">${draft.trim() ? renderMarkdown(draft) : `<div class="ctx-viewer-msg">${escapeHtml(t('contexts.editor.preview_empty'))}</div>`}</div>`
+ : `<textarea class="ctx-viewer-editor" data-mve-textarea spellcheck="false">${escapeHtml(draft)}</textarea>`;
+ bodyEl.innerHTML = `
+ <div class="ctx-editor-toolbar" role="toolbar">
+ ${toolbarHtml}
+ <span class="ctx-editor-toolbar-spacer"></span>
+ <button type="button" class="btn btn-sm ctx-editor-toggle" data-mve-toggle title="${escapeHtml(t(toggleKey))}">${toggleIcon}<span>${escapeHtml(t(toggleKey))}</span></button>
+ </div>
+ <div class="ctx-editor-body">${bodyHtml}</div>
+ `;
+
+ // 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>`);
+ } 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>`);
+ }
+ actionsEl.innerHTML = actions.join('');
+
+ actionsEl.querySelector('[data-mve-action="save"]')?.addEventListener('click', () => _mveSave(state));
+ actionsEl.querySelector('[data-mve-action="cancel"]')?.addEventListener('click', () => _mveCancelEdit(state));
+ actionsEl.querySelector('[data-mve-action="copy-draft"]')?.addEventListener('click', () => _mveCopyDraft(state));
+ actionsEl.querySelector('[data-mve-action="send-to-chat"]')?.addEventListener('click', () => _mveSendDraftToChat(state));
+
+ bodyEl.querySelector('[data-mve-toggle]')?.addEventListener('click', () => _mveTogglePreview(state));
+ bodyEl.querySelectorAll('.ctx-editor-tb-btn').forEach(btn => {
+ btn.addEventListener('mousedown', (e) => e.preventDefault());
+ btn.addEventListener('click', () => {
+ if (state.preview) return;
+ const ta = bodyEl.querySelector('[data-mve-textarea]');
+ if (!ta) return;
+ _mveApplyMd(state, ta, btn.dataset.kind);
+ });
+ });
+ const ta = bodyEl.querySelector('[data-mve-textarea]');
+ if (ta) {
+ ta.addEventListener('keydown', (e) => _mveOnKey(state, ta, e));
+ ta.addEventListener('input', () => {
+ state.draft = ta.value;
+ _mveEmitDraftChange(state);
+ _mveEmitDirty(state);
+ });
+ ta.focus();
+ }
+
+ _mveEmitDirty(state);
+}
+
+function _mveCancelEdit(state) {
+ state.draft = state.content;
+ state.preview = false;
+ _mveRenderView(state);
+ _mveEmitDraftChange(state, /* cleared = */ true);
+ _mveEmitDirty(state);
+}
+
+async function _mveSave(state) {
+ const ta = state.bodyEl.querySelector('[data-mve-textarea]');
+ if (ta) state.draft = ta.value;
+ const next = state.draft;
+ const res = await _mveWriteSource(state.source, next);
+ if (!res.ok) {
+ await uiAlert(t('contexts.save_failed_with', { reason: res.error || 'unknown' }));
+ return;
+ }
+ state.content = next;
+ state.preview = false;
+ _mveRenderView(state);
+ _mveEmitDraftChange(state, /* cleared = */ true);
+ _mveEmitDirty(state);
+ if (state.callbacks.onSaved) {
+ try { state.callbacks.onSaved(next); }
+ catch (e) { _mveLog.warn('onSaved threw', e); }
+ }
+}
+
+function _mveTogglePreview(state) {
+ const ta = state.bodyEl.querySelector('[data-mve-textarea]');
+ if (ta) state.draft = ta.value;
+ state.preview = !state.preview;
+ _mveEmitDraftChange(state);
+ _mveRenderEditor(state);
+}
+
+function _mveCopyDraft(state) {
+ const ta = state.bodyEl.querySelector('[data-mve-textarea]');
+ const text = ta ? ta.value : state.draft;
+ navigator.clipboard.writeText(text || '').catch(() => {});
+}
+
+function _mveSendDraftToChat(state) {
+ const ta = state.bodyEl.querySelector('[data-mve-textarea]');
+ const text = (ta ? ta.value : state.draft) || '';
+ if (state.callbacks.onSendToChatInput) {
+ try { state.callbacks.onSendToChatInput(text); }
+ catch (e) { _mveLog.warn('onSendToChatInput threw', e); }
+ }
+}
+
+// ── Task-checkbox view-mode interactivity ────────────────────────────────
+
+function _mveScanTaskLines(content) {
+ const lines = (content || '').split('\n');
+ const out = [];
+ for (let i = 0; i < lines.length; i++) {
+ const m = lines[i].match(_MVE_TODO_LINE_RE);
+ if (m) out.push({ lineIdx: i, checked: m[2].toLowerCase() === 'x' });
+ }
+ return out;
+}
+
+function _mveBindTaskCheckboxes(state, rootEl) {
+ if (!rootEl) return;
+ const tasks = _mveScanTaskLines(state.content);
+ const boxes = rootEl.querySelectorAll('.task-item input[type="checkbox"]');
+ if (boxes.length !== tasks.length) return;
+ boxes.forEach((box, i) => {
+ box.removeAttribute('disabled');
+ const li = box.closest('li.task-item');
+ if (tasks[i].checked && li) li.classList.add('is-done');
+ box.addEventListener('change', () => _mveToggleTask(state, tasks[i].lineIdx, li, box));
+ });
+}
+
+async function _mveToggleTask(state, lineIdx, liEl, boxEl) {
+ const lines = (state.content || '').split('\n');
+ const m = (lines[lineIdx] || '').match(_MVE_TODO_LINE_RE);
+ if (!m) return;
+ const wasChecked = m[2].toLowerCase() === 'x';
+ const nextMark = wasChecked ? ' ' : 'x';
+ lines[lineIdx] = `${m[1]}- [${nextMark}] ${m[3]}`;
+ const next = lines.join('\n');
+ if (liEl) liEl.classList.toggle('is-done', !wasChecked);
+ if (boxEl) boxEl.checked = !wasChecked;
+ const res = await _mveWriteSource(state.source, next);
+ if (!res.ok) {
+ if (liEl) liEl.classList.toggle('is-done', wasChecked);
+ if (boxEl) boxEl.checked = wasChecked;
+ await uiAlert(t('contexts.todo.save_failed', { reason: res.error || 'unknown' }));
+ return;
+ }
+ state.content = next;
+}
+
+// ── Toolbar / keyboard operations (textarea selection math) ─────────────
+
+function _mveWrapSelection(state, ta, mark, placeholder) {
+ const start = ta.selectionStart;
+ let end = ta.selectionEnd;
+ const value = ta.value;
+ while (end > start && value[end - 1] === '\n') end -= 1;
+ const sel = value.slice(start, end);
+ const before = value.slice(0, start);
+ const after = value.slice(end);
+ const markLen = mark.length;
+ if (sel.startsWith(mark) && sel.endsWith(mark) && sel.length >= markLen * 2) {
+ const inner = sel.slice(markLen, sel.length - markLen);
+ _mveReplaceRange(state, ta, start, end, inner, start, start + inner.length);
+ return;
+ }
+ if (before.endsWith(mark) && after.startsWith(mark)) {
+ const newStart = start - markLen;
+ const newEnd = end + markLen;
+ _mveReplaceRange(state, ta, newStart, newEnd, sel, newStart, newStart + sel.length);
+ return;
+ }
+ const inner = sel || placeholder;
+ const wrapped = `${mark}${inner}${mark}`;
+ const innerStart = start + markLen;
+ const innerEnd = innerStart + inner.length;
+ _mveReplaceRange(state, ta, start, end, wrapped, innerStart, innerEnd);
+}
+
+function _mveLineSpan(value, selStart, selEnd) {
+ let effEnd = selEnd;
+ if (effEnd > selStart && value[effEnd - 1] === '\n') effEnd -= 1;
+ const lineStart = value.lastIndexOf('\n', selStart - 1) + 1;
+ let lineEnd = value.indexOf('\n', effEnd);
+ if (lineEnd === -1) lineEnd = value.length;
+ return { lineStart, lineEnd };
+}
+
+function _mveApplyHeading(state, ta, level) {
+ const target = '#'.repeat(level) + ' ';
+ const value = ta.value;
+ const { lineStart, lineEnd } = _mveLineSpan(value, ta.selectionStart, ta.selectionEnd);
+ const block = value.slice(lineStart, lineEnd);
+ const lines = block.split('\n');
+ const stripHeading = (line) => line.replace(/^#{1,6} /, '');
+ const isTarget = (line) => line === '' || line.startsWith(target);
+ if (lines.every(isTarget)) {
+ const rebuilt = lines.map(stripHeading).join('\n');
+ _mveReplaceRange(state, ta, lineStart, lineEnd, rebuilt, lineStart, lineStart + rebuilt.length);
+ return;
+ }
+ const rebuilt = lines.map(line => line === '' ? line : `${target}${stripHeading(line)}`).join('\n');
+ _mveReplaceRange(state, ta, lineStart, lineEnd, rebuilt, lineStart, lineStart + rebuilt.length);
+}
+
+function _mveApplyTodo(state, ta) {
+ const value = ta.value;
+ const { lineStart, lineEnd } = _mveLineSpan(value, ta.selectionStart, ta.selectionEnd);
+ const block = value.slice(lineStart, lineEnd);
+ const lines = block.split('\n');
+ const placeholder = t('contexts.editor.placeholder.todo');
+ const firstNonEmpty = lines.find(l => l.trim().length > 0) || '';
+ let mode;
+ if (/^(\s*)- \[ \] /.test(firstNonEmpty)) mode = 'check';
+ else if (/^(\s*)- \[[xX]\] /.test(firstNonEmpty)) mode = 'strip';
+ else mode = 'mark';
+ const rebuilt = lines.map(line => {
+ if (line.trim().length === 0) return line;
+ const indent = (line.match(/^(\s*)/) || ['', ''])[1];
+ const rest = line.slice(indent.length);
+ if (mode === 'check') {
+ const m = rest.match(/^- \[ \] (.*)$/);
+ return m ? `${indent}- [x] ${m[1]}` : line;
+ }
+ if (mode === 'strip') {
+ return `${indent}${rest.replace(/^- \[[ xX]\] /, '')}`;
+ }
+ const body = rest.replace(/^([-*+]|\d+\.) +/, '') || placeholder;
+ return `${indent}- [ ] ${body}`;
+ }).join('\n');
+ _mveReplaceRange(state, ta, lineStart, lineEnd, rebuilt, lineStart, lineStart + rebuilt.length);
+}
+
+function _mveLinePrefix(state, ta, prefixFn) {
+ const value = ta.value;
+ const { lineStart, lineEnd } = _mveLineSpan(value, ta.selectionStart, ta.selectionEnd);
+ const block = value.slice(lineStart, lineEnd);
+ const lines = block.split('\n');
+ const firstPrefix = prefixFn(0);
+ const allMatch = lines.every(line => line.length === 0 || line.startsWith(firstPrefix));
+ let rebuilt;
+ if (allMatch && firstPrefix) {
+ rebuilt = lines.map(line => line.startsWith(firstPrefix) ? line.slice(firstPrefix.length) : line).join('\n');
+ } else {
+ rebuilt = lines.map((line, idx) => `${prefixFn(idx)}${line}`).join('\n');
+ }
+ _mveReplaceRange(state, ta, lineStart, lineEnd, rebuilt, lineStart, lineStart + rebuilt.length);
+}
+
+function _mveInsertBlock(state, ta, opts) {
+ const { text, selStart, selEnd } = opts;
+ const start = ta.selectionStart;
+ const end = ta.selectionEnd;
+ _mveReplaceRange(state, ta, start, end, text, start + selStart, start + selEnd);
+}
+
+function _mveReplaceRange(state, ta, from, to, replacement, newSelStart, newSelEnd) {
+ ta.setRangeText(replacement, from, to, 'preserve');
+ ta.selectionStart = newSelStart;
+ ta.selectionEnd = newSelEnd;
+ state.draft = ta.value;
+ _mveEmitDraftChange(state);
+ _mveEmitDirty(state);
+ ta.focus();
+}
+
+function _mveApplyMd(state, ta, kind) {
+ switch (kind) {
+ case 'bold': return _mveWrapSelection(state, ta, '**', t('contexts.editor.placeholder.bold'));
+ case 'italic': return _mveWrapSelection(state, ta, '*', t('contexts.editor.placeholder.italic'));
+ case 'strike': return _mveWrapSelection(state, ta, '~~', t('contexts.editor.placeholder.strike'));
+ case 'code': return _mveWrapSelection(state, ta, '`', t('contexts.editor.placeholder.code'));
+ case 'h1': return _mveApplyHeading(state, ta, 1);
+ case 'h2': return _mveApplyHeading(state, ta, 2);
+ case 'h3': return _mveApplyHeading(state, ta, 3);
+ case 'quote': return _mveLinePrefix(state, ta, () => '> ');
+ case 'ul': return _mveLinePrefix(state, ta, () => '- ');
+ case 'ol': return _mveLinePrefix(state, ta, (i) => `${i + 1}. `);
+ case 'todo': return _mveApplyTodo(state, ta);
+ case 'codeblock': {
+ const start = ta.selectionStart, end = ta.selectionEnd;
+ const sel = ta.value.slice(start, end);
+ const body = sel || t('contexts.editor.placeholder.code');
+ const before = ta.value.slice(0, start);
+ const after = ta.value.slice(end);
+ const leadNl = before.length === 0 || before.endsWith('\n\n') ? '' : (before.endsWith('\n') ? '\n' : '\n\n');
+ const tailNl = after.length === 0 || after.startsWith('\n\n') ? '' : (after.startsWith('\n') ? '\n' : '\n\n');
+ const text = `${leadNl}\`\`\`\n${body}\n\`\`\`${tailNl}`;
+ const innerStart = start + leadNl.length + 4; // after ```\n
+ const innerEnd = innerStart + body.length;
+ return _mveInsertBlock(state, ta, { text, selStart: innerStart - start, selEnd: innerEnd - start });
+ }
+ case 'link': {
+ const start = ta.selectionStart, end = ta.selectionEnd;
+ const sel = ta.value.slice(start, end);
+ const linkText = sel || t('contexts.editor.placeholder.link_text');
+ const url = t('contexts.editor.placeholder.link_url');
+ const text = `[${linkText}](${url})`;
+ const urlStart = 1 + linkText.length + 2; // after "[text]("
+ const urlEnd = urlStart + url.length;
+ return _mveInsertBlock(state, ta, { text, selStart: urlStart, selEnd: urlEnd });
+ }
+ case 'image': {
+ const start = ta.selectionStart, end = ta.selectionEnd;
+ const sel = ta.value.slice(start, end);
+ const alt = sel || t('contexts.editor.placeholder.image_alt');
+ const url = t('contexts.editor.placeholder.image_url');
+ const text = `![${alt}](${url})`;
+ const urlStart = 2 + alt.length + 2;
+ const urlEnd = urlStart + url.length;
+ return _mveInsertBlock(state, ta, { text, selStart: urlStart, selEnd: urlEnd });
+ }
+ }
+}
+
+function _mveParseListPrefix(line) {
+ const m = line.match(/^(\s*)([-*+]|\d+\.)(\s+)/);
+ if (!m) return null;
+ return { indent: m[1], marker: m[2], gap: m[3], total: m[0] };
+}
+
+function _mveOnKey(state, ta, e) {
+ // IME composition guard (CLAUDE.md §8).
+ if (e.isComposing || e.keyCode === 229) return;
+
+ const mod = e.metaKey || e.ctrlKey;
+ if (mod && !e.shiftKey && !e.altKey) {
+ const k = (e.key || '').toLowerCase();
+ if (k === 'b') { e.preventDefault(); return _mveApplyMd(state, ta, 'bold'); }
+ if (k === 'i') { e.preventDefault(); return _mveApplyMd(state, ta, 'italic'); }
+ if (k === 'k') { e.preventDefault(); return _mveApplyMd(state, ta, 'link'); }
+ if (k === 's' && state.caps.save) { e.preventDefault(); return _mveSave(state); }
+ }
+
+ if (e.key === 'Tab') {
+ e.preventDefault();
+ const start = ta.selectionStart;
+ const end = ta.selectionEnd;
+ const value = ta.value;
+ const multiLine = value.slice(start, end).includes('\n');
+ if (multiLine) {
+ const { lineStart, lineEnd } = _mveLineSpan(value, start, end);
+ const block = value.slice(lineStart, lineEnd);
+ const lines = block.split('\n');
+ let rebuilt;
+ if (e.shiftKey) {
+ rebuilt = lines.map(l => l.replace(/^( {1,2}|\t)/, '')).join('\n');
+ } else {
+ rebuilt = lines.map(l => ` ${l}`).join('\n');
+ }
+ _mveReplaceRange(state, ta, lineStart, lineEnd, rebuilt, lineStart, lineStart + rebuilt.length);
+ return;
+ }
+ if (e.shiftKey) {
+ const lineStart = value.lastIndexOf('\n', start - 1) + 1;
+ const head = value.slice(lineStart, lineStart + 2);
+ const strip = head === ' ' ? 2 : (head[0] === '\t' ? 1 : 0);
+ if (strip) {
+ const newStart = Math.max(lineStart, start - strip);
+ _mveReplaceRange(state, ta, lineStart, lineStart + strip, '', newStart, Math.max(newStart, end - strip));
+ }
+ return;
+ }
+ _mveReplaceRange(state, ta, start, end, ' ', start + 2, start + 2);
+ return;
+ }
+
+ if (e.key === 'Enter') {
+ const value = ta.value;
+ const start = ta.selectionStart;
+ const end = ta.selectionEnd;
+ if (start !== end) return;
+ const lineStart = value.lastIndexOf('\n', start - 1) + 1;
+ const lineSoFar = value.slice(lineStart, start);
+ const parsed = _mveParseListPrefix(lineSoFar);
+ if (!parsed) return;
+ if (lineSoFar === parsed.total) {
+ e.preventDefault();
+ _mveReplaceRange(state, ta, lineStart, start, '', lineStart, lineStart);
+ return;
+ }
+ e.preventDefault();
+ let nextMarker = parsed.marker;
+ if (/^\d+\.$/.test(parsed.marker)) {
+ const n = parseInt(parsed.marker, 10);
+ nextMarker = `${n + 1}.`;
+ }
+ const insert = `\n${parsed.indent}${nextMarker}${parsed.gap}`;
+ _mveReplaceRange(state, ta, start, start, insert, start + insert.length, start + insert.length);
+ return;
+ }
+}
+
+// ── Callback emission helpers ────────────────────────────────────────────
+
+function _mveEmitDirty(state) {
+ if (!state.callbacks.onDirtyChange) return;
+ try { state.callbacks.onDirtyChange(state.mode === 'edit' && state.draft !== state.content); }
+ catch (e) { _mveLog.warn('onDirtyChange threw', e); }
+}
+
+function _mveEmitDraftChange(state, cleared = false) {
+ if (!state.callbacks.onDraftChange) return;
+ try {
+ state.callbacks.onDraftChange(
+ cleared ? null : { content: state.draft, isPreview: state.preview }
+ );
+ } catch (e) { _mveLog.warn('onDraftChange threw', e); }
+}
+
+// CommonJS bridge for unit tests (CLAUDE.md §9 testability exception).
+if (typeof module !== 'undefined' && typeof module.exports === 'object') {
+ module.exports = {
+ _mveScanTaskLines,
+ _MVE_TODO_LINE_RE,
+ };
+}
diff --git a/src/renderer/modules/plan-rail.js b/src/renderer/modules/plan-rail.js
index 0fc6f785..ef28cfa3 100644
--- a/src/renderer/modules/plan-rail.js
+++ b/src/renderer/modules/plan-rail.js
@@ -140,6 +140,18 @@ function _refreshConversationInfo(cid) {
}
}
+function _beginConversationRecoveryStream(cid) {
+ const runtime = window.ConversationRuntime;
+ if (!runtime || typeof runtime.observePlanRecoveryRun !== 'function') return null;
+ try { return runtime.observePlanRecoveryRun(cid); }
+ catch (_) { return null; }
+}
+
+function _cancelConversationRecoveryStream(handle) {
+ try { if (handle && typeof handle.cancel === 'function') handle.cancel(); }
+ catch (_) {}
+}
+
async function _postStepAction(cid, stepIndex, action) {
const res = await apiFetch(
`/api/conversations/${encodeURIComponent(cid)}/plan/steps/${stepIndex}/${action}`,
@@ -188,7 +200,7 @@ function _buildStepHtml(step) {
const actions = _isStepActionable(step, _currentInFlight) && !actionRequested
? `<div class="plan-rail-step-actions">
<button type="button" class="btn btn-sm" data-action="retry" data-i18n="plan.action.retry">${escapeHtml(t('plan.action.retry'))}</button>
- <button type="button" class="btn btn-sm" data-action="skip" data-i18n="plan.action.skip">${escapeHtml(t('plan.action.skip') || 'Skip')}</button>
+ <button type="button" class="btn btn-sm" data-action="skip" data-i18n="plan.action.skip">${escapeHtml(t('plan.action.skip'))}</button>
<button type="button" class="btn btn-sm btn-danger" data-action="abort" data-i18n="plan.action.abort">${escapeHtml(t('plan.action.abort'))}</button>
</div>`
: '';
@@ -366,14 +378,21 @@ document.addEventListener('click', async (ev) => {
transient_attempts: 0,
},
});
+ const recoveryStream = _beginConversationRecoveryStream(cid);
+ let recoveryStarted = false;
try {
const data = await _postStepAction(cid, stepIndex, 'retry');
if (!data?.ok) {
_alertStepActionFailure('retry', data?.error);
+ _cancelConversationRecoveryStream(recoveryStream);
+ } else {
+ recoveryStarted = true;
}
} catch (err) {
+ _cancelConversationRecoveryStream(recoveryStream);
_alertStepActionFailure('retry', err && err.message);
} finally {
+ if (!recoveryStarted) _cancelConversationRecoveryStream(recoveryStream);
await _finishStepAction(cid, stepIndex, { refreshInfo: true, clearAfterRefresh: true });
}
return;
@@ -385,16 +404,22 @@ document.addEventListener('click', async (ev) => {
await _finishStepAction(cid, stepIndex, { rerender: true });
return;
}
+ const recoveryStream = _beginConversationRecoveryStream(cid);
+ let recoveryStarted = false;
try {
const data = await _postStepAction(cid, stepIndex, 'skip');
if (!data?.ok) {
_alertStepActionFailure('skip', data?.error);
+ _cancelConversationRecoveryStream(recoveryStream);
} else {
+ recoveryStarted = true;
_applyOptimisticStepStatus(cid, stepIndex, 'skipped');
}
} catch (err) {
+ _cancelConversationRecoveryStream(recoveryStream);
_alertStepActionFailure('skip', err && err.message);
} finally {
+ if (!recoveryStarted) _cancelConversationRecoveryStream(recoveryStream);
await _finishStepAction(cid, stepIndex, { refreshInfo: true, clearAfterRefresh: true });
}
return;
diff --git a/src/renderer/modules/project-detail.js b/src/renderer/modules/project-detail.js
index e05e2581..b6f4af97 100644
--- a/src/renderer/modules/project-detail.js
+++ b/src/renderer/modules/project-detail.js
@@ -13,7 +13,7 @@
const _projectDetailLog = createLogger('project-detail');
let _projectDetailPid = ''; // pid currently rendered in the panel
-let _projectDetailMeta = null; // { project, bindings, agentDetails, skillDetails }
+let _projectDetailMeta = null; // { project, agentDetails, skillDetails }
// ── Public: navigate-into ──────────────────────────────────────────────
@@ -34,7 +34,6 @@ async function loadProjectDetail(pid) {
}
_projectDetailMeta = {
project: getRes.project,
- bindings: listRes.bindings || { agents: [], skills: [] },
agentDetails: Array.isArray(listRes.agentDetails) ? listRes.agentDetails : [],
skillDetails: Array.isArray(listRes.skillDetails) ? listRes.skillDetails : [],
};
@@ -55,29 +54,23 @@ function _renderProjectDetailEmpty() {
function _renderProjectDetail() {
if (!_projectDetailMeta) { _renderProjectDetailEmpty(); return; }
- const { project, bindings, agentDetails, skillDetails } = _projectDetailMeta;
+ const { project, agentDetails, skillDetails } = _projectDetailMeta;
const titleEl = document.getElementById('project-detail-title');
if (titleEl) titleEl.textContent = project?.name || '';
- // Stale ids (binding referent missing — agent / skill was deleted).
- const agentValidIds = new Set(agentDetails.map((a) => a.agent_id));
- const skillValidIds = new Set(skillDetails.map((s) => s.id));
- const staleAgents = (bindings.agents || []).filter((id) => !agentValidIds.has(id));
- const staleSkills = (bindings.skills || []).filter((id) => !skillValidIds.has(id));
-
document.getElementById('project-agents-list').innerHTML = _renderBindingsRows(
- 'agent', agentDetails, staleAgents,
+ 'agent', agentDetails,
);
document.getElementById('project-skills-list').innerHTML = _renderBindingsRows(
- 'skill', skillDetails, staleSkills,
+ 'skill', skillDetails,
);
applyDomI18n();
_bindRemoveButtons();
}
-function _renderBindingsRows(kind, items, staleIds) {
+function _renderBindingsRows(kind, items) {
const lang = _activeLang();
const removeLabel = escapeHtml(t('project.bindings.remove'));
const sorted = (items || []).slice().sort(_byDisplayName);
@@ -101,19 +94,6 @@ function _renderBindingsRows(kind, items, staleIds) {
</div>
`);
}
- for (const id of staleIds) {
- rows.push(`
- <div class="project-binding-row project-binding-row--stale" data-kind="${kind}" data-id="${escapeHtml(id)}">
- <div class="project-binding-main">
- <div class="project-binding-head">
- <span class="project-binding-name">${escapeHtml(id)}</span>
- <span class="project-binding-source project-binding-source--stale" data-i18n="project.bindings.stale">Removed</span>
- </div>
- </div>
- <button type="button" class="btn btn-sm" data-action="remove">${removeLabel}</button>
- </div>
- `);
- }
if (!rows.length) {
const emptyKey = kind === 'agent' ? 'project.bindings.empty_agents' : 'project.bindings.empty_skills';
return `<div class="empty" data-i18n="${emptyKey}">${escapeHtml(t(emptyKey))}</div>`;
diff --git a/src/renderer/modules/queue-draft.js b/src/renderer/modules/queue-draft.js
index 863600c0..e1ec8180 100644
--- a/src/renderer/modules/queue-draft.js
+++ b/src/renderer/modules/queue-draft.js
@@ -4,8 +4,8 @@
// sent immediately. Queue is per-cid, persisted in localStorage so a refresh
// mid-stream doesn't drop pending messages. Drained one-by-one when the
// current reply finishes (or is aborted). Each entry records the raw user
-// text plus the selected skill — the "use skill X" prefix is applied at
-// dispatch time so a later skill change is reflected correctly.
+// text plus the selected skill / connector — the "use X" prefix is applied
+// at dispatch time so a later selection change is reflected correctly.
function _loadQueueFromStorage(cid) {
if (!cid) return [];
@@ -41,12 +41,30 @@ function _forgetConvLocal(cid) {
if (typeof _forgetCidRecipient === 'function') _forgetCidRecipient(cid);
}
-function enqueueMessage(cid, content, skill) {
+function _queueItemUseSelection(item) {
+ if (!item) return null;
+ if (item.use && typeof _normalizeChatUseSelection === 'function') {
+ return _normalizeChatUseSelection(item.use);
+ }
+ if (item.skill && typeof _normalizeChatUseSelection === 'function') {
+ return _normalizeChatUseSelection({ kind: 'skill', id: item.skill, name: item.skill });
+ }
+ return null;
+}
+
+function enqueueMessage(cid, content, useSelection, opts = {}) {
const q = _getQueue(cid);
+ const extra = opts && opts.extra && typeof opts.extra === 'object' ? opts.extra : null;
+ const use = typeof _normalizeChatUseSelection === 'function'
+ ? _normalizeChatUseSelection(useSelection)
+ : null;
q.push({
id: `q${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
content,
- skill: skill || '',
+ use: use || null,
+ skill: use && use.kind === 'skill' ? (use.name || use.id || '') : '',
+ direct: !!(opts && opts.direct),
+ ...(extra ? { extra } : {}),
});
_saveQueueToStorage(cid);
_updateConvSidebarBadge(cid);
@@ -103,15 +121,17 @@ function _dispatchNextQueued(cid) {
_saveQueueToStorage(cid);
_updateConvSidebarBadge(cid);
renderMessageQueue(cid);
- // Skill is an inline text prefix (applied at dispatch time so later skill
- // changes take effect). Agent runs are just "run <name>" text — no flag.
+ // Skill / connector is an inline text prefix (applied at dispatch time so
+ // later selection changes take effect). Agent runs are just "run <name>"
+ // text — no flag.
// Recipient prefix (`@<agent>`) is also applied at dispatch time so the
// message routes to whoever is currently selected in the chip.
- const withSkill = next.skill ? transformWithSkill(next.content, next.skill) : next.content;
- const content = applyRecipientPrefix(withSkill, 'conversation');
+ const use = _queueItemUseSelection(next);
+ const withUse = use ? transformWithChatUse(next.content, use) : next.content;
+ const content = next.direct ? next.content : applyRecipientPrefix(withUse, 'conversation');
// Fire-and-forget: sendInCurrentConversation handles its own errors via
// _streamingSetError + _finishStreamingMsg (which will re-enter this fn).
- sendInCurrentConversation(content);
+ sendInCurrentConversation(content, next.extra);
}
function renderMessageQueue(cid) {
@@ -129,13 +149,14 @@ function renderMessageQueue(cid) {
panel.style.display = '';
if (countEl) countEl.textContent = String(q.length);
list.innerHTML = q.map(item => {
- const skillChip = item.skill
- ? `<span class="chat-queue-skill">${escapeHtml(item.skill)}</span>` : '';
+ const use = _queueItemUseSelection(item);
+ const useChip = use
+ ? `<span class="chat-queue-skill">${escapeHtml(formatChatUseLabel(use))}</span>` : '';
const preview = escapeHtml((item.content || '').replace(/\s+/g, ' ')).slice(0, 200);
return `
<div class="chat-queue-item" draggable="true" data-qid="${item.id}">
<div class="chat-queue-drag" title="${escapeHtml(t('chat.queue_drag_title'))}">⋮⋮</div>
- <div class="chat-queue-text">${skillChip}${preview}</div>
+ <div class="chat-queue-text">${useChip}${preview}</div>
<div class="chat-queue-actions">
<button class="chat-queue-btn" data-act="edit">${escapeHtml(t('chat.queue_edit'))}</button>
<button class="chat-queue-btn danger" data-act="del">×</button>
@@ -243,8 +264,8 @@ function _startQueueItemEdit(cid, row) {
// ─── Input draft persistence (per-conversation) ───
//
// Typed-but-unsent text is bound to the conversation id and survives tab
-// switches, panel navigation, and reloads. The selected skill chip for the
-// conversation input is persisted alongside so it's restored too.
+// switches, panel navigation, and reloads. The selected skill / connector
+// chip for the conversation input is persisted alongside so it's restored too.
let _draftSaveTimer = null;
@@ -254,10 +275,14 @@ function _saveDraft(cid) {
_draftSaveTimer = setTimeout(() => {
const input = document.getElementById('chat-input');
const text = input ? input.value : '';
- const skill = _chatSkill['conversation'] || '';
+ const use = getChatUseSelection('conversation');
try {
- if (text || skill) {
- localStorage.setItem(_DRAFT_KEY(cid), JSON.stringify({ text, skill }));
+ if (text || use) {
+ localStorage.setItem(_DRAFT_KEY(cid), JSON.stringify({
+ text,
+ use,
+ skill: use && use.kind === 'skill' ? (use.name || use.id || '') : '',
+ }));
} else {
localStorage.removeItem(_DRAFT_KEY(cid));
}
@@ -280,10 +305,13 @@ function _restoreDraft(cid) {
data = raw ? JSON.parse(raw) : null;
} catch (_) {}
const text = (data && typeof data.text === 'string') ? data.text : '';
- const skill = (data && typeof data.skill === 'string') ? data.skill : '';
+ const use = data && data.use
+ ? data.use
+ : ((data && typeof data.skill === 'string' && data.skill)
+ ? { kind: 'skill', id: data.skill, name: data.skill }
+ : null);
input.value = text;
autoGrow(input, 200);
- // Apply or clear the skill chip without re-persisting the draft (no input event fires).
- setChatSkill('conversation', skill);
+ // Apply or clear the chip without re-persisting the draft (no input event fires).
+ setChatUseSelection('conversation', use);
}
-
diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.js
index 353efe75..bd994714 100644
--- a/src/renderer/modules/settings.js
+++ b/src/renderer/modules/settings.js
@@ -28,6 +28,7 @@ async function loadSettings() {
if (typeof initSettingsTabs === 'function') initSettingsTabs();
_settingsBindLanguageOnce();
_settingsBindAppUpdateOnce();
+ if (typeof initFeedbackSettings === 'function') initFeedbackSettings();
_settingsSyncLanguageRadio();
_settingsBindClearAllConvsOnce();
await Promise.all([
diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.js
index f40daf09..f6610c47 100644
--- a/src/renderer/modules/skills.js
+++ b/src/renderer/modules/skills.js
@@ -3,6 +3,11 @@ 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 _normalizeSkillCategoryForHiddenSave(category) {
+ const code = String(category || '').trim().toLowerCase();
+ return _SKILL_SPEC_CATEGORY_CODE_RE.test(code) ? code : 'general';
+}
function _skillUiIconHtml(name, className) {
if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {
@@ -40,6 +45,7 @@ function _skillPlatformChipsHtml(s) {
// `selectSkillFile` so the SKILL.md frontmatter re-parses and the description picks the
// right locale via `_renderSkillSections`.
window.addEventListener('i18n-change', () => {
+ refreshChatUseChips();
if (_skillsCache) renderSkillsGrid(_skillsCache);
if (_selectedSkill?.id && _selectedSkill?.source) {
// Re-read the same file the user was viewing; null nodeEl preserves
@@ -51,6 +57,24 @@ window.addEventListener('i18n-change', () => {
let _expandedDirs = new Set(); // keys like "source:id" or "source:id/subdir"
let _skillTreeCache = new Map(); // key: "source:id" → tree array
+async function refreshSkillsAfterMarketplaceReconcile() {
+ _skillTreeCache.clear();
+ await loadSkills(true);
+ if (_skillEditMode) return;
+ if (_selectedSkill?.id && _selectedSkill.source === 'builtin') {
+ const source = _selectedSkill.source;
+ const id = _selectedSkill.id;
+ const filepath = _selectedSkill.filepath || 'SKILL.md';
+ await selectSkillFile(source, id, filepath, null);
+ const toggle = document.getElementById('skills-source-toggle');
+ const treeEl = document.getElementById('skills-source-tree');
+ if (toggle?.getAttribute('aria-expanded') === 'true' && treeEl) {
+ await expandSkillTree(source, id, treeEl);
+ _markActiveSkillFileInTree(filepath);
+ }
+ }
+}
+
async function loadSkills(forceRefresh) {
if (_skillsCache && !forceRefresh) { renderSkillsList(_skillsCache); return; }
try {
@@ -65,15 +89,13 @@ async function loadSkills(forceRefresh) {
}
}
-// ─── Chat-input skill chip ───────────────────────────────────────────────
+// ─── Chat-input tool chip ────────────────────────────────────────────────
//
-// The chat composer no longer surfaces a skill-picker button (or shortcut).
-// The chip pill is still used to display a skill that was attached
-// programmatically by the "use skill" flow (▶ on a skill card → useSkill →
-// setChatSkill). Clicking × removes the chip. On send, the chip's name is
-// prepended to the message as `use skill <name>: <content>`.
+// The composer exposes one reusable "use X" chip. Skills and connectors are
+// mutually exclusive because both are textual routing hints prepended to the
+// next message; agents remain separate in the recipient chip.
-const _chatSkill = { 'new-chat': '', 'conversation': '' };
+const _chatUse = { 'new-chat': null, 'conversation': null };
function bindSkillPicker() {
// Chip remove (×)
@@ -81,39 +103,131 @@ function bindSkillPicker() {
el.addEventListener('click', (e) => {
e.stopPropagation();
const chip = el.closest('.chat-skill-chip');
- if (chip) setChatSkill(chip.dataset.target, '');
+ if (chip) setChatUseSelection(chip.dataset.target, null);
});
});
}
-function setChatSkill(target, name) {
- const prev = _chatSkill[target] || '';
- _chatSkill[target] = name || '';
- if (target === 'conversation' && prev !== _chatSkill[target] && currentCid) {
- _saveDraft(currentCid);
+function _normalizeChatUseSelection(value) {
+ if (!value) return null;
+ if (typeof value === 'string') {
+ const name = value.trim();
+ return name ? { kind: 'skill', id: name, name } : null;
}
+ if (typeof value !== 'object') return null;
+ const kind = value.kind === 'connector' ? 'connector' : (value.kind === 'skill' ? 'skill' : '');
+ if (!kind) return null;
+ const name = String(value.name || value.id || '').trim();
+ const id = String(value.id || name).trim();
+ if (!name && !id) return null;
+ return { kind, id: id || name, name: name || id };
+}
+
+function getChatUseSelection(target) {
+ const cur = _normalizeChatUseSelection(_chatUse[target]);
+ return cur ? { ...cur } : null;
+}
+
+function formatChatUseLabel(selection) {
+ const sel = _normalizeChatUseSelection(selection);
+ if (!sel) return '';
+ if (sel.kind === 'connector') return t('connectors.use_label', { connector: sel.name || sel.id });
+ return t('skills.use_label', { skill: sel.name || sel.id });
+}
+
+function _chatUseLabelParts(selection) {
+ const sel = _normalizeChatUseSelection(selection);
+ if (!sel) return null;
+ const name = sel.name || sel.id;
+ const token = sel.kind === 'connector' ? 'connector' : 'skill';
+ const key = sel.kind === 'connector' ? 'connectors.use_label' : 'skills.use_label';
+ return {
+ name,
+ label: t(key, { [token]: name }),
+ prefix: t(key, { [token]: '' }),
+ };
+}
+
+function _renderChatUseChipLabel(labelEl, selection) {
+ if (!labelEl) return;
+ labelEl.textContent = '';
+ labelEl.removeAttribute('title');
+ const parts = _chatUseLabelParts(selection);
+ if (!parts) return;
+
+ const prefixEl = document.createElement('span');
+ prefixEl.className = 'chip-label-prefix';
+ prefixEl.textContent = parts.prefix;
+
+ const nameEl = document.createElement('span');
+ nameEl.className = 'chip-label-name';
+ nameEl.textContent = parts.name;
+
+ labelEl.append(prefixEl, nameEl);
+ labelEl.title = parts.label;
+}
+
+function _renderChatUseChip(target) {
+ const next = _normalizeChatUseSelection(_chatUse[target]);
const chipId = target === 'new-chat' ? 'new-chat-skill-chip' : 'chat-skill-chip';
const chip = document.getElementById(chipId);
if (!chip) return;
- if (!name) {
+ if (!next) {
chip.style.display = 'none';
+ chip.classList.remove('is-skill', 'is-connector');
+ delete chip.dataset.kind;
+ delete chip.dataset.itemId;
const lbl = chip.querySelector('.chip-label');
- if (lbl) lbl.textContent = '';
+ _renderChatUseChipLabel(lbl, null);
return;
}
chip.style.display = 'inline-flex';
+ chip.classList.toggle('is-skill', next.kind === 'skill');
+ chip.classList.toggle('is-connector', next.kind === 'connector');
+ chip.dataset.kind = next.kind;
+ chip.dataset.itemId = next.id || '';
const lbl = chip.querySelector('.chip-label');
- if (lbl) lbl.textContent = name;
- // Return focus to the textarea after selection
+ _renderChatUseChipLabel(lbl, next);
+}
+
+function refreshChatUseChips() {
+ _renderChatUseChip('new-chat');
+ _renderChatUseChip('conversation');
+}
+
+function setChatUseSelection(target, selection) {
+ const prev = JSON.stringify(_normalizeChatUseSelection(_chatUse[target]) || null);
+ const next = _normalizeChatUseSelection(selection);
+ _chatUse[target] = next;
+ if (target === 'conversation' && prev !== JSON.stringify(next || null) && currentCid) {
+ _saveDraft(currentCid);
+ }
+ _renderChatUseChip(target);
+ // Return focus to the textarea after selection.
const input = target === 'new-chat'
? document.getElementById('new-chat-input')
: document.getElementById('chat-input');
input?.focus();
}
+function setChatSkill(target, name) {
+ setChatUseSelection(target, name ? { kind: 'skill', id: name, name } : null);
+}
+
+function setChatConnector(target, connectorId, connectorName) {
+ const id = String(connectorId || connectorName || '').trim();
+ const name = String(connectorName || connectorId || '').trim();
+ setChatUseSelection(target, id || name ? { kind: 'connector', id: id || name, name: name || id } : null);
+}
+
function consumeChatSkill(target) {
+ const sel = getChatUseSelection(target);
+ return sel && sel.kind === 'skill' ? (sel.name || sel.id) : '';
+}
+
+function consumeChatUseSelection(target) {
// Currently a one-way read. Chip persists until user removes it via the ×.
- return _chatSkill[target] || '';
+ return getChatUseSelection(target);
}
function transformWithSkill(content, skill) {
@@ -121,6 +235,15 @@ function transformWithSkill(content, skill) {
return t('skills.use_prefix', { skill, content });
}
+function transformWithChatUse(content, selection) {
+ const sel = _normalizeChatUseSelection(selection);
+ if (!sel) return content;
+ if (sel.kind === 'connector') {
+ return t('connectors.use_prefix', { connector: sel.name || sel.id, content });
+ }
+ return transformWithSkill(content, sel.name || sel.id);
+}
+
function renderSkillsList(skills) { renderSkillsGrid(skills); }
function renderSkillsGrid(skills) {
@@ -1262,15 +1385,6 @@ async function openSkillModal(editId) {
_switchSkillTab('manual');
}
- // Marketplace category dropdown (manual tab). Edit mode pre-fills from cached category;
- // create mode picks the first entry as default. 24h cached in main with fallback list.
- if (typeof mountMarketplaceCategorySelect === 'function') {
- const initial = editId
- ? (_skillsCache?.find((s) => s.id === editId && s.source === 'custom')?.category || '')
- : '';
- mountMarketplaceCategorySelect('skill-category-select', initial).catch(() => {});
- }
-
// Wire tab buttons (idempotent — checks a flag)
if (tabBar && !tabBar.dataset.wired) {
tabBar.querySelectorAll('.skill-modal-tab').forEach((btn) => {
@@ -1329,7 +1443,6 @@ window.saveSkill = saveSkill;
async function _saveSkillManual({ editId, msgEl }) {
const name = document.getElementById('skill-name').value.trim();
const description = document.getElementById('skill-description').value.trim();
- const category = document.getElementById('skill-category-select')?.dataset.value || '';
if (!name) {
msgEl.textContent = t('skills.input_name_needed');
msgEl.className = 'form-msg err';
@@ -1343,6 +1456,8 @@ async function _saveSkillManual({ editId, msgEl }) {
return;
}
try {
+ const cached = editId ? _skillsCache?.find((s) => s.id === editId && s.source === 'custom') : null;
+ const category = _normalizeSkillCategoryForHiddenSave(cached?.category);
const res = editId
? await apiFetch(`/api/skills/${editId}/update`, {
method: 'PUT',
diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.js
index dbdabe4b..ddc4e372 100644
--- a/src/renderer/modules/state.js
+++ b/src/renderer/modules/state.js
@@ -67,15 +67,42 @@ function startPolling(cid) {
const res = await apiFetch(`/api/conversations/${cid}/history?limit=500`);
const data = await res.json();
if (!data.ok || !data.history) return;
- const msgs = data.history;
+ const msgs = data.history.filter((m) => !(m && m.dispatch));
const last = msgs[msgs.length - 1];
const known = pollMsgCounts.get(cid) || 0;
+ const hasServerRuntime = !!data.conversation
+ && Object.prototype.hasOwnProperty.call(data.conversation, 'processing');
+ const runtimeBusy = hasServerRuntime
+ ? data.conversation.processing === true
+ : isGroupConversationBusy(cid);
+ if (runtimeBusy && cid === currentCid && window.PlanRail) {
+ try { window.PlanRail.refresh(cid, { force: true }); } catch (_) {}
+ }
if (msgs.length > known && _isPolledAssistantMsg(last)) {
- // New assistant message arrived
+ // New visible assistant message arrived. During plan execution this
+ // may be a mid-turn announcement while other actors are still
+ // running; reloading history then detaches live placeholders and
+ // makes bubbles flash. Treat polling as rescue only once runtime is
+ // idle; the live stream owns in-flight DOM updates.
+ if (runtimeBusy) {
+ const recovered = await window.ConversationRuntime?.recoverPolledMessages?.(cid, msgs);
+ if (recovered) pollMsgCounts.set(cid, msgs.length);
+ return;
+ }
+ pollMsgCounts.set(cid, msgs.length);
+ stopPolling(cid);
+ _onPolledResponse(cid, last);
+ return;
+ }
+
+ // Local busy state can outlive the IPC stream if the renderer missed the
+ // terminal state_changed event. Once main says runtime is idle, use the
+ // persisted last assistant message to settle any leftover placeholder.
+ if (!runtimeBusy && isConvPending(cid) && _isPolledAssistantMsg(last)) {
pollMsgCounts.set(cid, msgs.length);
stopPolling(cid);
- _onPolledResponse(cid, last.text);
+ _onPolledResponse(cid, last);
return;
}
@@ -107,7 +134,11 @@ function stopPolling(cid) {
if (t) { clearInterval(t); pollTimers.delete(cid); }
}
-function _onPolledResponse(cid, content, isError = false) {
+function _onPolledResponse(cid, contentOrMessage, isError = false) {
+ const polledMessage = contentOrMessage && typeof contentOrMessage === 'object'
+ ? contentOrMessage
+ : null;
+ const content = polledMessage ? (polledMessage.text || '') : contentOrMessage;
const state = pendingConvs.get(cid);
pendingConvs.delete(cid);
setGroupConversationBusy(cid, false);
@@ -129,7 +160,25 @@ function _onPolledResponse(cid, content, isError = false) {
&& finalEl.style.display !== 'none'
&& (finalEl.textContent || '').trim().length > 0;
if (alreadyFinalized) {
- // Stream already finalized this bubble in place — leave it alone.
+ // Stream already finalized this bubble in place. Leave it alone only
+ // when polling is reporting the same persisted message. If polling saw a
+ // later assistant record (common for plan-generated user forms emitted
+ // right after the commander's plan card), reload history so sidecar
+ // fields like `form` are mounted instead of silently disappearing.
+ const finalizedId = el.dataset.msgId || '';
+ const polledId = polledMessage?.id || '';
+ const sidecarMissing = !!polledMessage && (
+ (polledMessage.form && !el.querySelector('.chat-input-form'))
+ || (Array.isArray(polledMessage.produced) && polledMessage.produced.length && !el.querySelector('.chat-msg-produced'))
+ || (polledMessage.plan_announcement && !el.querySelector('.chat-plan-announce'))
+ );
+ if (polledId && (finalizedId !== polledId || sidecarMissing)) {
+ if (cid === currentCid) {
+ loadConversationHistory(cid);
+ _updateConvSendUI(cid);
+ }
+ return;
+ }
if (cid === currentCid) _updateConvSendUI(cid);
return;
}
diff --git a/src/renderer/modules/strip-structural-blocks.js b/src/renderer/modules/strip-structural-blocks.js
index d07d5c25..de5df558 100644
--- a/src/renderer/modules/strip-structural-blocks.js
+++ b/src/renderer/modules/strip-structural-blocks.js
@@ -26,12 +26,13 @@
// `chat_skill_setup.md` chose `<<<>>>` for file blocks).
//
// Both families share the same prose/code guard — if any of them is
-// mentioned literally inside a fenced code block or inline backtick span
-// (e.g., a protocol explanation), the literal mention must survive; the
-// real container must still be stripped/replaced atomically even when its
-// body contains backticks / fences / quotes (otherwise the prose/code split
-// fragments the container and the post-fragment suffix leaks past — the
-// 34e27fcb / a3110e61 / follow-up cycle on `<agent>`).
+// mentioned literally inside a non-XML fenced code block, inline backtick
+// span, or inline quoted sentence (e.g., a protocol explanation), the
+// literal mention must survive. Explicit ```xml fences remain structural
+// output. Real containers must still be stripped/replaced atomically even
+// when their body contains backticks / fences / quotes (otherwise the
+// prose/code split fragments the container and the post-fragment suffix
+// leaks past — the 34e27fcb / a3110e61 / follow-up cycle on `<agent>`).
//
// Lives in a standalone file so vitest can `require()` it under Node and
// pin the set-A vs set-B invariants — regressions in this category aren't
@@ -49,9 +50,11 @@
// backtick spans; everything else is prose. Used by the `<agent>` container
// strippers so coding scenarios — where the LLM legitimately quotes `<agent>`
// inside a code sample to explain how this app's structured-output protocol
-// works — don't see the bubble silently truncated. Mid-stream unclosed fences
-// and unclosed inline backticks are treated as code through end-of-buffer,
-// matching how the markdown renderer would paint them.
+// works — don't see the bubble silently truncated. Fenced blocks with an
+// `xml` info string carry `xmlFence: true` so structural parsers can still
+// process them. Mid-stream unclosed fences and unclosed inline backticks are
+// treated as code through end-of-buffer, matching how the markdown renderer
+// would paint them.
function _splitMarkdownProseCode(text) {
const segs = [];
if (!text) return segs;
@@ -74,6 +77,8 @@ function _splitMarkdownProseCode(text) {
if (count >= 3) {
let k = j + count;
while (k < n && text[k] !== '\n') k++;
+ const info = text.slice(j + count, k).trim().toLowerCase();
+ const xmlFence = /^xml(?:\s|$)/.test(info);
let scan = k < n ? k + 1 : n;
let close = -1;
while (scan < n) {
@@ -95,7 +100,7 @@ function _splitMarkdownProseCode(text) {
}
flushProse(i);
const endIdx = close >= 0 ? close : n;
- segs.push({ kind: 'code', text: text.slice(i, endIdx) });
+ segs.push({ kind: 'code', text: text.slice(i, endIdx), xmlFence });
proseStart = endIdx;
i = endIdx;
continue;
@@ -136,6 +141,46 @@ function _splitMarkdownProseCode(text) {
return segs;
}
+function _isInsideQuotedSpanOnLine(text, idx) {
+ const lineStart = text.lastIndexOf('\n', Math.max(0, idx - 1)) + 1;
+ const nextNl = text.indexOf('\n', idx);
+ const lineEnd = nextNl < 0 ? text.length : nextNl;
+ const linePrefix = text.slice(lineStart, idx);
+ const hasClosingAsciiDouble = text.indexOf('"', idx) >= 0 && text.indexOf('"', idx) < lineEnd;
+ if (hasClosingAsciiDouble) {
+ let open = false;
+ for (let i = 0; i < linePrefix.length; i++) {
+ if (linePrefix[i] !== '"') continue;
+ if (i > 0 && linePrefix[i - 1] === '\\') continue;
+ open = !open;
+ }
+ if (open) return true;
+ }
+
+ for (const [openQuote, closeQuote] of [['“', '”'], ['‘', '’'], ['「', '」'], ['『', '』'], ['《', '》']]) {
+ const lastOpen = text.lastIndexOf(openQuote, idx - 1);
+ if (lastOpen < lineStart) continue;
+ const lastClose = text.lastIndexOf(closeQuote, idx - 1);
+ const nextClose = text.indexOf(closeQuote, idx);
+ if (lastOpen > lastClose && nextClose >= 0 && nextClose < lineEnd) return true;
+ }
+ return false;
+}
+
+function _isLineStartOpening(text, idx) {
+ const lineStart = text.lastIndexOf('\n', Math.max(0, idx - 1)) + 1;
+ for (let i = lineStart; i < idx; i++) {
+ const ch = text[i];
+ if (ch === ' ' || ch === '\t' || ch === '"' || ch === '\'' || ch === '“' || ch === '‘' || ch === '「' || ch === '『' || ch === '《') continue;
+ return false;
+ }
+ return true;
+}
+
+function _isInlineQuotedOpening(text, idx) {
+ return _isInsideQuotedSpanOnLine(text, idx) && !_isLineStartOpening(text, idx);
+}
+
// Find every `<TAG>...</TAG>` (or unclosed `<TAG>...EOF`) range whose
// OPENING tag falls in an outer prose segment. The tagged container is
// treated as one atomic unit — once the opening tag is in prose, we walk
@@ -143,8 +188,8 @@ function _splitMarkdownProseCode(text) {
// backticks / fences / quotes authored inside the body don't fragment
// the container and let the post-fragment suffix (often including the
// closing tag) leak past the stripper. The outer-context check still
-// preserves literal mentions of the tag inside fenced code / inline
-// backtick spans (coding-explanation case).
+// preserves literal mentions of the tag inside non-XML fenced code, inline
+// backtick spans, and inline quoted sentences (coding-explanation case).
//
// Generalized over `tagName` so the same atomic-container guarantee
// covers `<agent>` (commander create/edit container), `<agent-input-form>`
@@ -168,7 +213,7 @@ function _findOuterTagRanges(text, tagName) {
for (const seg of segs) {
const segStart = pos;
pos += seg.text.length;
- if (seg.kind !== 'prose') continue;
+ if (seg.kind !== 'prose' && !seg.xmlFence) continue;
let from = segStart;
while (from < pos) {
const last = ranges.length ? ranges[ranges.length - 1] : null;
@@ -186,6 +231,13 @@ function _findOuterTagRanges(text, tagName) {
from = openIdx + openLeader.length;
continue;
}
+ // Inline quoted explanations survive (`请输出 "<skill>...</skill>"`).
+ // A line that starts with quoted XML still counts as a deliberate
+ // structure block and is processed.
+ if (!seg.xmlFence && _isInlineQuotedOpening(text, openIdx)) {
+ from = openIdx + openLeader.length;
+ continue;
+ }
// Walk past attributes to the closing `>` of the open tag, then to
// `</tagName>` (or EOF). Unclosed open-tag mid-stream → swallow rest
// of buffer atomically.
@@ -262,7 +314,7 @@ function _replaceOuterAgentBlocks(buf, placeholder) {
// but if the main extractor misses a variant the raw XML lands in the
// bubble alongside the widget. Strip silently rather than render raw.
// - `<agent-input-submission>` — user form-reply tag; user-side render
-// already strips it via _stripSubmissionTagForDisplay, but if it ever
+// already strips it via _stripUserStructuralBlocksForDisplay, but if it ever
// leaks into assistant text (LLM hallucination / quoting), strip too.
//
// Each tag is removed independently via the same atomic-container helper
@@ -280,21 +332,24 @@ function _replaceOuterAgentBlocks(buf, placeholder) {
// `SKILL_FILE_BLOCK_RE` in `features/skills.ts`).
//
// Outer-context check (prose vs code segment) is shared with the tag
-// finder: a literal `<<<skill-file` mentioned inside a fenced code block
-// or inline backtick (LLM showing the protocol to a user) must NOT be
-// recognised as a real block.
+// finder: a literal `<<<skill-file` mentioned inside a non-XML fenced code
+// block, inline backtick, or inline quoted sentence (LLM showing the
+// protocol to a user) must NOT be recognised as a real block. Explicit
+// ```xml fences are treated as machine output.
const SKILL_FILE_OPEN = '<<<skill-file';
const SKILL_FILE_CLOSE = '\n>>>';
-function _findOuterSkillFileRanges(text) {
+function _findSkillFileRanges(text, { respectCodeGuard = true } = {}) {
if (!text || text.indexOf(SKILL_FILE_OPEN) < 0) return [];
- const segs = _splitMarkdownProseCode(text);
+ const segs = respectCodeGuard
+ ? _splitMarkdownProseCode(text)
+ : [{ kind: 'prose', text }];
const ranges = [];
let pos = 0;
for (const seg of segs) {
const segStart = pos;
pos += seg.text.length;
- if (seg.kind !== 'prose') continue;
+ if (seg.kind !== 'prose' && !seg.xmlFence) continue;
let from = segStart;
while (from < pos) {
const last = ranges.length ? ranges[ranges.length - 1] : null;
@@ -302,6 +357,10 @@ function _findOuterSkillFileRanges(text) {
if (from >= pos) break;
const openIdx = text.indexOf(SKILL_FILE_OPEN, from);
if (openIdx < 0 || openIdx >= pos) break;
+ if (!seg.xmlFence && _isInlineQuotedOpening(text, openIdx)) {
+ from = openIdx + SKILL_FILE_OPEN.length;
+ continue;
+ }
// Mirror agent's atomic-container guarantee: once the opener is in an
// outer prose segment, walk to `\n>>>` regardless of what's inside
// (file content can contain backticks, inline code, fences, anything).
@@ -316,6 +375,14 @@ function _findOuterSkillFileRanges(text) {
return ranges;
}
+function _findOuterSkillFileRanges(text) {
+ return _findSkillFileRanges(text, { respectCodeGuard: true });
+}
+
+function _findAnySkillFileRanges(text) {
+ return _findSkillFileRanges(text, { respectCodeGuard: false });
+}
+
function _stripOuterSkillFileBlocks(text) {
if (!text) return text;
const ranges = _findOuterSkillFileRanges(text);
@@ -330,6 +397,21 @@ function _stripOuterSkillFileBlocks(text) {
return out;
}
+function _replaceAnySkillFileBlocks(buf, replacement) {
+ if (!buf) return buf;
+ const ranges = _findAnySkillFileRanges(buf);
+ if (!ranges.length) return buf;
+ let out = '';
+ let cursor = 0;
+ for (const [s, e] of ranges) {
+ out += buf.slice(cursor, s);
+ out += replacement;
+ cursor = e;
+ }
+ out += buf.slice(cursor);
+ return out;
+}
+
// Pull the `path=X` attribute value out of a captured block — used by the
// streaming placeholder so the user sees "writing <basename>…" instead of
// a generic "writing file…". Tolerant of attribute order; quotes are not
@@ -378,10 +460,18 @@ function _stripSkillCreateContainer(buf, fallbackPlaceholder) {
out += buf.slice(cursor, s);
const block = buf.slice(s, e);
if (block.endsWith('</skill>')) {
- out += block
+ const inner = block
.replace(/^<skill>\s*/, '')
.replace(/\s*<\/skill>$/, '')
.replace(/<skill_id>[\s\S]*?<\/skill_id>\s*/g, '');
+ // The normal streaming pipeline replaces `<<<skill-file>>>` blocks
+ // before this function runs. Some models wrap those machine blocks
+ // inside a Markdown fence or otherwise leave one behind before this
+ // pass sees it. Even if an earlier pass misses the block, the
+ // surrounding `<skill>` container tells us this is real machine output.
+ // Inside a real container there are no user-visible examples: any
+ // surviving skill-file block is machine output and must be hidden.
+ out += _replaceAnySkillFileBlocks(inner, fallbackPlaceholder);
} else {
out += fallbackPlaceholder;
}
@@ -410,6 +500,95 @@ function _stripSurvivingStructuralBlocks(text) {
return out.replace(/\n{3,}/g, '\n\n').trim();
}
+function _stripSubmissionRoutingMentionForDisplay(text) {
+ if (!text) return text;
+ return String(text).replace(/^@[^\r\n]+[ \t]*(?:\r?\n|$)/, '').trimStart();
+}
+
+function _stripUserStructuralBlocksForDisplay(text) {
+ if (!text) return text;
+ let out = text;
+
+ const afterSubmission = _stripOuterTagBlocks(out, 'agent-input-submission');
+ if (afterSubmission !== out) {
+ out = _stripSubmissionRoutingMentionForDisplay(afterSubmission)
+ .replace(/\n{3,}/g, '\n\n')
+ .trimEnd();
+ }
+
+ const afterArtifact = _stripOuterTagBlocks(out, 'artifact-result');
+ if (afterArtifact !== out) {
+ out = afterArtifact.replace(/\n{3,}/g, '\n\n').trimEnd();
+ }
+
+ const afterMarketplace = _stripOuterTagBlocks(out, 'marketplace-install-result');
+ if (afterMarketplace !== out) {
+ out = afterMarketplace.replace(/\n{3,}/g, '\n\n').trimEnd();
+ }
+
+ return out;
+}
+
+function _buildSkillDisplayNameById(skills) {
+ const out = new Map();
+ if (!Array.isArray(skills)) return out;
+ for (const skill of skills) {
+ const id = typeof skill?.id === 'string' ? skill.id.trim() : '';
+ const name = typeof skill?.name === 'string' ? skill.name.trim() : '';
+ if (!id || !name || id === name) continue;
+ out.set(id.toLowerCase(), name);
+ }
+ return out;
+}
+
+function _buildSkillDisplayNameByRef(skills) {
+ const out = new Map();
+ if (!Array.isArray(skills)) return out;
+ for (const skill of skills) {
+ const id = typeof skill?.id === 'string' ? skill.id.trim() : '';
+ const name = typeof skill?.name === 'string' ? skill.name.trim() : '';
+ const display = name || id;
+ if (!display) continue;
+ if (id) out.set(id.toLowerCase(), display);
+ if (name) out.set(name.toLowerCase(), display);
+ }
+ return out;
+}
+
+function _escapeSkillIdForRegex(s) {
+ return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function _replaceKnownSkillIdsForDisplay(text, skills) {
+ if (!text) return text;
+ const byId = _buildSkillDisplayNameById(skills);
+ if (!byId.size) return text;
+ const ids = Array.from(byId.keys()).sort((a, b) => b.length - a.length);
+ const alt = ids.map(_escapeSkillIdForRegex).join('|');
+ const re = new RegExp(`(^|[^A-Za-z0-9_])(${alt})(?=$|[^A-Za-z0-9_])`, 'gi');
+ return String(text).replace(re, (_m, prefix, id) => `${prefix}${byId.get(id.toLowerCase()) || id}`);
+}
+
+function _simplifyKnownSkillFollowPhrasesForDisplay(text, skills) {
+ if (!text) return text;
+ const byRef = _buildSkillDisplayNameByRef(skills);
+ if (!byRef.size) return text;
+ const replaceRef = (full, ref) => {
+ const display = byRef.get(String(ref || '').trim().toLowerCase());
+ return display ? `\`${display}\` skill` : full;
+ };
+ let out = String(text).replace(/`skill:\s*follow\s+the\s+([A-Za-z0-9_.-]+)\s+skill`/gi, replaceRef);
+ out = out.replace(/skill:\s*follow\s+the\s+`?([A-Za-z0-9_.-]+)`?\s+skill/gi, replaceRef);
+ return out;
+}
+
+function _normalizeKnownSkillRefsForDisplay(text, skills) {
+ return _simplifyKnownSkillFollowPhrasesForDisplay(
+ _replaceKnownSkillIdsForDisplay(text, skills),
+ skills,
+ );
+}
+
// Test bridge — see file header. No-op in the browser (`module` undefined).
if (typeof module !== 'undefined' && typeof module.exports === 'object') {
module.exports = {
@@ -426,5 +605,10 @@ if (typeof module !== 'undefined' && typeof module.exports === 'object') {
_extractSkillFilePath,
_stripSkillCreateContainer,
_stripSurvivingStructuralBlocks,
+ _stripSubmissionRoutingMentionForDisplay,
+ _stripUserStructuralBlocksForDisplay,
+ _replaceKnownSkillIdsForDisplay,
+ _simplifyKnownSkillFollowPhrasesForDisplay,
+ _normalizeKnownSkillRefsForDisplay,
};
}
diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.js
index 58919792..198a26f8 100644
--- a/src/renderer/modules/utils.js
+++ b/src/renderer/modules/utils.js
@@ -82,6 +82,18 @@ function renderMarkdownFull(md) {
}
});
+ // :::dashboard directives — JSON component tree → recursive HTML render.
+ // Malformed JSON falls back to a code-view block so the user sees the raw
+ // body instead of a silently-dropped section.
+ md = md.replace(/:::dashboard\s*\n([\s\S]*?)\n\s*:::/g, (_, body) => {
+ try {
+ const spec = JSON.parse(body.trim());
+ return protect(renderDashboard(spec));
+ } catch (e) {
+ return protect(`<pre class="code-view dashboard-parse-error"><code>${escapeHtml(body.trim())}</code></pre>`);
+ }
+ });
+
// Math blocks — protect so markdown phase 2 (emphasis, autolinking, html
// escapes) doesn't mangle LaTeX before MathJax sees it. Order matters:
// 1. `$$...$$` and `\[...\]` (display) — multi-line, must match first
@@ -328,6 +340,256 @@ function renderChartBar(data) {
return html;
}
+// ─── Dashboard renderer (`:::dashboard` directive) ────────────────────────
+// Recursive component tree → HTML. Components live in two tiers:
+// • Layout primitives : Stack / Grid / Card / Separator (no semantics)
+// • Content components : Metric / Chart / Table / Alert / Timeline /
+// Code / Markdown / Image
+// Unknown `type` and missing props render an empty container instead of
+// throwing — keeps the surrounding bubble alive when the model produces a
+// partially-formed tree. Props are enum-coerced via _dbEnum(); raw px / hex
+// values are intentionally NOT accepted (consistency over flexibility).
+//
+// Cross-file note: the model-facing schema reference lives in
+// `chat_shared_rules.md` "Output formats". Component names and enum values
+// must match that doc — adding a component or a new prop value requires
+// updating both sides in the same patch.
+
+const _DB_GAP = { sm: 'sm', md: 'md', lg: 'lg' };
+const _DB_TONE = { positive: 'positive', negative: 'negative', neutral: 'neutral', warning: 'warning' };
+const _DB_LEVEL = { info: 'info', success: 'success', warning: 'warning', error: 'error' };
+const _DB_CHART_KIND = { line: 'line', bar: 'bar', area: 'area', pie: 'pie' };
+
+function _dbEnum(table, val, dflt) {
+ return (val && Object.prototype.hasOwnProperty.call(table, val)) ? table[val] : dflt;
+}
+
+function renderDashboard(spec) {
+ if (!spec || typeof spec !== 'object') return '';
+ const theme = spec.theme || {};
+ const themeColor = _dbEnum({ neutral: 'neutral', brand: 'brand', success: 'success', warning: 'warning', danger: 'danger' }, theme.color, 'neutral');
+ const themeStyle = _dbEnum({ minimal: 'minimal', card: 'card' }, theme.style, 'minimal');
+ const inner = _renderDbNode(spec.root);
+ return `<div class="dashboard" data-theme-color="${themeColor}" data-theme-style="${themeStyle}">${inner}</div>`;
+}
+
+function _renderDbNode(node) {
+ if (!node || typeof node !== 'object') return '';
+ const props = (node.props && typeof node.props === 'object') ? node.props : {};
+ const children = Array.isArray(node.children) ? node.children : [];
+ switch (node.type) {
+ // ── Layout ────────────────────────────────────────────────────────
+ case 'Stack': return _dbStack(props, children);
+ case 'Grid': return _dbGrid(props, children);
+ case 'Card': return _dbCard(props, children);
+ case 'Separator': return '<hr class="db-separator">';
+ // ── Content ───────────────────────────────────────────────────────
+ case 'Metric': return _dbMetric(props);
+ case 'Chart': return _dbChart(props);
+ case 'Table': return _dbTable(props);
+ case 'Alert': return _dbAlert(props);
+ case 'Timeline': return _dbTimeline(props);
+ case 'Code': return _dbCode(props);
+ case 'Markdown': return _dbMarkdown(props);
+ case 'Image': return _dbImage(props);
+ default: return `<div class="db-unknown" data-type="${escapeHtml(String(node.type || ''))}"></div>`;
+ }
+}
+
+function _dbChildren(children) {
+ return children.map(_renderDbNode).join('');
+}
+
+// ── Layout primitives ──────────────────────────────────────────────────
+
+function _dbStack(props, children) {
+ const dir = props.direction === 'horizontal' ? 'horizontal' : 'vertical';
+ const gap = _dbEnum(_DB_GAP, props.gap, 'md');
+ return `<div class="db-stack" data-direction="${dir}" data-gap="${gap}">${_dbChildren(children)}</div>`;
+}
+
+function _dbGrid(props, children) {
+ const cols = Math.min(4, Math.max(1, Number(props.columns) || 2));
+ const gap = _dbEnum(_DB_GAP, props.gap, 'md');
+ return `<div class="db-grid" data-columns="${cols}" data-gap="${gap}">${_dbChildren(children)}</div>`;
+}
+
+function _dbCard(props, children) {
+ const tone = _dbEnum(_DB_TONE, props.tone, 'neutral');
+ const title = props.title ? `<div class="db-card-title">${escapeHtml(props.title)}</div>` : '';
+ return `<section class="db-card" data-tone="${tone}">${title}<div class="db-card-body">${_dbChildren(children)}</div></section>`;
+}
+
+// ── Content components ────────────────────────────────────────────────
+
+function _dbMetric(props) {
+ const label = escapeHtml(props.label || '');
+ const value = escapeHtml(String(props.value == null ? '' : props.value));
+ const tone = _dbEnum(_DB_TONE, props.tone, 'neutral');
+ const delta = props.delta != null
+ ? `<div class="db-metric-delta" data-tone="${tone}">${escapeHtml(String(props.delta))}</div>` : '';
+ return `<div class="db-metric" data-tone="${tone}">
+ <div class="db-metric-label">${label}</div>
+ <div class="db-metric-value">${value}</div>
+ ${delta}
+ </div>`;
+}
+
+function _dbAlert(props) {
+ const level = _dbEnum(_DB_LEVEL, props.level, 'info');
+ const title = escapeHtml(props.title || '');
+ const body = props.body ? `<div class="db-alert-body">${escapeHtml(props.body)}</div>` : '';
+ return `<div class="db-alert" data-level="${level}" role="status">
+ <div class="db-alert-title">${title}</div>${body}
+ </div>`;
+}
+
+function _dbTable(props) {
+ const cols = Array.isArray(props.columns) ? props.columns : [];
+ const rows = Array.isArray(props.rows) ? props.rows : [];
+ if (!cols.length) return '<div class="db-table-empty"></div>';
+ const head = cols.map(c => {
+ const numeric = c && c.numeric ? ' data-numeric="1"' : '';
+ return `<th${numeric}>${escapeHtml((c && (c.label || c.key)) || '')}</th>`;
+ }).join('');
+ const body = rows.map(r => {
+ const cells = cols.map(c => {
+ const k = c && c.key;
+ const v = (k && r && Object.prototype.hasOwnProperty.call(r, k)) ? r[k] : '';
+ const numeric = c && c.numeric ? ' data-numeric="1"' : '';
+ return `<td${numeric}>${escapeHtml(String(v == null ? '' : v))}</td>`;
+ }).join('');
+ return `<tr>${cells}</tr>`;
+ }).join('');
+ return `<div class="db-table-wrap"><table class="db-table"><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table></div>`;
+}
+
+function _dbTimeline(props) {
+ const items = Array.isArray(props.items) ? props.items : [];
+ if (!items.length) return '<div class="db-timeline-empty"></div>';
+ const lis = items.map(it => {
+ const time = escapeHtml((it && it.time) || '');
+ const label = escapeHtml((it && it.label) || '');
+ const body = it && it.body ? `<div class="db-timeline-body">${escapeHtml(it.body)}</div>` : '';
+ return `<li class="db-timeline-item">
+ <div class="db-timeline-time">${time}</div>
+ <div class="db-timeline-label">${label}</div>
+ ${body}
+ </li>`;
+ }).join('');
+ return `<ol class="db-timeline">${lis}</ol>`;
+}
+
+function _dbCode(props) {
+ const lang = escapeHtml(props.lang || '');
+ const code = escapeHtml(String(props.code == null ? '' : props.code));
+ const langAttr = lang ? ` data-lang="${lang}"` : '';
+ return `<pre class="db-code"${langAttr}><code>${code}</code></pre>`;
+}
+
+function _dbMarkdown(props) {
+ // Accept `text` (schema name) or `content` (common model guess) — without
+ // this alias the model's `{ Markdown: { content: "..." } }` silently
+ // collapses to an empty bubble and the section disappears.
+ const raw = props.text != null ? props.text : props.content;
+ const text = String(raw == null ? '' : raw);
+ // Recursive call back into renderMarkdownFull keeps the same feature set
+ // (tables / lists / inline code / autolinks); strip leading `:::dashboard`
+ // re-entry to prevent an infinite-render loop if the model nests one.
+ const cleaned = text.replace(/:::dashboard[\s\S]*?:::/g, '');
+ return `<div class="db-markdown">${renderMarkdownFull(cleaned)}</div>`;
+}
+
+function _dbImage(props) {
+ const src = String(props.src || '');
+ if (!src) return '';
+ const alt = escapeHtml(props.alt || '');
+ const caption = props.caption
+ ? `<figcaption class="db-image-caption">${escapeHtml(props.caption)}</figcaption>` : '';
+ return `<figure class="db-image"><img src="${src}" alt="${alt}">${caption}</figure>`;
+}
+
+// ── Chart (minimal inline SVG; line/bar/area/pie) ─────────────────────
+
+function _dbChart(props) {
+ const kind = _dbEnum(_DB_CHART_KIND, props.kind, 'bar');
+ const data = Array.isArray(props.data) ? props.data : [];
+ if (!data.length) return '<div class="db-chart-empty"></div>';
+ if (kind === 'pie') return _dbPie(data);
+ return _dbXyChart(kind, data);
+}
+
+function _dbPie(data) {
+ // data: [{label, value}, ...]
+ const items = data.filter(d => d && Number.isFinite(Number(d.value)) && Number(d.value) > 0);
+ const total = items.reduce((a, d) => a + Number(d.value), 0);
+ if (!total) return '<div class="db-chart-empty"></div>';
+ const cx = 50, cy = 50, r = 45;
+ let acc = 0;
+ const segs = items.map((d, i) => {
+ const v = Number(d.value);
+ const startAngle = (acc / total) * Math.PI * 2 - Math.PI / 2;
+ acc += v;
+ const endAngle = (acc / total) * Math.PI * 2 - Math.PI / 2;
+ const large = (v / total) > 0.5 ? 1 : 0;
+ const x1 = cx + r * Math.cos(startAngle), y1 = cy + r * Math.sin(startAngle);
+ const x2 = cx + r * Math.cos(endAngle), y2 = cy + r * Math.sin(endAngle);
+ return `<path d="M${cx},${cy} L${x1.toFixed(2)},${y1.toFixed(2)} A${r},${r} 0 ${large} 1 ${x2.toFixed(2)},${y2.toFixed(2)} Z" class="db-chart-slice" data-idx="${i % 6}"></path>`;
+ }).join('');
+ const legend = items.map((d, i) =>
+ `<li data-idx="${i % 6}"><span class="db-chart-swatch"></span>${escapeHtml(d.label || '')} <span class="db-chart-val">${escapeHtml(String(d.value))}</span></li>`
+ ).join('');
+ return `<div class="db-chart" data-kind="pie">
+ <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" class="db-chart-svg">${segs}</svg>
+ <ol class="db-chart-legend">${legend}</ol>
+ </div>`;
+}
+
+function _dbXyChart(kind, data) {
+ // data: [{x, y}, ...] — x is label (string), y is numeric.
+ const points = data.map(d => ({ x: String((d && d.x) ?? ''), y: Number((d && d.y) ?? 0) }))
+ .filter(p => Number.isFinite(p.y));
+ if (!points.length) return '<div class="db-chart-empty"></div>';
+ const W = 320, H = 140, padL = 32, padR = 8, padT = 8, padB = 22;
+ const innerW = W - padL - padR, innerH = H - padT - padB;
+ const maxY = Math.max(...points.map(p => p.y), 0);
+ const minY = Math.min(...points.map(p => p.y), 0);
+ const span = (maxY - minY) || 1;
+ const xOf = (i) => padL + (points.length === 1 ? innerW / 2 : (i / (points.length - 1)) * innerW);
+ const yOf = (y) => padT + innerH - ((y - minY) / span) * innerH;
+ const axis = `<line x1="${padL}" y1="${padT + innerH}" x2="${W - padR}" y2="${padT + innerH}" class="db-chart-axis"></line>`;
+ let body = '';
+ if (kind === 'bar') {
+ const barW = innerW / points.length * 0.6;
+ body = points.map((p, i) => {
+ const x = xOf(i) - barW / 2;
+ const y = yOf(Math.max(p.y, 0));
+ const h = Math.abs(yOf(p.y) - yOf(0));
+ return `<rect x="${x.toFixed(2)}" y="${y.toFixed(2)}" width="${barW.toFixed(2)}" height="${h.toFixed(2)}" class="db-chart-bar-rect"></rect>`;
+ }).join('');
+ } else {
+ const path = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${xOf(i).toFixed(2)},${yOf(p.y).toFixed(2)}`).join(' ');
+ if (kind === 'area') {
+ const area = `M${xOf(0).toFixed(2)},${yOf(minY).toFixed(2)} ` +
+ points.map((p, i) => `L${xOf(i).toFixed(2)},${yOf(p.y).toFixed(2)}`).join(' ') +
+ ` L${xOf(points.length - 1).toFixed(2)},${yOf(minY).toFixed(2)} Z`;
+ body = `<path d="${area}" class="db-chart-area"></path><path d="${path}" class="db-chart-line"></path>`;
+ } else {
+ body = `<path d="${path}" class="db-chart-line"></path>` +
+ points.map((p, i) => `<circle cx="${xOf(i).toFixed(2)}" cy="${yOf(p.y).toFixed(2)}" r="2.5" class="db-chart-dot"></circle>`).join('');
+ }
+ }
+ const labels = points.map((p, i) => {
+ if (points.length > 8 && i % Math.ceil(points.length / 6) !== 0 && i !== points.length - 1) return '';
+ return `<text x="${xOf(i).toFixed(2)}" y="${(H - 6).toFixed(2)}" class="db-chart-xlabel" text-anchor="middle">${escapeHtml(p.x)}</text>`;
+ }).join('');
+ return `<div class="db-chart" data-kind="${kind}">
+ <svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="xMidYMid meet" class="db-chart-svg">
+ ${axis}${body}${labels}
+ </svg>
+ </div>`;
+}
+
// Detect video src by extension. Dispatches markdown ![](src) to <video>
// instead of <img> — covers chat-media://local/...mp4, https://..../clip.webm,
// and any user-authored markdown pointing at a video file. The match is
@@ -745,5 +1007,7 @@ if (typeof module !== 'undefined' && typeof module.exports === 'object') {
_linkifyBareEmails,
inlineFormat,
escapeHtml,
+ renderMarkdown,
+ renderDashboard,
};
}
diff --git a/src/renderer/style.css b/src/renderer/style.css
index f4c03e34..205ee24b 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -1162,6 +1162,9 @@ body.model-not-configured .main-content { flex-direction: column; }
padding: 14px 20px 28px;
width: 100%;
}
+#skills-detail-content {
+ padding-top: 0;
+}
.skills-detail-content::-webkit-scrollbar { width: 6px; }
.skills-detail-content::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.1); border-radius: 3px; }
@@ -1171,14 +1174,17 @@ body.model-not-configured .main-content { flex-direction: column; }
back-button on the left, title + source chip middle, actions hugged to the right via
`margin-left:auto`. The row stays `nowrap` so it visually reads as one chrome strip; long
titles ellipsize rather than wrap (title gets `min-width:0` + overflow). Negative side
- margins offset the `.skills-detail-content` container's horizontal padding so the
+ side margins offset the `.skills-detail-content` container's horizontal padding so the
border-bottom rule reaches the panel edges — same chrome divider the agent detail uses. */
.skills-doc-headline {
+ position: sticky;
+ top: 0;
+ z-index: 5;
display: flex;
align-items: center;
flex-wrap: nowrap;
gap: 8px;
- margin: -14px -20px 20px;
+ margin: 0 -20px 20px;
padding: 14px 20px;
border-bottom: 1px solid var(--border);
background: #fff;
@@ -1883,6 +1889,185 @@ body.model-not-configured .main-content { flex-direction: column; }
color: var(--primary);
}
+/* ─── Dashboard (`:::dashboard` directive — see utils.js renderDashboard).
+ Component tree → HTML; tones use the global --primary/--success/
+ --danger/--muted palette; data-* attrs drive layout / state. ─── */
+.dashboard {
+ margin: 0.6em 0;
+ font-size: 13px;
+ color: var(--text);
+}
+.dashboard .db-stack {
+ display: flex;
+ flex-direction: column;
+}
+.dashboard .db-stack[data-direction="horizontal"] {
+ flex-direction: row;
+ flex-wrap: wrap;
+ align-items: stretch;
+}
+.dashboard .db-stack[data-gap="sm"], .dashboard .db-grid[data-gap="sm"] { gap: 6px; }
+.dashboard .db-stack[data-gap="md"], .dashboard .db-grid[data-gap="md"] { gap: 12px; }
+.dashboard .db-stack[data-gap="lg"], .dashboard .db-grid[data-gap="lg"] { gap: 20px; }
+.dashboard .db-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+}
+.dashboard .db-grid[data-columns="1"] { grid-template-columns: minmax(0, 1fr); }
+.dashboard .db-grid[data-columns="2"] { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+.dashboard .db-grid[data-columns="3"] { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+.dashboard .db-grid[data-columns="4"] { grid-template-columns: repeat(4, minmax(0, 1fr)); }
+@media (max-width: 640px) {
+ .dashboard .db-grid[data-columns="3"],
+ .dashboard .db-grid[data-columns="4"] { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+}
+
+.dashboard .db-card {
+ border: 1px solid var(--border);
+ border-radius: var(--radius-md);
+ background: var(--card);
+ padding: 12px 14px;
+}
+.dashboard .db-card[data-tone="positive"] { border-color: rgba(22, 163, 74, 0.4); }
+.dashboard .db-card[data-tone="negative"] { border-color: rgba(220, 38, 38, 0.4); }
+.dashboard .db-card[data-tone="warning"] { border-color: rgba(234, 179, 8, 0.45); }
+.dashboard .db-card-title {
+ font-weight: 600;
+ font-size: 13px;
+ margin-bottom: 8px;
+ color: var(--text);
+}
+.dashboard .db-separator {
+ border: none;
+ border-top: 1px solid var(--border);
+ margin: 6px 0;
+}
+
+/* Metric — KPI card. Numeric value is the visual anchor; delta carries tone. */
+.dashboard .db-metric {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 12px 14px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-md);
+ background: var(--card);
+ min-width: 0;
+}
+.dashboard .db-metric-label {
+ font-size: 12px;
+ color: var(--muted);
+ text-transform: none;
+ letter-spacing: 0;
+}
+.dashboard .db-metric-value {
+ font-size: 20px;
+ font-weight: 700;
+ color: var(--text);
+ line-height: 1.2;
+ word-break: break-word;
+}
+.dashboard .db-metric-delta {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--muted);
+}
+.dashboard .db-metric-delta[data-tone="positive"] { color: var(--success); }
+.dashboard .db-metric-delta[data-tone="negative"] { color: var(--danger); }
+.dashboard .db-metric-delta[data-tone="warning"] { color: #b45309; }
+
+/* Alert — color-coded banner. */
+.dashboard .db-alert {
+ padding: 10px 12px;
+ border-radius: var(--radius-sm);
+ border: 1px solid var(--border);
+ background: var(--card);
+}
+.dashboard .db-alert-title { font-weight: 600; font-size: 13px; }
+.dashboard .db-alert-body { font-size: 12.5px; color: var(--muted); margin-top: 4px; }
+.dashboard .db-alert[data-level="info"] { border-color: rgba(37, 99, 235, 0.35); background: rgba(37, 99, 235, 0.06); }
+.dashboard .db-alert[data-level="success"] { border-color: rgba(22, 163, 74, 0.35); background: rgba(22, 163, 74, 0.06); }
+.dashboard .db-alert[data-level="warning"] { border-color: rgba(234, 179, 8, 0.45); background: rgba(234, 179, 8, 0.08); }
+.dashboard .db-alert[data-level="error"] { border-color: rgba(220, 38, 38, 0.4); background: rgba(220, 38, 38, 0.06); }
+
+/* Table — compact, numeric columns right-aligned. */
+.dashboard .db-table-wrap { overflow-x: auto; border: 1px solid var(--border); border-radius: var(--radius-sm); }
+.dashboard .db-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
+.dashboard .db-table th,
+.dashboard .db-table td { padding: 6px 10px; border-bottom: 1px solid var(--border); text-align: left; }
+.dashboard .db-table tr:last-child td { border-bottom: none; }
+.dashboard .db-table th { background: var(--bg); font-weight: 600; color: var(--text); }
+.dashboard .db-table th[data-numeric="1"],
+.dashboard .db-table td[data-numeric="1"] { text-align: right; font-variant-numeric: tabular-nums; }
+
+/* Timeline — left rail + per-item dot. */
+.dashboard .db-timeline { list-style: none; padding: 4px 0 4px 16px; border-left: 2px solid var(--border); display: flex; flex-direction: column; gap: 10px; }
+.dashboard .db-timeline-item { position: relative; padding-left: 8px; }
+.dashboard .db-timeline-item::before {
+ content: "";
+ position: absolute;
+ left: -22px;
+ top: 6px;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--primary);
+}
+.dashboard .db-timeline-time { font-size: 11.5px; color: var(--muted); }
+.dashboard .db-timeline-label { font-size: 13px; font-weight: 600; color: var(--text); }
+.dashboard .db-timeline-body { font-size: 12.5px; color: var(--muted); margin-top: 2px; }
+
+/* Code / Markdown / Image */
+.dashboard .db-code {
+ background: #f8fafc;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ padding: 10px 12px;
+ overflow-x: auto;
+ font-family: ui-monospace, SFMono-Regular, "SF Mono", monospace;
+ font-size: 12px;
+ line-height: 1.5;
+ margin: 0;
+}
+.dashboard .db-markdown { font-size: 13px; line-height: 1.5; }
+.dashboard .db-markdown p { margin: 0.3em 0; }
+.dashboard .db-image { margin: 0; }
+.dashboard .db-image img { max-width: 100%; border-radius: var(--radius-sm); display: block; }
+.dashboard .db-image-caption { font-size: 11.5px; color: var(--muted); margin-top: 4px; }
+
+/* Chart — minimal inline SVG. 6-step categorical palette; pie + xy share it. */
+.dashboard .db-chart { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 8px; }
+.dashboard .db-chart-svg { width: 100%; height: auto; display: block; }
+.dashboard .db-chart-axis { stroke: var(--border); stroke-width: 1; }
+.dashboard .db-chart-line { fill: none; stroke: var(--primary); stroke-width: 2; }
+.dashboard .db-chart-area { fill: var(--primary); opacity: 0.18; stroke: none; }
+.dashboard .db-chart-dot { fill: var(--primary); }
+.dashboard .db-chart-bar-rect { fill: var(--primary); opacity: 0.85; }
+.dashboard .db-chart-xlabel { font-size: 10px; fill: var(--muted); font-family: inherit; }
+.dashboard .db-chart-slice[data-idx="0"] { fill: #2563eb; }
+.dashboard .db-chart-slice[data-idx="1"] { fill: #16a34a; }
+.dashboard .db-chart-slice[data-idx="2"] { fill: #ea580c; }
+.dashboard .db-chart-slice[data-idx="3"] { fill: #9333ea; }
+.dashboard .db-chart-slice[data-idx="4"] { fill: #0891b2; }
+.dashboard .db-chart-slice[data-idx="5"] { fill: #ca8a04; }
+.dashboard .db-chart-legend { list-style: none; padding: 8px 4px 0; margin: 0; display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: 12px; }
+.dashboard .db-chart-legend li { display: flex; align-items: center; gap: 6px; color: var(--text); }
+.dashboard .db-chart-legend .db-chart-swatch { display: inline-block; width: 10px; height: 10px; border-radius: 2px; }
+.dashboard .db-chart-legend li[data-idx="0"] .db-chart-swatch { background: #2563eb; }
+.dashboard .db-chart-legend li[data-idx="1"] .db-chart-swatch { background: #16a34a; }
+.dashboard .db-chart-legend li[data-idx="2"] .db-chart-swatch { background: #ea580c; }
+.dashboard .db-chart-legend li[data-idx="3"] .db-chart-swatch { background: #9333ea; }
+.dashboard .db-chart-legend li[data-idx="4"] .db-chart-swatch { background: #0891b2; }
+.dashboard .db-chart-legend li[data-idx="5"] .db-chart-swatch { background: #ca8a04; }
+.dashboard .db-chart-legend .db-chart-val { color: var(--muted); }
+.dashboard .db-chart-empty,
+.dashboard .db-table-empty,
+.dashboard .db-timeline-empty { font-size: 12px; color: var(--muted); padding: 6px 0; }
+
+/* Fallback when a `:::dashboard` block fails to parse — show the raw body
+ so the user can copy it and diagnose, rather than silently dropping. */
+.dashboard-parse-error { border-color: rgba(220, 38, 38, 0.4); }
+
/* ─── Code view (for .py, .json etc.) ─── */
.code-view {
background: #f8fafc;
@@ -1996,6 +2181,7 @@ body.model-not-configured .main-content { flex-direction: column; }
background: #f8fafc;
/* Used by `.chat-input-form { width: 40cqw }`. */
container-type: inline-size;
+ --chat-input-reserve: 140px;
}
.conversation-info-toggle {
@@ -2245,14 +2431,6 @@ body.model-not-configured .main-content { flex-direction: column; }
}
.conversation-info-dir-summary::-webkit-details-marker { display: none; }
.conversation-info-dir-summary:hover { background: #f8fafc; }
-.conversation-info-dir-icon {
- width: 12px;
- color: #94a3b8;
- transition: transform 120ms ease;
-}
-.conversation-info-dir[open] > .conversation-info-dir-summary .conversation-info-dir-icon {
- transform: rotate(90deg);
-}
.conversation-info-dir-folder-icon {
flex: 0 0 auto;
width: 18px;
@@ -2384,13 +2562,13 @@ body.model-not-configured .main-content { flex-direction: column; }
min-height: 0;
/* Bottom: 80px **inside** the scroll viewport so when the user
scrolls all the way down the last bubble has breathing room above
- the floating input area / attachment chips. The 140px margin-bottom
- keeps the scrollbar track clear of the floating input so the thumb
- stays visible at the end. We use padding-bottom (NOT bigger margin)
+ the floating input area / attachment chips. The margin-bottom follows
+ the measured floating input wrapper height so quote previews / queues
+ keep the scrollbar track clear of the composer. We use padding-bottom (NOT bigger margin)
because the goal is more whitespace inside the scroll view, not
pushing the viewport upward — that was the wrong fix earlier. */
padding: 24px 10% 80px;
- margin-bottom: 140px;
+ margin-bottom: var(--chat-input-reserve, 140px);
overflow-y: auto;
display: flex;
flex-direction: column;
@@ -3886,6 +4064,20 @@ body.model-not-configured .main-content { flex-direction: column; }
font-weight: 500;
color: var(--text, #1f2937);
}
+.chat-msg-from.is-agent-link {
+ cursor: pointer;
+ border-radius: 4px;
+ transition: color 0.12s, background 0.12s;
+}
+.chat-msg-from.is-agent-link:hover {
+ color: var(--primary, #2563eb);
+ background: rgba(37, 99, 235, 0.08);
+}
+.chat-msg-from.is-agent-link:focus-visible,
+.chat-msg-header .avatar-circle.is-clickable:focus-visible {
+ outline: 2px solid rgba(37, 99, 235, 0.45);
+ outline-offset: 2px;
+}
.chat-msg-from:empty {
display: none;
}
@@ -4305,15 +4497,14 @@ body.model-not-configured .main-content { flex-direction: column; }
display: inline-flex;
align-items: center;
gap: 4px;
- padding: 3px 6px 3px 10px;
- background: rgba(37, 99, 235, 0.1);
- border: 1px solid rgba(37, 99, 235, 0.25);
+ padding: 4px 6px 4px 10px;
+ background: rgba(37, 99, 235, 0.08);
+ border: 1px solid rgba(37, 99, 235, 0.22);
color: var(--primary);
- border-radius: 10px;
+ border-radius: 14px;
font-size: 12px;
font-weight: 500;
line-height: 1.4;
- margin-bottom: 2px;
align-self: center;
}
@@ -4402,10 +4593,24 @@ body.model-not-configured .main-content { flex-direction: column; }
}
.chat-skill-chip .chip-label {
+ display: inline-flex;
+ align-items: center;
+ min-width: 0;
max-width: 160px;
+}
+
+.chat-skill-chip .chip-label-prefix {
+ flex-shrink: 0;
+ color: var(--muted);
+ font-weight: 400;
+}
+
+.chat-skill-chip .chip-label-name {
+ min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
+ color: var(--primary);
}
.chat-skill-chip .chip-close {
@@ -4541,8 +4746,8 @@ body.model-not-configured .main-content { flex-direction: column; }
.skill-picker {
position: fixed;
- width: 300px;
- max-height: 340px;
+ width: 340px;
+ max-height: 380px;
background: #fff;
border: 1px solid var(--border);
border-radius: 12px;
@@ -4553,6 +4758,38 @@ body.model-not-configured .main-content { flex-direction: column; }
overflow: hidden;
}
+.skill-picker-tabs {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 4px;
+ padding: 8px 8px 0;
+ background: #fff;
+}
+
+.skill-picker-tab {
+ border: 1px solid transparent;
+ background: transparent;
+ color: var(--muted);
+ border-radius: 8px;
+ padding: 6px 8px;
+ font-size: 12px;
+ font-weight: 600;
+ font-family: inherit;
+ cursor: pointer;
+ white-space: nowrap;
+}
+
+.skill-picker-tab:hover {
+ background: #f8fafc;
+ color: var(--text);
+}
+
+.skill-picker-tab.active {
+ background: rgba(37, 99, 235, 0.1);
+ border-color: rgba(37, 99, 235, 0.22);
+ color: var(--primary);
+}
+
.skill-picker-header {
padding: 8px;
border-bottom: 1px solid var(--border);
@@ -6390,12 +6627,22 @@ body.model-not-configured .main-content { flex-direction: column; }
line-height: 1.5;
}
.settings-header {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 16px;
margin-bottom: 28px;
}
+.settings-heading {
+ min-width: 0;
+}
.settings-header h2 {
margin: 0 0 6px;
font-size: 20px;
font-weight: 600;
+}
+ flex: 0 0 auto;
+ margin-top: 2px;
}
.settings-version {
color: var(--text-muted, #6b7280);
@@ -6514,6 +6761,127 @@ body.model-not-configured .main-content { flex-direction: column; }
.settings-status.error { color: #b91c1c; }
.settings-status.busy { color: #6b7280; }
+.feedback-dialog {
+ width: min(560px, 92vw);
+ max-width: 560px;
+}
+.feedback-submit-btn {
+ display: inline-flex;
+ align-items: center;
+ min-width: 82px;
+ justify-content: center;
+}
+.feedback-dialog-body {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+.feedback-textarea {
+ width: 100%;
+ resize: vertical;
+ min-height: 130px;
+ max-height: 260px;
+ padding: 10px 12px;
+ border: 1px solid var(--border, #e5e7eb);
+ border-radius: 8px;
+ font-size: 13px;
+ line-height: 1.5;
+ font-family: inherit;
+ color: var(--text);
+ box-sizing: border-box;
+}
+.feedback-textarea:focus {
+ outline: none;
+ border-color: var(--primary, #2563eb);
+ box-shadow: 0 0 0 3px rgba(37,99,235,.12);
+}
+.feedback-meta-row,
+.feedback-picker-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+.feedback-meta-row .settings-status,
+.feedback-picker-row .settings-status {
+ flex: 1 1 auto;
+}
+.feedback-counter {
+ flex: 0 0 auto;
+ font-size: 12px;
+ color: var(--text-muted, #6b7280);
+}
+.feedback-images {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 10px;
+}
+.feedback-image-item {
+ position: relative;
+ min-width: 0;
+ border: 1px solid var(--border, #e5e7eb);
+ border-radius: 8px;
+ padding: 8px;
+ background: #fff;
+}
+.feedback-image-thumb {
+ width: 100%;
+ aspect-ratio: 4 / 3;
+ border-radius: 6px;
+ overflow: hidden;
+ background: #f8fafc;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+.feedback-image-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.feedback-image-placeholder {
+ width: 22px;
+ height: 22px;
+ border: 2px solid #cbd5e1;
+ border-top-color: var(--primary, #2563eb);
+ border-radius: 50%;
+ animation: feedback-spin 0.8s linear infinite;
+}
+@keyframes feedback-spin { to { transform: rotate(360deg); } }
+.feedback-image-name {
+ margin-top: 6px;
+ padding-right: 22px;
+ font-size: 12px;
+ color: var(--text-muted, #6b7280);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.feedback-image-item.is-failed {
+ border-color: rgba(220, 38, 38, 0.35);
+}
+.feedback-image-item.is-failed .feedback-image-name {
+ color: #b91c1c;
+}
+.feedback-image-remove {
+ position: absolute;
+ right: 6px;
+ bottom: 5px;
+ width: 22px;
+ height: 22px;
+ border: 0;
+ border-radius: 50%;
+ background: transparent;
+ color: #64748b;
+ cursor: pointer;
+ font-size: 16px;
+ line-height: 20px;
+}
+.feedback-image-remove:hover {
+ background: #f1f5f9;
+ color: #0f172a;
+}
+
/* ── Custom dropdown (AiSelect) ────────────────────────────────────────── */
.ai-select {
position: relative;
@@ -7141,6 +7509,61 @@ body.model-not-configured .main-content { flex-direction: column; }
.agents-detail-runtime { display: block; }
.agents-detail-runtime-select { max-width: 280px; }
+.agents-detail-project-dir { max-width: 100%; }
+.agent-project-dir-card {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 10px;
+ padding: 10px 12px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: rgba(15, 23, 42, 0.02);
+ min-width: 0;
+}
+.agent-project-dir-card.is-missing {
+ border-color: rgba(239, 68, 68, 0.35);
+ background: rgba(239, 68, 68, 0.04);
+}
+.agent-project-dir-card.is-disabled {
+ opacity: 0.72;
+}
+.agent-project-dir-icon {
+ flex: 0 0 auto;
+ width: 18px;
+ height: 18px;
+ color: var(--primary);
+}
+.agent-project-dir-card.is-missing .agent-project-dir-icon {
+ color: var(--danger);
+}
+.agent-project-dir-main {
+ flex: 1 1 auto;
+ min-width: 180px;
+}
+.agent-project-dir-path {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 12px;
+ color: var(--text);
+}
+.agent-project-dir-mode {
+ margin-top: 2px;
+ font-size: 11px;
+ color: var(--muted);
+}
+.agent-project-dir-card.is-missing .agent-project-dir-mode {
+ color: var(--danger);
+}
+.agent-project-dir-actions {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex: 0 0 auto;
+ margin-left: auto;
+}
/* Wrapper for the multi-button cluster on the right side of agents-grid-header /
skills-grid-header. Keeps `+ Create` / `More` glued together while the parent
@@ -8039,3 +8462,114 @@ body.model-not-configured .main-content { flex-direction: column; }
#connectors-connect-modal .form-hint { font-size: 11px; display: inline-block; }
#connectors-connect-modal .modal-actions { display: flex; gap: 8px; justify-content: flex-end; }
.connectors-add-status { font-size: 12px; min-height: 18px; }
+
+/* ── Chat-side markdown drawer ─────────────────────────────────────────
+ Same width / chrome rules as `.conversation-info-panel` (kept locally
+ rather than promoted to a shared `.chat-side-drawer` class because the
+ conversation-info CSS already shipped — extracting later if a third
+ drawer surface lands). The body re-uses `.ctx-*` classes from the
+ contexts editor since the mount component is the same. */
+.chat-md-drawer-panel {
+ /* Wider than conversation-info — markdown is text-heavy and worth the
+ real estate. Caps so the main chat column doesn't collapse on narrow
+ windows. */
+ flex: 0 0 min(560px, 50vw);
+ width: min(560px, 50vw);
+ min-width: 420px;
+ max-width: 720px;
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ border-left: 1px solid var(--border);
+ background: #fff;
+ color: var(--text);
+ box-shadow: -12px 0 28px rgba(15, 23, 42, 0.05);
+ z-index: 20;
+}
+.chat-md-drawer-panel[hidden] { display: none !important; }
+.chat-md-drawer-header {
+ flex: 0 0 auto;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 16px 16px 12px;
+ border-bottom: 1px solid var(--border);
+}
+.chat-md-drawer-title {
+ flex: 1 1 auto;
+ min-width: 0;
+ font-size: 14px;
+ font-weight: 650;
+ color: var(--text);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.chat-md-drawer-actions { flex: 0 0 auto; display: flex; gap: 6px; }
+.chat-md-drawer-close {
+ flex: 0 0 auto;
+ width: 28px;
+ height: 28px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid transparent;
+ border-radius: 8px;
+ background: transparent;
+ color: #94a3b8;
+ font-size: 20px;
+ line-height: 1;
+ cursor: pointer;
+}
+.chat-md-drawer-close:hover {
+ color: #0f172a;
+ background: #f1f5f9;
+ border-color: #e2e8f0;
+}
+.chat-md-drawer-body {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow: auto;
+ display: flex;
+ flex-direction: column;
+ padding: 0;
+}
+/* The mount writes its toolbar / body / textarea inline; we let the
+ existing ctx-* rules dictate visuals (single source of truth) and only
+ reset the host container's padding here so the textarea can stretch
+ edge-to-edge. */
+.chat-md-drawer-body .ctx-editor-toolbar { padding: 8px 12px; border-bottom: 1px solid var(--border); }
+.chat-md-drawer-body .ctx-editor-body { flex: 1 1 auto; min-height: 0; display: flex; }
+.chat-md-drawer-body .ctx-viewer-md { padding: 12px 16px; flex: 1 1 auto; overflow: auto; }
+.chat-md-drawer-body .ctx-viewer-editor { flex: 1 1 auto; min-height: 0; padding: 12px 16px; border: 0; outline: 0; resize: none; }
+
+/* ── Generic right-click context menu (modules/context-menu.js) ─────── */
+.context-menu {
+ position: fixed;
+ z-index: 9999;
+ min-width: 160px;
+ padding: 4px;
+ background: #fff;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 8px 24px rgba(15, 23, 42, 0.12);
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+}
+.context-menu-item {
+ display: block;
+ text-align: left;
+ border: 0;
+ background: transparent;
+ padding: 7px 10px;
+ border-radius: 6px;
+ font-size: 13px;
+ font-family: inherit;
+ color: var(--text);
+ cursor: pointer;
+}
+.context-menu-item:hover,
+.context-menu-item.is-active { background: var(--accent-soft, #eef2ff); }
+.context-menu-item.is-disabled { color: #94a3b8; cursor: not-allowed; }
+.context-menu-item.is-disabled:hover { background: transparent; }
diff --git a/test/main/features/agents.test.ts b/test/main/features/agents.test.ts
index 7c04e30b..2d7a516e 100644
--- a/test/main/features/agents.test.ts
+++ b/test/main/features/agents.test.ts
@@ -53,13 +53,14 @@ function builtinAgentsDir(): string {
}
function writeCustomAgent(agentId: string, fields: Partial<Record<string, any>> = {}): void {
- // Agent 目录形态:`agents/<aid>/agent.json`(详见 docs/plans/agent-as-directory.md)
+ // Agent directory shape: `agents/<aid>/agent.json` (see docs/plans/agent-as-directory.md).
const dir = path.join(customAgentsDir(), agentId);
fs.mkdirSync(dir, { recursive: true });
const data: Record<string, any> = {
agent_id: agentId,
name: fields.name ?? agentId,
description: fields.description ?? 'Test agent',
+ category: fields.category ?? 'general',
workflow: fields.workflow ?? '',
created_at: '2026-04-18T10:00:00',
updated_at: '2026-04-18T10:00:00',
@@ -73,10 +74,10 @@ function customSkillsDir(): string {
return path.join(tmpDir, TEST_UID, 'cloud', 'skills');
}
-function writeSkillOnDisk(id: string): void {
+function writeSkillOnDisk(id: string, name = id): void {
const dir = path.join(customSkillsDir(), id);
fs.mkdirSync(dir, { recursive: true });
- const lines = ['---', `name: ${id}`, `description: test skill ${id}`, '---', '', 'body'];
+ const lines = ['---', `name: ${name}`, `description: test skill ${name}`, '---', '', 'body'];
fs.writeFileSync(path.join(dir, 'SKILL.md'), lines.join('\n'));
}
@@ -227,6 +228,73 @@ describe('agents › normalizeAgent', () => {
});
});
+describe('agents › CLI project directory settings', () => {
+ it('defaults coding agents to workspace and stores custom dirs in local config only', async () => {
+ writeCustomAgent('code-agent', {
+ name: 'Code Agent',
+ runtime: { kind: 'cli', cli: 'codex' },
+ } as any);
+ const a = await loadAgents();
+ const userWorkspace = await import('../../../src/main/features/user_workspace');
+ const workspacePath = userWorkspace.getWorkspacePath(TEST_UID);
+
+ const initial = await a.getAgentCliProjectDirInfo(TEST_UID, 'code-agent');
+ expect(initial).toMatchObject({
+ agent_id: 'code-agent',
+ is_coding: true,
+ mode: 'workspace',
+ path: workspacePath,
+ effective_path: workspacePath,
+ exists: true,
+ });
+
+ const customDir = path.join(tmpDir, 'repo');
+ fs.mkdirSync(customDir);
+ const custom = await a.setAgentCliProjectDir(TEST_UID, 'code-agent', customDir);
+ expect(custom).toMatchObject({
+ mode: 'custom',
+ path: customDir,
+ effective_path: customDir,
+ custom_path: customDir,
+ exists: true,
+ });
+
+ const spec = JSON.parse(fs.readFileSync(path.join(customAgentsDir(), 'code-agent', 'agent.json'), 'utf8'));
+ expect(JSON.stringify(spec)).not.toContain(customDir);
+ const localConfig = path.join(tmpDir, TEST_UID, 'local', 'config', 'agent-runtime.json');
+ expect(JSON.parse(fs.readFileSync(localConfig, 'utf8')).project_dirs['code-agent'].path).toBe(customDir);
+
+ fs.rmSync(customDir, { recursive: true, force: true });
+ const missing = await a.getAgentCliProjectDirInfo(TEST_UID, 'code-agent');
+ expect(missing).toMatchObject({
+ mode: 'custom',
+ path: customDir,
+ effective_path: workspacePath,
+ exists: false,
+ });
+
+ const reset = await a.setAgentCliProjectDir(TEST_UID, 'code-agent', '');
+ expect(reset).toMatchObject({
+ mode: 'workspace',
+ path: workspacePath,
+ effective_path: workspacePath,
+ exists: true,
+ });
+ });
+
+ it('rejects project directory overrides on non-coding CLI agents', async () => {
+ writeCustomAgent('general-cli', {
+ name: 'General CLI',
+ runtime: { kind: 'cli', cli: 'openclaw' },
+ } as any);
+ const a = await loadAgents();
+ const customDir = path.join(tmpDir, 'repo');
+ fs.mkdirSync(customDir);
+ await expect(a.setAgentCliProjectDir(TEST_UID, 'general-cli', customDir))
+ .rejects.toMatchObject({ code: 'E_AGENT_NOT_CODING_CLI' });
+ });
+});
+
describe('agents › isValidAgentId', () => {
it('accepts alphanumeric + _/-', async () => {
const a = await loadAgents();
@@ -325,6 +393,59 @@ describe('agents › extractAgentFieldBlocks', () => {
expect(r.blocks[1].workflow).toBe('good-B');
});
+ it('ignores non-XML fenced protocol examples and extracts the real container after them', async () => {
+ const a = await loadAgents();
+ const text = [
+ 'Format example:',
+ '```',
+ '<agent>',
+ '<name>Example</name>',
+ '</agent>',
+ '```',
+ 'Now the actual update:',
+ '<agent>',
+ '<name>Real</name>',
+ '<workflow>step `bash`</workflow>',
+ '</agent>',
+ 'done',
+ ].join('\n');
+ const r = a.extractAgentFieldBlocks(text);
+ expect(r.blocks).toHaveLength(1);
+ expect(r.blocks[0]).toEqual({ name: 'Real', workflow: 'step `bash`' });
+ expect(r.cleanText).toContain('<name>Example</name>');
+ expect(r.cleanText).not.toContain('<name>Real</name>');
+ });
+
+ it('treats fenced ```xml agent blocks as structural output', async () => {
+ const a = await loadAgents();
+ const text = [
+ '```xml',
+ '<agent>',
+ '<name>Example</name>',
+ '<workflow>step one</workflow>',
+ '</agent>',
+ '```',
+ ].join('\n');
+ const r = a.extractAgentFieldBlocks(text);
+ expect(r.blocks).toEqual([{ name: 'Example', workflow: 'step one' }]);
+ expect(r.cleanText).toBe('```xml\n\n```');
+ });
+
+ it('leaves inline quoted agent markers visible', async () => {
+ const a = await loadAgents();
+ const text = '请输出 "<agent><name>Example</name></agent>" 这些字符';
+ const r = a.extractAgentFieldBlocks(text);
+ expect(r.blocks).toEqual([]);
+ expect(r.cleanText).toBe(text);
+ });
+
+ it('strips an unclosed real <agent> block without extracting partial fields', async () => {
+ const a = await loadAgents();
+ const r = a.extractAgentFieldBlocks('visible\n<agent>\n<name>Partial</name>\n<workflow>half');
+ expect(r.blocks).toEqual([]);
+ expect(r.cleanText).toBe('visible');
+ });
+
it('ignores child tags with empty body', async () => {
const a = await loadAgents();
const r = a.extractAgentFieldBlocks('<agent><name> </name></agent>');
@@ -395,6 +516,16 @@ describe('agents › extractAgentFieldBlocks', () => {
expect('interactive' in a.extractAgentFieldBlocks('<agent><interactive>1</interactive></agent>').blocks[0]).toBe(false);
expect('interactive' in a.extractAgentFieldBlocks('<agent><interactive></interactive></agent>').blocks[0]).toBe(false);
});
+
+ it('extracts safe category codes and drops unsafe ones', async () => {
+ const a = await loadAgents();
+ expect(a.extractAgentFieldBlocks('<agent><category>DATA</category></agent>')
+ .blocks[0].category).toBe('data');
+ expect(a.extractAgentFieldBlocks('<agent><category>misc</category></agent>')
+ .blocks[0].category).toBe('misc');
+ expect('category' in a.extractAgentFieldBlocks('<agent><category>bad category</category></agent>').blocks[0])
+ .toBe(false);
+ });
});
describe('agents › validateAgentInputs', () => {
@@ -557,7 +688,7 @@ describe('agents › extractAgentFieldBlocks › inputs', () => {
describe('agents › createCustomAgent', () => {
it('creates a 12-hex-id agent with defaults', async () => {
const a = await loadAgents();
- const agent = await a.createCustomAgent({ name: 'Alpha', description: 'desc' });
+ const agent = await a.createCustomAgent({ name: 'Alpha', description: 'desc', category: 'general' });
expect(agent?.agent_id).toMatch(/^[0-9a-f]{12}$/);
expect(agent?.name).toBe('Alpha');
expect(agent?.source).toBe('custom');
@@ -567,10 +698,24 @@ describe('agents › createCustomAgent', () => {
it('defaults empty name to the localized "Untitled agent" fallback', async () => {
const a = await loadAgents();
- const agent = await a.createCustomAgent({ description: 'desc' });
+ const agent = await a.createCustomAgent({ description: 'desc', category: 'general' });
expect(agent?.name).toBe('Untitled agent');
});
+ it('stores workflow skill references by display name', async () => {
+ writeSkillOnDisk('16e1bfcb3426', 'agent-creator');
+ const a = await loadAgents();
+ const agent = await a.createCustomAgent({
+ name: 'Builder',
+ description: 'desc',
+ category: 'rnd',
+ workflow: 'skill: follow the `16e1bfcb3426` skill',
+ });
+ expect(agent?.workflow).toBe('`agent-creator` skill');
+ const file = path.join(customAgentsDir(), agent?.agent_id || '', 'agent.json');
+ expect(JSON.parse(fs.readFileSync(file, 'utf8')).workflow).toBe('`agent-creator` skill');
+ });
+
it('rejects reserved names (collide with commander role / sidebar tab)', async () => {
const a = await loadAgents();
// Plain hits + whitespace + case variants all collapse to the same key.
@@ -578,7 +723,29 @@ describe('agents › createCustomAgent', () => {
await expect(a.createCustomAgent({ name: bad })).rejects.toThrow(/reserved/i);
}
// Sanity: the guard doesn't over-reach to nearby strings.
- await expect(a.createCustomAgent({ name: '副指挥官', description: 'desc' })).resolves.toBeTruthy();
+ await expect(a.createCustomAgent({ name: '副指挥官', description: 'desc', category: 'general' })).resolves.toBeTruthy();
+ });
+});
+
+describe('agents › createAgentFromBlocks', () => {
+ it('backfills the default category when model-authored creates omit it', async () => {
+ const a = await loadAgents();
+ const missing = await a.createAgentFromBlocks({
+ name: 'No Category',
+ description_en: 'desc',
+ workflow: 'Do the work.',
+ });
+ expect(missing?.category).toBe('general');
+
+ const created = await a.createAgentFromBlocks({
+ name: 'Data Agent',
+ description_en: 'desc',
+ workflow: 'Analyze the data.',
+ category: 'data',
+ });
+ expect(created?.category).toBe('data');
+ const file = path.join(customAgentsDir(), created?.agent_id || '', 'agent.json');
+ expect(JSON.parse(fs.readFileSync(file, 'utf8')).category).toBe('data');
});
});
@@ -633,6 +800,17 @@ describe('agents › getAgent', () => {
expect(agent?.name).toBe('A');
expect(agent?.source).toBe('custom');
});
+
+ it('exposes legacy workflow skill ids as display names', async () => {
+ writeSkillOnDisk('16e1bfcb3426', 'agent-creator');
+ writeCustomAgent('abc', {
+ name: 'A',
+ workflow: 'skill: follow the `16e1bfcb3426` skill',
+ });
+ const a = await loadAgents();
+ const agent = await a.getAgent('abc');
+ expect(agent?.workflow).toBe('`agent-creator` skill');
+ });
});
describe('agents › updateCustomAgent', () => {
@@ -647,6 +825,18 @@ describe('agents › updateCustomAgent', () => {
expect(updated?.workflow).toBe('wf'); // preserved
});
+ it('normalizes workflow skill references on update', async () => {
+ writeSkillOnDisk('efb0fe5d9664', 'skill-creator');
+ writeCustomAgent('abc', { name: 'Old', workflow: 'wf' });
+ const a = await loadAgents();
+ const updated = await a.updateCustomAgent('abc', {
+ workflow: 'skill: follow the efb0fe5d9664 skill',
+ });
+ expect(updated?.workflow).toBe('`skill-creator` skill');
+ const file = path.join(customAgentsDir(), 'abc', 'agent.json');
+ expect(JSON.parse(fs.readFileSync(file, 'utf8')).workflow).toBe('`skill-creator` skill');
+ });
+
it('backfills empty name to the localized "Untitled agent" fallback', async () => {
writeCustomAgent('abc', { name: 'Old' });
const a = await loadAgents();
@@ -984,9 +1174,10 @@ describe('agents › deleteCustomAgent', () => {
describe('agents › buildAgentEditSystemPrompt', () => {
it('substitutes agent fields and drops the removed skills_list placeholder', async () => {
const a = await loadAgents();
- const sys = a.buildAgentEditSystemPrompt({
+ const sys = await a.buildAgentEditSystemPrompt({
name: 'Researcher',
description: '一句话简介',
+ category: 'rnd',
workflow: '1. step one\n2. step two',
});
expect(sys).toContain('Researcher');
@@ -994,6 +1185,8 @@ describe('agents › buildAgentEditSystemPrompt', () => {
expect(sys).toContain('step one');
// Migration check: template no longer carries the redundant skills list.
expect(sys).not.toContain('$skills_list');
+ expect(sys).not.toContain('$category');
+ expect(sys).not.toContain('$category_field_definition');
expect(sys).not.toMatch(/##\s*可用的\s*skill/);
// Not a user-message prefix anymore — no trailing input footer.
expect(sys).not.toMatch(/##\s*用户的输入/);
@@ -1001,7 +1194,7 @@ describe('agents › buildAgentEditSystemPrompt', () => {
it('falls back to (not provided) when fields are empty', async () => {
const a = await loadAgents();
- const sys = a.buildAgentEditSystemPrompt({});
+ const sys = await a.buildAgentEditSystemPrompt({});
expect(sys).toContain('(not provided)');
});
});
@@ -1010,7 +1203,7 @@ describe('agents › list cache invalidation', () => {
it('picks up newly created agents on next listAgents', async () => {
const a = await loadAgents();
expect(await a.listAgents()).toEqual([]);
- await a.createCustomAgent({ name: 'New', description: 'desc' });
+ await a.createCustomAgent({ name: 'New', description: 'desc', category: 'general' });
const list = await a.listAgents();
expect(list).toHaveLength(1);
expect(list[0].name).toBe('New');
@@ -1018,11 +1211,43 @@ describe('agents › list cache invalidation', () => {
it('reflects updates immediately', async () => {
const a = await loadAgents();
- const agent = await a.createCustomAgent({ name: 'V1', description: 'desc' });
+ const agent = await a.createCustomAgent({ name: 'V1', description: 'desc', category: 'general' });
await a.updateCustomAgent(agent!.agent_id, { name: 'V2' });
const list = await a.listAgents();
expect(list[0].name).toBe('V2');
});
+
+ it('cache-only invalidator picks up marketplace file rewrites', async () => {
+ const parent = builtinAgentsDir();
+ const dir = path.join(parent, 'platform-agent');
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'agent.json'), JSON.stringify({
+ agent_id: 'platform-agent',
+ name: 'Old platform agent',
+ description: '',
+ workflow: '',
+ }));
+ const fixedStamp = new Date('2026-01-01T00:00:00.000Z');
+ fs.utimesSync(parent, fixedStamp, fixedStamp);
+
+ const a = await loadAgents();
+ expect((await a.listAgents()).find((x) => x.agent_id === 'platform-agent')?.name)
+ .toBe('Old platform agent');
+
+ fs.writeFileSync(path.join(dir, 'agent.json'), JSON.stringify({
+ agent_id: 'platform-agent',
+ name: 'New platform agent',
+ description: '',
+ workflow: '',
+ }));
+ fs.utimesSync(parent, fixedStamp, fixedStamp);
+
+ expect((await a.listAgents()).find((x) => x.agent_id === 'platform-agent')?.name)
+ .toBe('Old platform agent');
+ a.clearAgentListCache();
+ expect((await a.listAgents()).find((x) => x.agent_id === 'platform-agent')?.name)
+ .toBe('New platform agent');
+ });
});
// (The legacy marketplace-sentinel / data/builtin sync tests are gone. Marketplace
diff --git a/test/main/features/expert_signals/event.test.ts b/test/main/features/expert_signals/event.test.ts
new file mode 100644
index 00000000..a1690eb0
--- /dev/null
+++ b/test/main/features/expert_signals/event.test.ts
@@ -0,0 +1,197 @@
+import { describe, it, expect } from 'vitest';
+import {
+ buildRetrySignal,
+ buildSkipSignal,
+ buildFormLeftBlankSignals,
+ buildToolFailureSignal,
+ buildSkillAdvertisedSignal,
+ buildSkillInvokedSignal,
+ buildAgentDispatchedSignal,
+} from '../../../../src/main/features/expert_signals/extractors/event';
+
+describe('expert_signals.event › retry/skip builders', () => {
+ it('retry: stamps step_index in metadata', () => {
+ const sig = buildRetrySignal({
+ cid: 'c1', aid: 'a1', turn_id: 't1', step_index: 3,
+ });
+ expect(sig.type).toBe('retry');
+ expect(sig.aid).toBe('a1');
+ expect(sig.metadata?.step_index).toBe(3);
+ });
+
+ it('skip: same shape as retry but type=skip', () => {
+ const sig = buildSkipSignal({
+ cid: 'c1', aid: 'a1', turn_id: 't1', step_index: 3,
+ });
+ expect(sig.type).toBe('skip');
+ expect(sig.metadata?.step_index).toBe(3);
+ });
+});
+
+describe('expert_signals.event › form_left_blank', () => {
+ const fields = [
+ { id: 'project_dir', required: true, default: '' },
+ { id: 'review_depth', type: 'select', required: false, default: 'quick' },
+ { id: 'target_branch', type: 'text', required: false, default: 'main' },
+ ];
+
+ it('positive: required field empty → emits with was_required=true', () => {
+ const out = buildFormLeftBlankSignals({
+ cid: 'c1', aid: 'a1', turn_id: 't1', msg_id: 'm1',
+ fields,
+ values: { project_dir: '', review_depth: 'quick', target_branch: 'main' },
+ });
+ const projectDir = out.find((s) => (s.metadata as any)?.input_id === 'project_dir');
+ expect(projectDir).toBeDefined();
+ expect(projectDir!.metadata!.was_required).toBe(true);
+ });
+
+ it('positive: non-required unchanged from default → emits used_default=true', () => {
+ const out = buildFormLeftBlankSignals({
+ cid: 'c1', aid: 'a1', turn_id: 't1', msg_id: 'm1',
+ fields,
+ values: { project_dir: '/some/path', review_depth: 'quick', target_branch: 'main' },
+ });
+ const depth = out.find((s) => (s.metadata as any)?.input_id === 'review_depth');
+ expect(depth).toBeDefined();
+ expect(depth!.metadata!.used_default).toBe(true);
+ const branch = out.find((s) => (s.metadata as any)?.input_id === 'target_branch');
+ expect(branch).toBeDefined();
+ expect(branch!.metadata!.used_default).toBe(true);
+ });
+
+ it('negative: user changed every field → no signals', () => {
+ const out = buildFormLeftBlankSignals({
+ cid: 'c1', aid: 'a1', turn_id: 't1', msg_id: 'm1',
+ fields,
+ values: { project_dir: '/x', review_depth: 'deep', target_branch: 'develop' },
+ });
+ expect(out).toEqual([]);
+ });
+
+ it('negative: required field filled, no defaults equal → no signals', () => {
+ const out = buildFormLeftBlankSignals({
+ cid: 'c1', aid: 'a1', turn_id: 't1', msg_id: 'm1',
+ fields: [
+ { id: 'name', required: true, default: '' },
+ ],
+ values: { name: 'Alice' },
+ });
+ expect(out).toEqual([]);
+ });
+});
+
+describe('expert_signals.event › tool_failure', () => {
+ it('truncates error_excerpt to 200 chars', () => {
+ const long = 'x'.repeat(500);
+ const sig = buildToolFailureSignal({
+ cid: 'c1', aid: 'a1', turn_id: 't1',
+ tool_name: 'bash', error_excerpt: long,
+ });
+ expect((sig.metadata!.error_excerpt as string).length).toBe(200);
+ });
+});
+
+describe('expert_signals.event › skill_advertised builder', () => {
+ it('positive: groups by system + skill_ids list', () => {
+ const sig = buildSkillAdvertisedSignal({
+ cid: 'c1', aid: 'a1', turn_id: 'm_42',
+ system: 'A.custom',
+ skill_ids: ['summary-writer', 'search-docs'],
+ });
+ expect(sig.type).toBe('skill_advertised');
+ expect(sig.delta?.system).toBe('A.custom');
+ expect(sig.delta?.skill_ids).toEqual(['summary-writer', 'search-docs']);
+ expect(sig.extractor_version).toBe('[email protected]');
+ });
+
+ it('positive: System B emits with aid=agent_id (per-agent SkillStore)', () => {
+ const sig = buildSkillAdvertisedSignal({
+ cid: 'c1', aid: 'agent_x', turn_id: 'm_42',
+ system: 'B',
+ skill_ids: ['my-custom-pricing'],
+ });
+ expect(sig.aid).toBe('agent_x');
+ expect(sig.delta?.system).toBe('B');
+ });
+
+ it('negative: empty skill_ids list still emits a record (consumer sees the system fired but no ids)', () => {
+ // The buffer in turn_hooks dedups + groups, so this builder is fine
+ // with an empty list. Consumer behavior is to treat as a no-skill turn.
+ const sig = buildSkillAdvertisedSignal({
+ cid: 'c1', aid: 'a1', turn_id: 'm_42',
+ system: 'A.platform',
+ skill_ids: [],
+ });
+ expect(sig.delta?.skill_ids).toEqual([]);
+ });
+});
+
+describe('expert_signals.event › skill_invoked builder', () => {
+ it('positive: carries system + skill_id + trigger', () => {
+ const sig = buildSkillInvokedSignal({
+ cid: 'c1', aid: 'agent_x', turn_id: 'm_42',
+ system: 'A.platform',
+ skill_id: 'a1b2c3d4e5f6',
+ trigger: 'read_file',
+ });
+ expect(sig.type).toBe('skill_invoked');
+ expect(sig.delta?.system).toBe('A.platform');
+ expect(sig.delta?.skill_id).toBe('a1b2c3d4e5f6');
+ expect(sig.delta?.trigger).toBe('read_file');
+ });
+
+ it('positive: System B invocation carries owner aid', () => {
+ const sig = buildSkillInvokedSignal({
+ cid: 'c1', aid: 'agent_x', turn_id: 'm_42',
+ system: 'B',
+ skill_id: 'self-evolved',
+ trigger: 'read_file',
+ });
+ expect(sig.aid).toBe('agent_x');
+ expect(sig.delta?.system).toBe('B');
+ });
+});
+
+describe('expert_signals.event › agent_dispatched builder', () => {
+ it('positive: parallel group, candidates == dispatched (current model)', () => {
+ const sig = buildAgentDispatchedSignal({
+ cid: 'c1',
+ turn_id: 'c1:plan:dispatch:1000000:0',
+ candidates: ['aid_x', 'aid_y'],
+ dispatched: ['aid_x', 'aid_y'],
+ parallel_group: 'g1',
+ });
+ expect(sig.type).toBe('agent_dispatched');
+ expect(sig.aid).toBeNull(); // commander-scope signal
+ expect(sig.delta?.candidates).toEqual(['aid_x', 'aid_y']);
+ expect(sig.delta?.dispatched).toEqual(['aid_x', 'aid_y']);
+ expect(sig.delta?.parallel_group).toBe('g1');
+ });
+
+ it('positive: solo step → parallel_group=null', () => {
+ const sig = buildAgentDispatchedSignal({
+ cid: 'c1',
+ turn_id: 'c1:plan:dispatch:1000000:0',
+ candidates: ['aid_x'],
+ dispatched: ['aid_x'],
+ parallel_group: null,
+ });
+ expect(sig.delta?.parallel_group).toBeNull();
+ });
+
+ it('positive: candidates / dispatched arrays are copied (no shared reference)', () => {
+ const cand = ['aid_x', 'aid_y'];
+ const sig = buildAgentDispatchedSignal({
+ cid: 'c1',
+ turn_id: 't1',
+ candidates: cand,
+ dispatched: cand,
+ parallel_group: null,
+ });
+ cand.push('aid_z');
+ // Builder snapshotted via `.slice()` — mutations after emit don't bleed in.
+ expect(sig.delta?.candidates).toEqual(['aid_x', 'aid_y']);
+ expect(sig.delta?.dispatched).toEqual(['aid_x', 'aid_y']);
+ });
+});
diff --git a/test/main/features/expert_signals/silence.test.ts b/test/main/features/expert_signals/silence.test.ts
new file mode 100644
index 00000000..396c047e
--- /dev/null
+++ b/test/main/features/expert_signals/silence.test.ts
@@ -0,0 +1,72 @@
+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';
+
+// Pre-set ORKAS_WORKSPACE_ROOT before importing anything that loads paths.ts.
+const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'sig-silence-'));
+process.env.ORKAS_WORKSPACE_ROOT = TMP;
+fs.writeFileSync(path.join(TMP, 'users.json'),
+ JSON.stringify({ current_user_id: '12345678', users: [{ user_id: '12345678', created_at: new Date().toISOString() }] }));
+
+import { activateUser } from '../../../../src/main/features/users';
+activateUser('12345678');
+
+import {
+ scheduleSilenceCheck,
+ cancelSilenceCheck,
+ _clearAllPending,
+} from '../../../../src/main/features/expert_signals/extractors/silence';
+import { querySignals } from '../../../../src/main/features/expert_signals';
+
+describe('expert_signals.silence', () => {
+ beforeEach(() => {
+ _clearAllPending();
+ });
+ afterEach(() => {
+ _clearAllPending();
+ });
+
+ it('positive: timer fires after threshold → silence appears', async () => {
+ scheduleSilenceCheck({
+ uid: '12345678', cid: 'cid-silence-1', aid: 'agent-x',
+ turn_id: 'msg-1', msg_ids: ['msg-1'],
+ thresholdMs: 30,
+ });
+ await new Promise((r) => setTimeout(r, 80));
+ // Read what got emitted today
+ const sigs = await querySignals({ types: ['silence'], cid: 'cid-silence-1' });
+ expect(sigs.length).toBeGreaterThan(0);
+ expect(sigs[0].turn_id).toBe('msg-1');
+ });
+
+ it('negative: cancel before timer fires → no silence', async () => {
+ scheduleSilenceCheck({
+ uid: '12345678', cid: 'cid-silence-2', aid: 'agent-x',
+ turn_id: 'msg-2', msg_ids: ['msg-2'],
+ thresholdMs: 100,
+ });
+ cancelSilenceCheck('12345678', 'cid-silence-2');
+ await new Promise((r) => setTimeout(r, 150));
+ const sigs = await querySignals({ types: ['silence'], cid: 'cid-silence-2' });
+ expect(sigs.length).toBe(0);
+ });
+
+ it('rescheduling cancels the previous timer', async () => {
+ scheduleSilenceCheck({
+ uid: '12345678', cid: 'cid-silence-3', aid: 'agent-x',
+ turn_id: 'msg-3a', msg_ids: ['msg-3a'],
+ thresholdMs: 50,
+ });
+ // Schedule a fresh one before the first fires
+ scheduleSilenceCheck({
+ uid: '12345678', cid: 'cid-silence-3', aid: 'agent-x',
+ turn_id: 'msg-3b', msg_ids: ['msg-3b'],
+ thresholdMs: 200,
+ });
+ await new Promise((r) => setTimeout(r, 120));
+ const sigs = await querySignals({ types: ['silence'], cid: 'cid-silence-3' });
+ // Neither has fired yet (first cancelled, second still pending)
+ expect(sigs.length).toBe(0);
+ });
+});
diff --git a/test/main/features/expert_signals/skill_path.test.ts b/test/main/features/expert_signals/skill_path.test.ts
new file mode 100644
index 00000000..427be3d3
--- /dev/null
+++ b/test/main/features/expert_signals/skill_path.test.ts
@@ -0,0 +1,119 @@
+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';
+
+// paths.ts resolves WS_ROOT from env at module load. We don't write any
+// files in these tests (parseSkillPath is pure path-string parsing) — just
+// need WS_ROOT set so the path helpers compute deterministic prefixes.
+
+let tmpDir: string;
+let prevWs: string | undefined;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-skill-path-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ vi.resetModules();
+});
+
+afterEach(() => {
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+describe('expert_signals.skill_path › positives', () => {
+ it('A.custom: <uid>/cloud/skills/<id>/SKILL.md', async () => {
+ const { parseSkillPath } = await import('../../../../src/main/features/expert_signals/skill_path');
+ const p = await import('../../../../src/main/paths');
+ const abs = path.join(p.userSkillsDir('uid1'), 'summary-writer', 'SKILL.md');
+ expect(parseSkillPath(abs, 'uid1')).toEqual({
+ system: 'A.custom',
+ skill_id: 'summary-writer',
+ });
+ });
+
+ it('A.platform: <uid>/local/marketplace/skills/<id>/SKILL.md', async () => {
+ const { parseSkillPath } = await import('../../../../src/main/features/expert_signals/skill_path');
+ const p = await import('../../../../src/main/paths');
+ const abs = path.join(p.userMarketplaceSkillsDir('uid1'), 'a1b2c3d4e5f6', 'SKILL.md');
+ expect(parseSkillPath(abs, 'uid1')).toEqual({
+ system: 'A.platform',
+ skill_id: 'a1b2c3d4e5f6',
+ });
+ });
+
+ it('B: <uid>/cloud/agents/<aid>/skills/<sid>/SKILL.md (carries agent_id)', async () => {
+ const { parseSkillPath } = await import('../../../../src/main/features/expert_signals/skill_path');
+ const p = await import('../../../../src/main/paths');
+ const abs = path.join(p.agentEvolvedSkillsDir('uid1', 'agent_x'), 'self-evolved-skill', 'SKILL.md');
+ expect(parseSkillPath(abs, 'uid1')).toEqual({
+ system: 'B',
+ skill_id: 'self-evolved-skill',
+ agent_id: 'agent_x',
+ });
+ });
+});
+
+describe('expert_signals.skill_path › negatives', () => {
+ it('non-SKILL.md filename under a skill root → null', async () => {
+ const { parseSkillPath } = await import('../../../../src/main/features/expert_signals/skill_path');
+ const p = await import('../../../../src/main/paths');
+ const abs = path.join(p.userSkillsDir('uid1'), 'foo', 'helper.py');
+ expect(parseSkillPath(abs, 'uid1')).toBeNull();
+ });
+
+ it('SKILL.md outside any skill root → null', async () => {
+ const { parseSkillPath } = await import('../../../../src/main/features/expert_signals/skill_path');
+ const p = await import('../../../../src/main/paths');
+ const abs = path.join(p.userRoot('uid1'), 'cloud', 'memory', 'SKILL.md');
+ expect(parseSkillPath(abs, 'uid1')).toBeNull();
+ });
+
+ it('A.custom with extra nested dir → null (skill_id must be a leaf dir)', async () => {
+ const { parseSkillPath } = await import('../../../../src/main/features/expert_signals/skill_path');
+ const p = await import('../../../../src/main/paths');
+ // .../skills/foo/bar/SKILL.md — two segments before SKILL.md, not the
+ // expected one. Catches accidental nested-skill layouts.
+ const abs = path.join(p.userSkillsDir('uid1'), 'foo', 'bar', 'SKILL.md');
+ expect(parseSkillPath(abs, 'uid1')).toBeNull();
+ });
+
+ it('System B path missing the literal "skills" segment → null', async () => {
+ const { parseSkillPath } = await import('../../../../src/main/features/expert_signals/skill_path');
+ const p = await import('../../../../src/main/paths');
+ // Wrong shape: <agents-root>/<aid>/meta/<sid>/SKILL.md (meta, not skills)
+ const abs = path.join(p.userAgentsDir('uid1'), 'agent_x', 'meta', 'sid', 'SKILL.md');
+ expect(parseSkillPath(abs, 'uid1')).toBeNull();
+ });
+
+ it('different uid → null (path scoping is uid-specific)', async () => {
+ const { parseSkillPath } = await import('../../../../src/main/features/expert_signals/skill_path');
+ const p = await import('../../../../src/main/paths');
+ const abs = path.join(p.userSkillsDir('uid1'), 'foo', 'SKILL.md');
+ expect(parseSkillPath(abs, 'uid2')).toBeNull();
+ });
+
+ it('empty inputs → null (defensive)', async () => {
+ const { parseSkillPath, isSkillMdPath } = await import('../../../../src/main/features/expert_signals/skill_path');
+ expect(parseSkillPath('', 'uid1')).toBeNull();
+ expect(parseSkillPath('/some/path/SKILL.md', '')).toBeNull();
+ expect(isSkillMdPath('', 'uid1')).toBe(false);
+ });
+});
+
+describe('expert_signals.skill_path › isSkillMdPath delegates to parseSkillPath', () => {
+ it('returns true for an A.custom path', async () => {
+ const { isSkillMdPath } = await import('../../../../src/main/features/expert_signals/skill_path');
+ const p = await import('../../../../src/main/paths');
+ const abs = path.join(p.userSkillsDir('uid1'), 'foo', 'SKILL.md');
+ expect(isSkillMdPath(abs, 'uid1')).toBe(true);
+ });
+
+ it('returns false for a non-SKILL.md path', async () => {
+ const { isSkillMdPath } = await import('../../../../src/main/features/expert_signals/skill_path');
+ const p = await import('../../../../src/main/paths');
+ const abs = path.join(p.userSkillsDir('uid1'), 'foo', 'README.md');
+ expect(isSkillMdPath(abs, 'uid1')).toBe(false);
+ });
+});
diff --git a/test/main/features/expert_signals/storage.test.ts b/test/main/features/expert_signals/storage.test.ts
new file mode 100644
index 00000000..be18cb10
--- /dev/null
+++ b/test/main/features/expert_signals/storage.test.ts
@@ -0,0 +1,72 @@
+import { describe, it, expect, beforeAll } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'sig-storage-'));
+process.env.ORKAS_WORKSPACE_ROOT = TMP;
+// Seed users.json so activateUser doesn't have to invent one
+fs.writeFileSync(path.join(TMP, 'users.json'),
+ JSON.stringify({ current_user_id: '99999999', users: [{ user_id: '99999999', created_at: new Date().toISOString() }] }));
+
+import { activateUser } from '../../../../src/main/features/users';
+activateUser('99999999');
+
+import { emitSignal, querySignals } from '../../../../src/main/features/expert_signals';
+import type { SignalInput } from '../../../../src/main/features/expert_signals/types';
+
+function makeInput(type: SignalInput['type'], over: Partial<SignalInput> = {}): SignalInput {
+ return {
+ type, source: 'event',
+ cid: 'storage-test-cid', aid: 'a1', turn_id: 't1',
+ context_ref: { msg_ids: ['m1'] },
+ extractor_version: '[email protected]',
+ ...over,
+ };
+}
+
+describe('expert_signals.storage', () => {
+ beforeAll(async () => {
+ // give the first appendSignal time to land before the suite queries
+ emitSignal('99999999', makeInput('accept'));
+ await new Promise((r) => setTimeout(r, 50));
+ });
+
+ it('emit + query roundtrip', async () => {
+ emitSignal('99999999', makeInput('correction'));
+ await new Promise((r) => setTimeout(r, 50));
+ const sigs = await querySignals({ types: ['correction'] });
+ expect(sigs.length).toBeGreaterThan(0);
+ expect(sigs[0].type).toBe('correction');
+ expect(sigs[0].id).toMatch(/^sig_/);
+ expect(sigs[0].ts).toMatch(/^\d{4}-\d{2}-\d{2}T/);
+ });
+
+ it('filter by cid', async () => {
+ emitSignal('99999999', makeInput('retry', { cid: 'cid-A' }));
+ emitSignal('99999999', makeInput('retry', { cid: 'cid-B' }));
+ await new Promise((r) => setTimeout(r, 50));
+ const sigsA = await querySignals({ types: ['retry'], cid: 'cid-A' });
+ const sigsB = await querySignals({ types: ['retry'], cid: 'cid-B' });
+ expect(sigsA.every((s) => s.cid === 'cid-A')).toBe(true);
+ expect(sigsB.every((s) => s.cid === 'cid-B')).toBe(true);
+ });
+
+ it('filter by turn_id groups same-turn signals', async () => {
+ emitSignal('99999999', makeInput('correction', { turn_id: 'group-1' }));
+ emitSignal('99999999', makeInput('reject', { turn_id: 'group-1' }));
+ emitSignal('99999999', makeInput('accept', { turn_id: 'group-2' }));
+ await new Promise((r) => setTimeout(r, 50));
+ const group1 = await querySignals({ turn_id: 'group-1' });
+ expect(group1.length).toBe(2);
+ const types = group1.map((s) => s.type).sort();
+ expect(types).toEqual(['correction', 'reject']);
+ });
+
+ it('respects limit', async () => {
+ for (let i = 0; i < 5; i++) emitSignal('99999999', makeInput('skip'));
+ await new Promise((r) => setTimeout(r, 50));
+ const sigs = await querySignals({ types: ['skip'], limit: 2 });
+ expect(sigs.length).toBe(2);
+ });
+});
diff --git a/test/main/features/expert_signals/text.test.ts b/test/main/features/expert_signals/text.test.ts
new file mode 100644
index 00000000..4e06598b
--- /dev/null
+++ b/test/main/features/expert_signals/text.test.ts
@@ -0,0 +1,134 @@
+import { describe, it, expect } from 'vitest';
+import { extractTextSignals } from '../../../../src/main/features/expert_signals/extractors/text';
+
+// CLAUDE.md §9: text-processing extractor needs positive + negative fixtures.
+
+function ctx() {
+ return {
+ cid: 'cid-1',
+ aid: 'agent-x',
+ turn_id: 'msg-prev',
+ agent_last_text: 'Here is the Q3 profit: $5.2M',
+ msg_ids: ['msg-prev', 'msg-cur'],
+ };
+}
+
+describe('expert_signals.text › correction', () => {
+ it('positive: 不对 / 应该是 triggers correction', () => {
+ const out = extractTextSignals({
+ ...ctx(), user_msg: '不对,应该是 5.7M',
+ correction_detected: true,
+ });
+ expect(out.map((s) => s.type)).toContain('correction');
+ });
+
+ it('negative: "对不起" alone does NOT trigger correction', () => {
+ // detectUserCorrection returns false on plain apology — caller passes
+ // the boolean through. Asserts the extractor honours caller's verdict.
+ const out = extractTextSignals({
+ ...ctx(), user_msg: '对不起,我表达不清楚',
+ correction_detected: false,
+ });
+ expect(out.map((s) => s.type)).not.toContain('correction');
+ });
+});
+
+describe('expert_signals.text › reject', () => {
+ it('positive: "重新做一遍" triggers reject', () => {
+ const out = extractTextSignals({
+ ...ctx(), user_msg: '重新做一遍这部分',
+ correction_detected: false,
+ });
+ expect(out.map((s) => s.type)).toContain('reject');
+ });
+
+ it('negative: "重要的是" does NOT trigger reject', () => {
+ // "重" appears but not as a reject keyword — pattern requires 重新+verb.
+ const out = extractTextSignals({
+ ...ctx(), user_msg: '重要的是要保证准确性',
+ correction_detected: false,
+ });
+ expect(out.map((s) => s.type)).not.toContain('reject');
+ });
+});
+
+describe('expert_signals.text › accept (explicit)', () => {
+ it('positive: "好的" triggers accept', () => {
+ const out = extractTextSignals({
+ ...ctx(), user_msg: '好的,继续',
+ correction_detected: false,
+ });
+ expect(out.map((s) => s.type)).toContain('accept');
+ });
+
+ it('negative: "好" alone does NOT trigger (too noisy)', () => {
+ // Single 好 is ambiguous (could start a sentence). Pattern requires 好 + (的)?
+ // + punctuation/EOL — bare "好" doesn't match the anchored regex.
+ const out = extractTextSignals({
+ ...ctx(), user_msg: '好像有点问题',
+ correction_detected: false,
+ });
+ expect(out.map((s) => s.type)).not.toContain('accept');
+ });
+
+ it('does NOT emit accept when correction is detected (correction is stronger)', () => {
+ const out = extractTextSignals({
+ ...ctx(), user_msg: '好的,但实际上不对',
+ correction_detected: true,
+ });
+ const types = out.map((s) => s.type);
+ expect(types).toContain('correction');
+ expect(types).not.toContain('accept');
+ });
+});
+
+describe('expert_signals.text › edit', () => {
+ it('positive: user rewrites agent text with substantial diff', () => {
+ const out = extractTextSignals({
+ ...ctx(),
+ agent_last_text: 'Here is the Q3 profit summary written in formal style with all numbers',
+ user_msg: 'Here is the Q3 profit summary written more concisely',
+ correction_detected: false,
+ });
+ expect(out.map((s) => s.type)).toContain('edit');
+ });
+
+ it('negative: short question is not an edit', () => {
+ const out = extractTextSignals({
+ ...ctx(),
+ agent_last_text: 'Here is the Q3 profit summary written in formal style with all numbers',
+ user_msg: '什么时候出的?',
+ correction_detected: false,
+ });
+ expect(out.map((s) => s.type)).not.toContain('edit');
+ });
+
+ it('negative: identical echo is not an edit', () => {
+ const out = extractTextSignals({
+ ...ctx(),
+ agent_last_text: 'Here is the Q3 profit summary written in formal style with all numbers',
+ user_msg: 'Here is the Q3 profit summary written in formal style with all numbers',
+ correction_detected: false,
+ });
+ expect(out.map((s) => s.type)).not.toContain('edit');
+ });
+});
+
+describe('expert_signals.text › meta', () => {
+ it('returns empty array on empty user message', () => {
+ const out = extractTextSignals({
+ ...ctx(), user_msg: ' ', correction_detected: false,
+ });
+ expect(out).toEqual([]);
+ });
+
+ it('all emitted signals carry the same turn_id (group-by anchor)', () => {
+ const out = extractTextSignals({
+ ...ctx(), user_msg: '不对,重新做',
+ correction_detected: true,
+ });
+ expect(out.length).toBeGreaterThan(1);
+ const turnIds = new Set(out.map((s) => s.turn_id));
+ expect(turnIds.size).toBe(1);
+ });
+});
diff --git a/test/main/features/expert_signals/turn_buffer.test.ts b/test/main/features/expert_signals/turn_buffer.test.ts
new file mode 100644
index 00000000..b0471fc0
--- /dev/null
+++ b/test/main/features/expert_signals/turn_buffer.test.ts
@@ -0,0 +1,99 @@
+import { describe, it, expect } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+// Module-level setup mirrors storage.test.ts — WS_ROOT swap + activateUser
+// must run before any expert_signals import (storage caches active uid).
+const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'sig-skill-buffer-'));
+process.env.ORKAS_WORKSPACE_ROOT = TMP;
+fs.writeFileSync(path.join(TMP, 'users.json'),
+ JSON.stringify({ current_user_id: '99999991', users: [{ user_id: '99999991', created_at: new Date().toISOString() }] }));
+const UID = '99999991';
+
+import { activateUser } from '../../../../src/main/features/users';
+activateUser(UID);
+
+import { createSkillTurnBuffer } from '../../../../src/main/features/expert_signals/turn_hooks';
+import { querySignals } from '../../../../src/main/features/expert_signals';
+
+async function wait() { return new Promise((r) => setTimeout(r, 30)); }
+
+describe('expert_signals.turn_hooks › SkillTurnBuffer', () => {
+ it('groups advertised by system, dedups duplicates, emits one signal per system', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordAdvertised('summary-writer', 'A.custom');
+ buf.recordAdvertised('search-docs', 'A.custom');
+ // Duplicate (system, id) → deduped
+ buf.recordAdvertised('summary-writer', 'A.custom');
+ buf.recordAdvertised('a1b2c3d4e5f6', 'A.platform');
+ buf.recordAdvertised('learned-skill', 'B');
+
+ const cid = 'cid-buf-adv';
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: 'm_42', msg_ids: ['m_42'],
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['skill_advertised'], cid });
+ expect(sigs.length).toBe(3);
+ const bySystem = new Map(sigs.map((s) => [s.delta!.system, s]));
+ expect(bySystem.get('A.custom')!.delta!.skill_ids!.sort()).toEqual(['search-docs', 'summary-writer']);
+ expect(bySystem.get('A.platform')!.delta!.skill_ids).toEqual(['a1b2c3d4e5f6']);
+ expect(bySystem.get('B')!.delta!.skill_ids).toEqual(['learned-skill']);
+ for (const s of sigs) {
+ expect(s.turn_id).toBe('m_42');
+ expect(s.aid).toBe('agent_x');
+ }
+ });
+
+ it('skill_invoked: deduped per (system, id); same id under different systems is distinct', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordInvoked('summary-writer', 'A.custom', 'read_file');
+ buf.recordInvoked('summary-writer', 'A.custom', 'read_file'); // dup
+ buf.recordInvoked('summary-writer', 'B', 'read_file'); // distinct: different system
+ buf.recordInvoked('other-skill', 'A.custom', 'read_file');
+
+ const cid = 'cid-buf-inv';
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: 'm_43', msg_ids: ['m_43'],
+ });
+ await wait();
+
+ const sigs = await querySignals({ types: ['skill_invoked'], cid });
+ expect(sigs.length).toBe(3);
+ for (const s of sigs) {
+ expect(s.delta!.trigger).toBe('read_file');
+ expect(s.turn_id).toBe('m_43');
+ }
+ });
+
+ it('drops without turn_id (silent turn protection)', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordAdvertised('summary-writer', 'A.custom');
+ const cid = 'cid-buf-drop';
+ buf.drainAndEmit({
+ uid: UID, cid, aid: 'agent_x',
+ turn_id: '', msg_ids: [],
+ });
+ await wait();
+
+ const sigs = await querySignals({ cid });
+ expect(sigs.length).toBe(0);
+ });
+
+ it('clears buffer after drain (second drain emits nothing for the same data)', async () => {
+ const buf = createSkillTurnBuffer();
+ buf.recordAdvertised('s1', 'A.custom');
+ const cid = 'cid-buf-clear';
+ buf.drainAndEmit({ uid: UID, cid, aid: null, turn_id: 'm1', msg_ids: ['m1'] });
+ buf.drainAndEmit({ uid: UID, cid, aid: null, turn_id: 'm2', msg_ids: ['m2'] });
+ await wait();
+
+ const sigs = await querySignals({ types: ['skill_advertised'], cid });
+ expect(sigs.length).toBe(1);
+ expect(sigs[0].turn_id).toBe('m1');
+ });
+});
diff --git a/test/main/features/group_chat/bus.test.ts b/test/main/features/group_chat/bus.test.ts
index df8c8099..ca10a636 100644
--- a/test/main/features/group_chat/bus.test.ts
+++ b/test/main/features/group_chat/bus.test.ts
@@ -11,12 +11,24 @@ import * as path from 'node:path';
// state, not actual model output.
vi.mock('../../../../src/main/model/client', () => ({
async *streamChatWithModel(_opts: any) {
+ if (String(_opts?.message || '').includes('ARTIFACT_EVENT_TEST')) {
+ _opts?.onArtifactCreated?.({ id: 'art-live-1', title: 'Live App' });
+ }
yield { type: 'final', text: '' };
yield { type: 'done' };
},
async chatWithModel() { return { ok: true, text: '', error: '', aborted: false }; },
}));
+const cliRunMock = vi.hoisted(() => ({ calls: [] as any[] }));
+vi.mock('../../../../src/main/features/local_agents/runner', () => ({
+ run: vi.fn(async (opts: any) => {
+ cliRunMock.calls.push(opts);
+ opts.onEvent({ type: 'done', status: 'completed', output: 'ok' });
+ return { runId: 'mock-run', status: 'completed', output: 'ok' };
+ }),
+}));
+
let tmpDir: string;
let prevWs: string | undefined;
const TEST_UID = 'u1';
@@ -29,6 +41,7 @@ beforeEach(async () => {
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
vi.resetModules();
+ cliRunMock.calls.length = 0;
const users = await import('../../../../src/main/features/users');
users.activateUser(TEST_UID);
@@ -51,6 +64,16 @@ afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
+async function waitForQuiescent(uid: string, cid: string, timeoutMs = 2000) {
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const start = Date.now();
+ while (Date.now() - start < timeoutMs) {
+ if (bus.isQuiescent(uid, cid)) return;
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ throw new Error(`bus did not quiesce for ${uid}/${cid}`);
+}
+
describe('group_chat bus › enqueue routing + persistence', () => {
it('user → commander default route persists with to=["commander"]', async () => {
const bus = await import('../../../../src/main/features/group_chat/bus');
@@ -106,6 +129,32 @@ describe('group_chat bus › enqueue routing + persistence', () => {
expect(JSON.parse(sliceLine).id).toBe(persisted.id);
});
+ it('emits artifact_created as soon as create_artifact reports success', async () => {
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const events: any[] = [];
+ bus.subscribe(TEST_UID, TEST_CID, (ev) => events.push(ev));
+
+ await bus.enqueue({
+ uid: TEST_UID, cid: TEST_CID, fromActorId: 'user',
+ text: 'ARTIFACT_EVENT_TEST',
+ });
+ await waitForQuiescent(TEST_UID, TEST_CID);
+
+ const artifactIdx = events.findIndex((e) => e.type === 'artifact_created');
+ const finalIdx = events.findIndex((e) =>
+ e.type === 'message' && e.turn_end === true && e.msg?.from === 'commander');
+ expect(artifactIdx).toBeGreaterThanOrEqual(0);
+ expect(finalIdx).toBeGreaterThan(artifactIdx);
+ expect(events[artifactIdx]).toMatchObject({
+ cid: TEST_CID,
+ actor: 'commander',
+ artifact: { id: 'art-live-1', title: 'Live App', agent_id: 'commander' },
+ });
+ expect(events[finalIdx].msg.artifacts).toEqual([
+ { id: 'art-live-1', title: 'Live App', agent_id: 'commander' },
+ ]);
+ });
+
// `isQuiescent` reflects the in-memory queue/running state — exercised
// implicitly by every bus-integration `waitForQuiescent` call. A
// standalone tautological test (newly-empty bus is quiescent) wasn't
@@ -128,6 +177,99 @@ describe('group_chat bus › enqueue routing + persistence', () => {
// directly, but isQuiescent reports true (since cid state is gone).
expect(bus.isQuiescent(TEST_UID, TEST_CID)).toBe(true);
});
+
+ it('initialises a coding CLI conversation cwd from the agent project-dir setting without replaying on first dispatch', async () => {
+ const paths = await import('../../../../src/main/paths');
+ const agentFile = path.join(paths.agentDir(TEST_UID, AGENT_ID), 'agent.json');
+ const spec = JSON.parse(fs.readFileSync(agentFile, 'utf8'));
+ spec.runtime = { kind: 'cli', cli: 'codex' };
+ fs.writeFileSync(agentFile, JSON.stringify(spec));
+
+ const projectDir = path.join(tmpDir, 'repo');
+ fs.mkdirSync(projectDir);
+ const agents = await import('../../../../src/main/features/agents');
+ await agents.setAgentCliProjectDir(TEST_UID, AGENT_ID, projectDir);
+
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const cid = 'cid-coding-dir';
+ await bus.enqueue({
+ uid: TEST_UID, cid, fromActorId: 'user',
+ text: `@${AGENT_NAME} 看一下这个项目`,
+ });
+ await waitForQuiescent(TEST_UID, cid);
+
+ expect(cliRunMock.calls).toHaveLength(1);
+ expect(cliRunMock.calls[0].cwd).toBe(projectDir);
+ expect(cliRunMock.calls[0].prompt).toContain('看一下这个项目');
+ expect(cliRunMock.calls[0].prompt).not.toContain('## Conversation so far');
+ const st = await state.readState(TEST_UID, cid);
+ expect(st.coding_project_dir).toBe(projectDir);
+ expect(st.coding_project_dir_explicit).toBe(true);
+ });
+
+ it('does not replay prior visible history when a CLI session resumes', async () => {
+ const paths = await import('../../../../src/main/paths');
+ const agentFile = path.join(paths.agentDir(TEST_UID, AGENT_ID), 'agent.json');
+ const spec = JSON.parse(fs.readFileSync(agentFile, 'utf8'));
+ spec.runtime = { kind: 'cli', cli: 'codex' };
+ fs.writeFileSync(agentFile, JSON.stringify(spec));
+
+ const cid = 'cid-coding-resume';
+ const visibility = await import('../../../../src/main/features/group_chat/visibility');
+ await visibility.appendVisible(TEST_UID, cid, {
+ id: 'older-history',
+ ts: '2026-05-19T00:00:00.000Z',
+ from: 'user',
+ to: [AGENT_ID],
+ text: 'DO_NOT_PASS_WHEN_RESUMING',
+ }, [AGENT_ID]);
+ const sessions = await import('../../../../src/main/features/local_agents/sessions');
+ await sessions.setSessionId(TEST_UID, cid, AGENT_ID, 'codex', 'thread-123');
+
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ await bus.enqueue({
+ uid: TEST_UID, cid, fromActorId: 'user',
+ text: `@${AGENT_NAME} 继续`,
+ });
+ await waitForQuiescent(TEST_UID, cid);
+
+ expect(cliRunMock.calls).toHaveLength(1);
+ expect(cliRunMock.calls[0].resumeSessionId).toBe('thread-123');
+ expect(cliRunMock.calls[0].prompt).not.toContain('DO_NOT_PASS_WHEN_RESUMING');
+ expect(cliRunMock.calls[0].prompt).not.toContain('## Conversation so far');
+ });
+
+ it('bridges prior visible history when starting a fresh CLI session with existing context', async () => {
+ const paths = await import('../../../../src/main/paths');
+ const agentFile = path.join(paths.agentDir(TEST_UID, AGENT_ID), 'agent.json');
+ const spec = JSON.parse(fs.readFileSync(agentFile, 'utf8'));
+ spec.runtime = { kind: 'cli', cli: 'codex' };
+ fs.writeFileSync(agentFile, JSON.stringify(spec));
+
+ const cid = 'cid-coding-bridge';
+ const visibility = await import('../../../../src/main/features/group_chat/visibility');
+ await visibility.appendVisible(TEST_UID, cid, {
+ id: 'older-history',
+ ts: '2026-05-19T00:00:00.000Z',
+ from: 'user',
+ to: [AGENT_ID],
+ text: 'PASS_WHEN_FRESH_WITH_PRIOR_CONTEXT',
+ }, [AGENT_ID]);
+
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ await bus.enqueue({
+ uid: TEST_UID, cid, fromActorId: 'user',
+ text: `@${AGENT_NAME} 换目录后继续`,
+ });
+ await waitForQuiescent(TEST_UID, cid);
+
+ expect(cliRunMock.calls).toHaveLength(1);
+ expect(cliRunMock.calls[0].resumeSessionId).toBeUndefined();
+ expect(cliRunMock.calls[0].prompt).toContain('## Conversation so far');
+ expect(cliRunMock.calls[0].prompt).toContain('PASS_WHEN_FRESH_WITH_PRIOR_CONTEXT');
+ expect(cliRunMock.calls[0].prompt).toContain('换目录后继续');
+ });
});
describe('group_chat bus › abort', () => {
diff --git a/test/main/features/group_chat/plan_executor.test.ts b/test/main/features/group_chat/plan_executor.test.ts
index 7c9cbdc7..ca66cf99 100644
--- a/test/main/features/group_chat/plan_executor.test.ts
+++ b/test/main/features/group_chat/plan_executor.test.ts
@@ -544,4 +544,111 @@ describe('plan_executor › auto plan_update', () => {
expect(finalPlan?.steps[0].output_summary).toBe('A done');
expect(finalPlan?.completed_signaled).toBe(true); // single-step plan terminal → signal fired
}, 10_000);
+
+ it('manual commander dispatch still completes the matching in_progress step', async () => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [
+ { type: 'final', text: 'manual dispatch result' },
+ ]);
+
+ await plan.setPlan(TEST_UID, cid, {
+ initial_message: 'q',
+ steps: [{ title: 'a', assignee: A_NAME, input: 'do', wait_for: [] }],
+ });
+ await state.seedReservedActors(TEST_UID, cid);
+ await state.ensureAgentMember(TEST_UID, cid, A_ID, A_NAME);
+ await plan.updateStep(TEST_UID, cid, 1, 'in_progress');
+
+ await bus.enqueue({
+ uid: TEST_UID,
+ cid,
+ fromActorId: 'commander',
+ text: `@${A_NAME} 请继续执行第 1 步`,
+ forceTo: [A_ID],
+ dispatch: true,
+ });
+ await waitForQuiescent(TEST_UID, cid, 4000);
+
+ const finalPlan = await plan.readPlan(TEST_UID, cid);
+ expect(finalPlan?.steps[0].status).toBe('done');
+ expect(finalPlan?.steps[0].output_summary).toBe('manual dispatch result');
+ }, 10_000);
+});
+
+// ─────────────────────────────────────────────────────────────────────────
+// Test 6 — plan inherits user-turn attachments and forwards to workers
+//
+// Regression guard for "commander sees the image, worker doesn't" — workers
+// read images via ChatOptions.images, which is populated from
+// item.attachments → buildAttachmentManifest. plan-step dispatches live
+// across turn boundaries, so the source must be persisted on the plan.
+//
+// Two fixtures pinned:
+// A) initial_attachments set on plan → both forwarded dispatches carry
+// the same attachments list (so worker's turnImages populates).
+// B) initial_attachments unset → no attachments leak onto dispatches
+// (verifies the optional path doesn't accidentally add an empty key).
+// ─────────────────────────────────────────────────────────────────────────
+
+describe('plan_executor › attachment inheritance', () => {
+ it('plan.initial_attachments propagates onto every step dispatch', async () => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [{ type: 'final', text: 'A done' }]);
+ _setScript(state.buildGmemberSessionId(cid, B_ID), [{ type: 'final', text: 'B done' }]);
+
+ await setupPlanAndKick(TEST_UID, cid, {
+ initial_message: '解这道题',
+ initial_attachments: ['problem.png', 'extra.jpg'],
+ steps: [
+ { title: '识图', assignee: A_NAME, input: '看附件中的题', wait_for: [] },
+ { title: '求解', assignee: B_NAME, input: '解题: {{step_1.output_summary}}', wait_for: [1] },
+ ],
+ });
+
+ await waitForQuiescent(TEST_UID, cid, 5000);
+
+ const lines = await readJsonl(TEST_UID, cid);
+ const toA = lines.find((l) => l.from === 'commander' && l.to.includes(A_ID));
+ const toB = lines.find((l) => l.from === 'commander' && l.to.includes(B_ID));
+
+ expect(toA?.attachments).toEqual(['problem.png', 'extra.jpg']);
+ expect(toB?.attachments).toEqual(['problem.png', 'extra.jpg']);
+
+ // Plan still records the source so retries / replan inherit.
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ const persisted = await plan.readPlan(TEST_UID, cid);
+ expect(persisted?.initial_attachments).toEqual(['problem.png', 'extra.jpg']);
+ }, 15_000);
+
+ it('no initial_attachments → dispatch messages omit the attachments key', async () => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [{ type: 'final', text: 'A done' }]);
+
+ await setupPlanAndKick(TEST_UID, cid, {
+ initial_message: 'no image case',
+ steps: [{ title: '只是文字', assignee: A_NAME, input: '回答', wait_for: [] }],
+ });
+
+ await waitForQuiescent(TEST_UID, cid, 5000);
+
+ const lines = await readJsonl(TEST_UID, cid);
+ const toA = lines.find((l) => l.from === 'commander' && l.to.includes(A_ID));
+ // Persisted GroupMessage shape: `attachments` is only present when non-empty
+ // (see _enqueueBody at bus.ts:612). Asserting omission catches a regression
+ // where we'd accidentally pass `attachments: []` and pollute the file.
+ expect(toA).toBeTruthy();
+ expect('attachments' in toA).toBe(false);
+
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ const persisted = await plan.readPlan(TEST_UID, cid);
+ expect(persisted?.initial_attachments).toBeUndefined();
+ }, 15_000);
});
diff --git a/test/main/features/marketplace_reconcile.test.ts b/test/main/features/marketplace_reconcile.test.ts
new file mode 100644
index 00000000..5f7ee9e0
--- /dev/null
+++ b/test/main/features/marketplace_reconcile.test.ts
@@ -0,0 +1,69 @@
+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';
+
+const postJsonMock = vi.hoisted(() => vi.fn());
+
+vi.mock('../../../src/main/features/marketplace', () => ({
+ postJson: postJsonMock,
+ extractBundleSafely: vi.fn(),
+}));
+
+let tmpDir: string;
+let prevWs: string | undefined;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-marketplace-reconcile-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ vi.resetModules();
+ postJsonMock.mockReset();
+});
+
+afterEach(() => {
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+describe('marketplace reconcile', () => {
+ it('marks an installed item stale when updated_at changes even if version and published_at do not', async () => {
+ postJsonMock.mockImplementation(async (p: string) => {
+ if (p === '/marketplace/agents/list') {
+ return {
+ list: [{
+ id: 'agent1',
+ version: '1.0.0',
+ published_at: 100,
+ updated_at: 200,
+ }],
+ total: 1,
+ };
+ }
+ if (p === '/marketplace/skills/list') return { list: [], total: 0 };
+ throw new Error(`unexpected path ${p}`);
+ });
+
+ const installs = await import('../../../src/main/features/marketplace_installs');
+ await installs.addAgentInstall('u1', {
+ id: 'agent1',
+ version: '1.0.0',
+ published_at: 100,
+ agent_json_url: 'https://example.test/agent.json',
+ create_uid: '0',
+ });
+
+ const reconcile = await import('../../../src/main/features/marketplace_reconcile');
+ const result = await reconcile.checkServerUpdatesForInstalls('u1');
+
+ expect(result).toEqual({ updated_agents: 1, updated_skills: 0 });
+ const manifest = await installs.readInstalls('u1');
+ expect(manifest.agents[0]).toMatchObject({
+ id: 'agent1',
+ version: '1.0.0',
+ published_at: 100,
+ updated_at: 200,
+ agent_json_url: 'https://example.test/agent.json',
+ });
+ });
+});
diff --git a/test/main/features/projects.test.ts b/test/main/features/projects.test.ts
index 9f45101c..945ea9d4 100644
--- a/test/main/features/projects.test.ts
+++ b/test/main/features/projects.test.ts
@@ -308,6 +308,31 @@ describe('projects › bindings CRUD', () => {
expect(r.ok).toBe(false);
if (!r.ok) expect(r.error).toBe('not_found');
});
+
+ it('prunes bindings whose agent or skill no longer exists', async () => {
+ const projects = await loadProjects();
+ const p = await projects.createProject(TEST_UID, 'PruneBindings');
+ if (!p.ok) throw new Error('precondition');
+ const pid = p.project.project_id;
+
+ await projects.addAgentBinding(TEST_UID, pid, 'agent-live');
+ await projects.addAgentBinding(TEST_UID, pid, 'agent-gone');
+ await projects.addSkillBinding(TEST_UID, pid, 'skill-live');
+ await projects.addSkillBinding(TEST_UID, pid, 'skill-gone');
+
+ const res = await projects.pruneBindings(TEST_UID, pid, {
+ agents: new Set(['agent-live']),
+ skills: new Set(['skill-live']),
+ });
+
+ expect(res.ok).toBe(true);
+ if (res.ok) {
+ expect(res.bindings).toEqual({ agents: ['agent-live'], skills: ['skill-live'] });
+ expect(res.pruned).toEqual({ agents: ['agent-gone'], skills: ['skill-gone'] });
+ }
+ expect(await projects.getBindings(TEST_UID, pid))
+ .toEqual({ agents: ['agent-live'], skills: ['skill-live'] });
+ });
});
describe('projects › resolveProjectScope', () => {
diff --git a/test/main/features/skills.test.ts b/test/main/features/skills.test.ts
index 410bafed..4161a19a 100644
--- a/test/main/features/skills.test.ts
+++ b/test/main/features/skills.test.ts
@@ -326,14 +326,24 @@ describe('skills › extractSkillContainers', () => {
// span — would falsely trigger a real skill write. This is the "agent
// section line 229 / chat_skill_setup.md showing protocol" risk surface.
- it('B5: `<skill>` inside fenced ```xml block must NOT match', async () => {
+ it('B5: `<skill>` inside fenced non-XML code block must NOT match', async () => {
const s = await loadSkills();
- const text = 'Here is the format:\n```xml\n<skill>\n<skill_id>example</skill_id>\n<<<skill-file path=SKILL.md\nname: "example"\n>>>\n</skill>\n```\nThat is the shape.';
+ const text = 'Here is the format:\n```\n<skill>\n<skill_id>example</skill_id>\n<<<skill-file path=SKILL.md\nname: "example"\n>>>\n</skill>\n```\nThat is the shape.';
const r = s.extractSkillContainers(text);
expect(r.containers).toEqual([]);
expect(r.cleanText).toBe(text); // Untouched — it's prose teaching, not a real op.
});
+ it('B5b: `<skill>` inside fenced ```xml block is treated as structural', async () => {
+ const s = await loadSkills();
+ const text = '```xml\n<skill>\n<skill_id>example</skill_id>\n<<<skill-file path=SKILL.md\nbody\n>>>\n</skill>\n```';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers).toHaveLength(1);
+ expect(r.containers[0].skillId).toBe('example');
+ expect(r.containers[0].files.map((f: any) => f.path)).toEqual(['SKILL.md']);
+ expect(r.cleanText).toBe('```xml\n\n```');
+ });
+
it('B6: `<skill>` inside inline backtick span must NOT match', async () => {
const s = await loadSkills();
const text = 'Wrap your spec inside `<skill>...</skill>` and the system will pick it up.';
@@ -342,16 +352,24 @@ describe('skills › extractSkillContainers', () => {
expect(r.cleanText).toBe(text);
});
+ it('B6b: inline quoted `<skill>` text must NOT match', async () => {
+ const s = await loadSkills();
+ const text = '请输出 "<skill><skill_id>example</skill_id></skill>" 这些字符';
+ const r = s.extractSkillContainers(text);
+ expect(r.containers).toEqual([]);
+ expect(r.cleanText).toBe(text);
+ });
+
it('B7: real container AFTER a code-fence example — only the real one is extracted', async () => {
const s = await loadSkills();
// Critical: this is the failure mode the guard prevents — a naive
// regex would match the FIRST `<skill>` (the fenced example) and
// try to write fictional files, ignoring the real container below.
- const text = 'Format:\n```xml\n<skill>\n<skill_id>example</skill_id>\n</skill>\n```\nAnd here is the real one:\n<skill>\n<skill_id>real</skill_id>\n<<<skill-file path=SKILL.md\nbody\n>>>\n</skill>';
+ const text = 'Format:\n```\n<skill>\n<skill_id>example</skill_id>\n</skill>\n```\nAnd here is the real one:\n<skill>\n<skill_id>real</skill_id>\n<<<skill-file path=SKILL.md\nbody\n>>>\n</skill>';
const r = s.extractSkillContainers(text);
expect(r.containers).toHaveLength(1);
expect(r.containers[0].skillId).toBe('real');
- expect(r.cleanText).toContain('```xml');
+ expect(r.cleanText).toContain('```');
expect(r.cleanText).toContain('<skill>\n<skill_id>example</skill_id>'); // fenced example survives
});
});
@@ -359,7 +377,7 @@ describe('skills › extractSkillContainers', () => {
describe('skills › applySkillContainerFromCommander › create', () => {
it('creates skill from frontmatter `name`, writes all blocks', async () => {
const s = await loadSkills();
- const skillMdContent = '---\nname: "social-fetch"\ndescription_zh: "抓取并分析"\ndescription_en: "Fetch and analyze"\n---\n\n# When to use\n…\n';
+ const skillMdContent = '---\nname: "social-fetch"\ndescription_zh: "抓取并分析"\ndescription_en: "Fetch and analyze"\ncategory: "data"\n---\n\n# When to use\n…\n';
const r = await s.applySkillContainerFromCommander({
files: [
{ path: 'SKILL.md', content: skillMdContent },
@@ -393,6 +411,23 @@ describe('skills › applySkillContainerFromCommander › create', () => {
expect(r.error).toMatch(/name|缺少/);
});
+ it('backfills category when model-authored create omits or mangles it', async () => {
+ const s = await loadSkills();
+ const missing = await s.applySkillContainerFromCommander({
+ files: [{ path: 'SKILL.md', content: '---\nname: "uncategorized"\ndescription_en: "x"\n---\n\nbody\n' }],
+ });
+ expect(missing.ok).toBe(true);
+ expect(fs.readFileSync(path.join(customSkillsDir(), 'uncategorized', 'SKILL.md'), 'utf8'))
+ .toContain('category: "general"');
+
+ const invalid = await s.applySkillContainerFromCommander({
+ files: [{ path: 'SKILL.md', content: '---\nname: "badcat"\ndescription_en: "x"\ncategory: "bad category"\n---\n\nbody\n' }],
+ });
+ expect(invalid.ok).toBe(true);
+ expect(fs.readFileSync(path.join(customSkillsDir(), 'badcat', 'SKILL.md'), 'utf8'))
+ .toContain('category: "general"');
+ });
+
it('rejects create when name has Chinese characters (charset gate)', async () => {
const s = await loadSkills();
// Hard requirement from product: skill name must be ASCII only.
@@ -447,22 +482,37 @@ describe('skills › applySkillContainerFromCommander › edit', () => {
.toContain('body');
});
- it('rejects edit when skill does not exist', async () => {
+ it('creates when skill_id target is missing but a full SKILL.md payload is present', async () => {
+ const s = await loadSkills();
+ const r = await s.applySkillContainerFromCommander({
+ skillId: 'nonexistent',
+ files: [{
+ path: 'SKILL.md',
+ content: '---\nname: "nonexistent"\ndescription_zh: "测试技能"\ndescription_en: "Test skill"\ncategory: "general"\n---\n\n# When to use\nUse for test prompts.\n',
+ }],
+ });
+ expect(r.ok).toBe(true);
+ expect(r.kind).toBe('created');
+ expect(r.skillId).toBe('nonexistent');
+ expect(fs.existsSync(path.join(customSkillsDir(), 'nonexistent', 'SKILL.md'))).toBe(true);
+ });
+
+ it('rejects missing skill_id target when there is no SKILL.md create payload', async () => {
const s = await loadSkills();
const r = await s.applySkillContainerFromCommander({
skillId: 'nonexistent',
- files: [{ path: 'SKILL.md', content: '---\nname: "nonexistent"\n---\n\nbody\n' }],
+ files: [{ path: 'scripts/run.py', content: 'pass\n' }],
});
expect(r.ok).toBe(false);
expect(r.error).toMatch(/not found|不存在/i);
});
it('auto-renames the dir when SKILL.md `name` changes', async () => {
- writeCustomSkill('oldname', 'name: "oldname"\ndescription_en: "x"', 'body');
+ writeCustomSkill('oldname', 'name: "oldname"\ndescription_en: "x"\ncategory: "general"', 'body');
const s = await loadSkills();
const r = await s.applySkillContainerFromCommander({
skillId: 'oldname',
- files: [{ path: 'SKILL.md', content: '---\nname: "newname"\ndescription_en: "x"\n---\n\nbody\n' }],
+ files: [{ path: 'SKILL.md', content: '---\nname: "newname"\ndescription_en: "x"\ncategory: "general"\n---\n\nbody\n' }],
});
expect(r.ok).toBe(true);
expect(r.skillId).toBe('newname');
@@ -521,6 +571,30 @@ describe('skills › listSkills', () => {
expect(dup[0].source).toBe('custom');
expect(dup[0].description_en).toBe('cx');
});
+
+ it('cache-only invalidator picks up marketplace file rewrites', async () => {
+ const parent = builtinSkillsDir();
+ const dir = path.join(parent, 'platform-skill');
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'SKILL.md'),
+ '---\nname: "Old platform skill"\ndescription: "old"\n---\n');
+ const fixedStamp = new Date('2026-01-01T00:00:00.000Z');
+ fs.utimesSync(parent, fixedStamp, fixedStamp);
+
+ const s = await loadSkills();
+ expect((await s.listSkills()).find((x) => x.id === 'platform-skill')?.name)
+ .toBe('Old platform skill');
+
+ fs.writeFileSync(path.join(dir, 'SKILL.md'),
+ '---\nname: "New platform skill"\ndescription: "new"\n---\n');
+ fs.utimesSync(parent, fixedStamp, fixedStamp);
+
+ expect((await s.listSkills()).find((x) => x.id === 'platform-skill')?.name)
+ .toBe('Old platform skill');
+ s.clearSkillListCache();
+ expect((await s.listSkills()).find((x) => x.id === 'platform-skill')?.name)
+ .toBe('New platform skill');
+ });
});
describe('skills › getCustomSkill', () => {
@@ -687,7 +761,7 @@ describe('skills › listSkillTree', () => {
describe('skills › buildSkillEditSystemPrompt', () => {
it('renders template with skill metadata + file list, no leftover placeholders', async () => {
- writeCustomSkill('alpha', 'name: "Alpha"\ndescription: "a demo"', 'body text');
+ writeCustomSkill('alpha', 'name: "Alpha"\ndescription: "a demo"\ncategory: "writing"', 'body text');
const s = await loadSkills();
const skill = (await s.getCustomSkill('alpha'))!;
const sys = await s.buildSkillEditSystemPrompt(skill);
@@ -698,7 +772,7 @@ describe('skills › buildSkillEditSystemPrompt', () => {
// Template no longer carries the user-input footer.
expect(sys).not.toMatch(/##\s*用户的初始请求/);
// All placeholders resolved.
- expect(sys).not.toMatch(/\$skill_name|\$skill_description|\$skill_dir|\$skill_files/);
+ expect(sys).not.toMatch(/\$skill_name|\$skill_description|\$skill_category|\$category_field_definition|\$skill_dir|\$skill_files/);
});
});
diff --git a/test/main/model/core-agent/connector-meta-tools.test.ts b/test/main/model/core-agent/connector-meta-tools.test.ts
index 410e4360..d42cc4fa 100644
--- a/test/main/model/core-agent/connector-meta-tools.test.ts
+++ b/test/main/model/core-agent/connector-meta-tools.test.ts
@@ -50,6 +50,7 @@ vi.mock('../../../../src/main/features/connectors/catalog', () => ({
vi.mock('../../../../src/main/i18n', () => ({
getCurrentLang: () => 'en',
+ descriptionLang: (lang: 'zh' | 'en' | 'ja') => (lang === 'zh' ? 'zh' : 'en'),
}));
vi.mock('../../../../src/main/logger', () => ({
diff --git a/test/main/model/skill-registry.test.ts b/test/main/model/skill-registry.test.ts
index 962f294f..137d9e74 100644
--- a/test/main/model/skill-registry.test.ts
+++ b/test/main/model/skill-registry.test.ts
@@ -71,6 +71,16 @@ describe('skill-registry › getSystemPromptBlock(allowlist)', () => {
expect(text).not.toContain('summarize');
});
+ it('matches allowlist entries by display name when marketplace id differs', async () => {
+ writeSkill(builtinDir(), '6bb95f967501', 'github', 'GitHub skill');
+ writeSkill(builtinDir(), 'daa4378ab55a', 'find-skill', 'Find skill');
+ const { getSystemPromptBlock } = await loadRegistry();
+ const text = await getSystemPromptBlock({ allowlist: ['github', 'find-skill'] });
+ expect(text).toContain('**github** (Source: builtin; internal read id: 6bb95f967501)');
+ expect(text).toContain('**find-skill** (Source: builtin; internal read id: daa4378ab55a)');
+ expect(text).not.toContain('(id: 6bb95f967501)');
+ });
+
it('returns empty string when allowlist is [] (agent opting out of all skills)', async () => {
writeSkill(builtinDir(), 'translate', 'Translate', 'T');
const { getSystemPromptBlock } = await loadRegistry();
@@ -124,6 +134,9 @@ describe('skill-registry › getSystemPromptBlock(allowlist)', () => {
expect(text).toContain(`- custom: ${path.resolve(customDir())}`);
expect(text).toContain(`- builtin: ${path.resolve(builtinDir())}`);
expect(text).toContain('Use these ROOT values verbatim');
+ expect(text).toContain('These entries are skills, not tool names');
+ expect(text).toContain('never call the display name or id as a tool');
+ expect(text).toContain('Never mention skill ids');
});
it('block omits ROOT header when no skills are present (renderSkillLines short-circuits empty)', async () => {
@@ -132,3 +145,23 @@ describe('skill-registry › getSystemPromptBlock(allowlist)', () => {
expect(text).toBe('');
});
});
+
+describe('skill-registry › replaceKnownSkillIdsForDisplay', () => {
+ it('rewrites known marketplace ids to display names with token boundaries', async () => {
+ const { replaceKnownSkillIdsForDisplay } = await loadRegistry();
+ const text = replaceKnownSkillIdsForDisplay(
+ 'skill: follow the `16e1bfcb3426` skill; leave x16e1bfcb3426y alone',
+ [{ id: '16e1bfcb3426', name: 'agent-creator' }],
+ );
+ expect(text).toBe('skill: follow the `agent-creator` skill; leave x16e1bfcb3426y alone');
+ });
+
+ it('normalizes skill follow phrasing to a compact display reference', async () => {
+ const { normalizeKnownSkillRefsForDisplay } = await loadRegistry();
+ const text = normalizeKnownSkillRefsForDisplay(
+ '`skill: follow the 16e1bfcb3426 skill` — create agents',
+ [{ id: '16e1bfcb3426', name: 'agent-creator' }],
+ );
+ expect(text).toBe('`agent-creator` skill — create agents');
+ });
+});
diff --git a/test/main/prompts/contract.test.ts b/test/main/prompts/contract.test.ts
index 4fe323ff..f6234cb7 100644
--- a/test/main/prompts/contract.test.ts
+++ b/test/main/prompts/contract.test.ts
@@ -136,4 +136,25 @@ describe('prompts ↔ code contract', () => {
expect(commanderPrompt).not.toMatch(/Even when the built-in PDF tools error, do not fall back/i);
expect(agentPrompt).not.toMatch(/Even when the built-in PDF tools error, do not fall back/i);
});
+
+ it('agent authoring and execution prompts distinguish skills from tools', () => {
+ const agentPrompt = fs.readFileSync(path.join(PROMPTS_DIR, 'chat_agent_in_group.md'), 'utf-8');
+
+ expect(agentPrompt).toContain('Skills are not tools');
+ expect(agentPrompt).toContain('do NOT attempt a tool call with the skill');
+ });
+
+ it('authoring prompt shells leave category field rules to creator skills', () => {
+ const authoringPrompts = [
+ 'chat_commander.md',
+ 'chat_agent_setup.md',
+ 'chat_agent_setup_cli.md',
+ 'chat_skill_setup.md',
+ ].map((name) => fs.readFileSync(path.join(PROMPTS_DIR, name), 'utf-8'));
+ for (const prompt of authoringPrompts) {
+ expect(prompt).not.toContain('Required category');
+ expect(prompt).not.toContain('$category_field_definition');
+ expect(prompt).not.toMatch(/education.*ecommerce.*rnd.*writing.*data.*general/s);
+ }
+ });
});
diff --git a/test/main/quality/index.test.ts b/test/main/quality/index.test.ts
index 9dc47552..e1e531bc 100644
--- a/test/main/quality/index.test.ts
+++ b/test/main/quality/index.test.ts
@@ -21,6 +21,7 @@ describe('quality › validateSkillFile', () => {
'name: pdf-summarize',
'description_en: Summarize PDFs',
'description_zh: PDF 摘要',
+ 'category: data',
'---',
'Body text explaining how to use this skill.',
].join('\n');
@@ -47,7 +48,7 @@ describe('quality › validateSkillFile', () => {
const content = [
'---',
'name: x',
- 'description_en: x', 'description_zh: x',
+ 'description_en: x', 'description_zh: x', 'category: general',
'---',
'```bash',
'cat ~/.ssh/config',
@@ -75,7 +76,7 @@ describe('quality › validateSkillFile', () => {
});
it('treats SKILL.md case-insensitively', () => {
- const content = '---\nname: x\ndescription_en: x\ndescription_zh: x\n---\n';
+ const content = '---\nname: x\ndescription_en: x\ndescription_zh: x\ncategory: general\n---\n';
const a = validateSkillFile({ relpath: 'skill.md', content });
const b = validateSkillFile({ relpath: 'SKILL.MD', content });
expect(a.violations).toEqual([]);
@@ -108,14 +109,14 @@ describe('quality › validateSkillDir', () => {
it('passes a directory with only a valid SKILL.md', () => {
fs.writeFileSync(path.join(dir, 'SKILL.md'),
- '---\nname: x\ndescription_zh: x\ndescription_en: x\n---\n');
+ '---\nname: x\ndescription_zh: x\ndescription_en: x\ncategory: general\n---\n');
const r = validateSkillDir(dir);
expect(r.ok).toBe(true);
});
it('aggregates findings from SKILL.md + scripts/', () => {
fs.writeFileSync(path.join(dir, 'SKILL.md'),
- '---\nname: x\ndescription_zh: x\ndescription_en: x\n---\n');
+ '---\nname: x\ndescription_zh: x\ndescription_en: x\ncategory: general\n---\n');
fs.mkdirSync(path.join(dir, 'scripts'), { recursive: true });
fs.writeFileSync(path.join(dir, 'scripts', 'x.sh'),
'cat ~/.bash_history\n');
@@ -127,7 +128,7 @@ describe('quality › validateSkillDir', () => {
it('skips _install.json and other meta files', () => {
fs.writeFileSync(path.join(dir, 'SKILL.md'),
- '---\nname: x\ndescription_zh: x\ndescription_en: x\n---\n');
+ '---\nname: x\ndescription_zh: x\ndescription_en: x\ncategory: general\n---\n');
fs.writeFileSync(path.join(dir, '_install.json'),
'{"version":"1","published_at":0,"create_uid":""}');
const r = validateSkillDir(dir);
@@ -141,6 +142,7 @@ describe('quality › validateAgentSpec', () => {
agentJson: {
agent_id: 'a1', name: 'A1',
description_zh: 'zh', description_en: 'en',
+ category: 'general',
},
});
expect(r.ok).toBe(true);
@@ -157,6 +159,7 @@ describe('quality › validateAgentSpec', () => {
agentJson: {
agent_id: 'a', name: 'X',
description_en: 'en', description_zh: 'zh',
+ category: 'general',
workflow: 'reads ~/.ssh/config from the user',
},
});
@@ -187,6 +190,7 @@ describe('quality › validateAgentDir', () => {
fs.writeFileSync(path.join(dir, 'agent.json'), JSON.stringify({
agent_id: 'a', name: 'X',
description_zh: 'zh', description_en: 'en',
+ category: 'general',
}));
const r = validateAgentDir(dir);
expect(r.ok).toBe(true);
@@ -195,7 +199,7 @@ describe('quality › validateAgentDir', () => {
describe('quality › report shape', () => {
it('always includes validated_at + validator_version', () => {
- const r = validateSkillFile({ relpath: 'SKILL.md', content: '---\nname: x\ndescription_en: x\ndescription_zh: x\n---\n' });
+ const r = validateSkillFile({ relpath: 'SKILL.md', content: '---\nname: x\ndescription_en: x\ndescription_zh: x\ncategory: general\n---\n' });
expect(r.validated_at).toMatch(/^\d{4}-\d{2}-\d{2}T/);
expect(r.validator_version).toMatch(/^\d+\.\d+/);
});
diff --git a/test/main/quality/schema.test.ts b/test/main/quality/schema.test.ts
index 4d4855f3..d1b4104f 100644
--- a/test/main/quality/schema.test.ts
+++ b/test/main/quality/schema.test.ts
@@ -11,6 +11,7 @@ describe('quality › schema › validateSkillFrontmatter', () => {
name: 'pdf-summarize',
description_zh: 'PDF 摘要工具',
description_en: 'Summarize PDF documents',
+ category: 'data',
});
expect(v).toEqual([]);
});
@@ -57,6 +58,7 @@ describe('quality › schema › validateSkillFrontmatter', () => {
name: 'foo',
description_en: long,
description_zh: 'short',
+ category: 'general',
});
const long_v = v.find((x) => x.rule === 'frontmatter_description_too_long');
expect(long_v?.level).toBe('MEDIUM');
@@ -66,10 +68,24 @@ describe('quality › schema › validateSkillFrontmatter', () => {
it('a valid name with single-space groups passes', () => {
const v = validateSkillFrontmatter({
name: 'Foo Bar Baz',
- description_zh: 'x', description_en: 'x',
+ description_zh: 'x', description_en: 'x', category: 'general',
});
expect(v.map((x) => x.rule)).not.toContain('frontmatter_name_invalid');
});
+
+ it('flags missing or invalid category', () => {
+ const missing = validateSkillFrontmatter({
+ name: 'foo', description_zh: 'x', description_en: 'x',
+ });
+ const missingCat = missing.find((x) => x.rule === 'frontmatter_category_missing');
+ expect(missingCat?.level).toBe('MEDIUM');
+
+ const invalid = validateSkillFrontmatter({
+ name: 'foo', description_zh: 'x', description_en: 'x', category: 'bad category',
+ });
+ const invalidCat = invalid.find((x) => x.rule === 'frontmatter_category_invalid');
+ expect(invalidCat?.level).toBe('MEDIUM');
+ });
});
describe('quality › schema › validateAgentJsonShape', () => {
@@ -78,6 +94,7 @@ describe('quality › schema › validateAgentJsonShape', () => {
agent_id: 'abc123',
name: 'My Agent',
description_zh: 'zh', description_en: 'en',
+ category: 'general',
});
expect(v).toEqual([]);
});
@@ -108,11 +125,25 @@ describe('quality › schema › validateAgentJsonShape', () => {
it('flags overlong description as MEDIUM', () => {
const v = validateAgentJsonShape({
agent_id: 'abc', name: 'X',
- description_en: 'y'.repeat(900), description_zh: 'short',
+ description_en: 'y'.repeat(900), description_zh: 'short', category: 'general',
});
const long = v.find((x) => x.rule === 'agent_description_too_long');
expect(long?.level).toBe('MEDIUM');
});
+
+ it('flags missing or invalid category', () => {
+ const missing = validateAgentJsonShape({
+ agent_id: 'abc', name: 'X', description_zh: 'zh', description_en: 'en',
+ });
+ const missingCat = missing.find((x) => x.rule === 'agent_category_missing');
+ expect(missingCat?.level).toBe('MEDIUM');
+
+ const invalid = validateAgentJsonShape({
+ agent_id: 'abc', name: 'X', description_zh: 'zh', description_en: 'en', category: 'bad category',
+ });
+ const invalidCat = invalid.find((x) => x.rule === 'agent_category_invalid');
+ expect(invalidCat?.level).toBe('MEDIUM');
+ });
});
describe('quality › schema › parseFailureViolation', () => {
diff --git a/test/main/util/image-transform.test.ts b/test/main/util/image-transform.test.ts
index 057f84aa..f2b5f7e1 100644
--- a/test/main/util/image-transform.test.ts
+++ b/test/main/util/image-transform.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeAll } from 'vitest';
-import { toCompressedGrayJpeg } from '../../../src/main/util/image-transform';
+import { prepareFeedbackUploadImage, toCompressedGrayJpeg } from '../../../src/main/util/image-transform';
let sourcePng: Buffer;
@@ -53,3 +53,53 @@ describe('image-transform › toCompressedGrayJpeg', () => {
await expect(toCompressedGrayJpeg(Buffer.alloc(0))).rejects.toThrow(/empty|invalid/i);
});
});
+
+describe('image-transform › prepareFeedbackUploadImage', () => {
+ it('compresses large feedback images as color JPEG', async () => {
+ const r = await prepareFeedbackUploadImage(sourcePng, {
+ fileName: 'screen.png',
+ mimeType: 'image/png',
+ maxBytes: 200 * 1024,
+ maxDim: 600,
+ compressTriggerBytes: 0,
+ });
+
+ expect(r.compressed).toBe(true);
+ expect(r.mimeType).toBe('image/jpeg');
+ expect(r.fileName).toBe('screen.jpg');
+ expect(r.buf.length).toBeLessThanOrEqual(200 * 1024);
+ expect(Math.max(r.width || 0, r.height || 0)).toBeLessThanOrEqual(600);
+
+ const { Jimp } = await import('jimp' as any);
+ const out: any = await Jimp.read(r.buf);
+ const px = out.getPixelColor(20, 20);
+ const r8 = (px >>> 24) & 0xff;
+ const g8 = (px >>> 16) & 0xff;
+ const b8 = (px >>> 8) & 0xff;
+ expect(Math.max(Math.abs(r8 - g8), Math.abs(g8 - b8), Math.abs(r8 - b8))).toBeGreaterThan(16);
+ });
+
+ it('keeps small feedback images untouched when compression is not useful', async () => {
+ const { Jimp } = await import('jimp' as any);
+ const small: any = new Jimp({ width: 120, height: 90, color: 0x6699CCFF });
+ const smallPng: Buffer = await small.getBuffer('image/png');
+ const r = await prepareFeedbackUploadImage(smallPng, {
+ fileName: 'small.png',
+ mimeType: 'image/png',
+ maxBytes: 5 * 1024 * 1024,
+ });
+
+ expect(r.compressed).toBe(false);
+ expect(r.mimeType).toBe('image/png');
+ expect(r.fileName).toBe('small.png');
+ expect(r.buf.equals(smallPng)).toBe(true);
+ });
+
+ it('does not try to compress oversized GIFs', async () => {
+ await expect(prepareFeedbackUploadImage(Buffer.alloc(11), {
+ fileName: 'clip.gif',
+ mimeType: 'image/gif',
+ maxBytes: 10,
+ })).rejects.toMatchObject({ code: 'image_too_large' });
+ });
+});
diff --git a/test/renderer/marketplace-dev.test.ts b/test/renderer/marketplace-dev.test.ts
new file mode 100644
index 00000000..647be825
--- /dev/null
+++ b/test/renderer/marketplace-dev.test.ts
@@ -0,0 +1,96 @@
+import { describe, it, expect } from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as vm from 'node:vm';
+
+type FakeButton = {
+ dataset: Record<string, string>;
+ style: Record<string, string>;
+ disabled: boolean;
+ textContent: string;
+ innerHTML: string;
+ classList: {
+ add: (cls: string) => void;
+ remove: (cls: string) => void;
+ contains: (cls: string) => boolean;
+ };
+ addEventListener: () => void;
+};
+
+function makeButton(): FakeButton {
+ const classes = new Set<string>();
+ return {
+ dataset: {},
+ style: { display: 'none' },
+ disabled: false,
+ textContent: '',
+ innerHTML: '',
+ classList: {
+ add: (cls: string) => { classes.add(cls); },
+ remove: (cls: string) => { classes.delete(cls); },
+ contains: (cls: string) => classes.has(cls),
+ },
+ addEventListener: () => {},
+ };
+}
+
+function loadMarketplaceDev(button: FakeButton, opts: { isDev?: boolean } = {}): any {
+ const code = fs.readFileSync(
+ path.join(__dirname, '../../src/renderer/modules/marketplace_dev.js'),
+ 'utf8',
+ );
+ const context: any = {
+ document: {
+ addEventListener: () => {},
+ querySelector: (selector: string) => (
+ selector === '[data-mp-detail-delete]' ? button : null
+ ),
+ },
+ escapeHtml: (s: unknown) => String(s ?? ''),
+ isDevMode: () => opts.isDev !== false,
+ t: (key: string) => ({
+ 'marketplace.delete': 'Delete',
+ 'marketplace.deleting': 'Deleting...',
+ 'marketplace.tab_agent': 'Agents',
+ 'marketplace.tab_skill': 'Skills',
+ 'marketplace.delete_confirm_title': 'Delete item',
+ 'marketplace.delete_confirm_msg': 'Delete {kind} {name}?',
+ 'marketplace.delete_ok': 'Deleted',
+ 'marketplace.delete_failed': 'Delete failed: {reason}',
+ } as Record<string, string>)[key] || key,
+ uiConfirmDanger: async () => true,
+ uiAlert: async () => {},
+ window: { orkas: { invoke: async () => ({ ok: true }) } },
+ };
+ vm.createContext(context);
+ vm.runInContext(code, context, { filename: 'marketplace_dev.js' });
+ return context;
+}
+
+describe('marketplace dev delete button', () => {
+ it('re-enables the shared detail delete button when rendering a new item', () => {
+ const button = makeButton();
+ button.disabled = true;
+ button.classList.add('is-disabled');
+ button.innerHTML = '<span class="marketplace-btn-spinner"></span>Deleting...';
+ const ctx = loadMarketplaceDev(button);
+
+ ctx.onMarketplaceDetailRendered({ kind: 'skill', item: { id: 'skill1' } });
+
+ expect(button.disabled).toBe(false);
+ expect(button.classList.contains('is-disabled')).toBe(false);
+ expect(button.textContent).toBe('Delete');
+ expect(button.dataset).toMatchObject({ id: 'skill1', kind: 'skill' });
+ expect(button.style.display).toBe('');
+ });
+
+ it('keeps the button hidden when the renderer is not in dev mode', () => {
+ const button = makeButton();
+ const ctx = loadMarketplaceDev(button, { isDev: false });
+
+ ctx.onMarketplaceDetailRendered({ kind: 'skill', item: { id: 'skill1' } });
+
+ expect(button.style.display).toBe('none');
+ expect(button.disabled).toBe(false);
+ });
+});
diff --git a/test/renderer/strip-structural-blocks.test.ts b/test/renderer/strip-structural-blocks.test.ts
index e3ff56c1..c284dd45 100644
--- a/test/renderer/strip-structural-blocks.test.ts
+++ b/test/renderer/strip-structural-blocks.test.ts
@@ -19,7 +19,7 @@
// them preserved.
//
// Set B — literal `<agent>` mentions that MUST be preserved:
-// B1. Inside a fenced ```xml code block (the original 34e27fcb case).
+// B1. Inside a non-XML fenced code block.
// B2. Inside an inline backtick span.
// B3. Inside an UNCLOSED inline backtick (mid-stream code-explanation).
//
@@ -44,8 +44,12 @@ const {
_replaceOuterAgentBlocks,
_stripSkillCreateContainer,
_stripSurvivingStructuralBlocks,
+ _stripUserStructuralBlocksForDisplay,
+ _replaceKnownSkillIdsForDisplay,
+ _simplifyKnownSkillFollowPhrasesForDisplay,
+ _normalizeKnownSkillRefsForDisplay,
} = strip as {
- _splitMarkdownProseCode: (text: string) => Array<{ kind: 'prose' | 'code'; text: string }>;
+ _splitMarkdownProseCode: (text: string) => Array<{ kind: 'prose' | 'code'; text: string; xmlFence?: boolean }>;
_findOuterTagRanges: (text: string, tagName: string) => Array<[number, number]>;
_stripOuterTagBlocks: (text: string, tagName: string) => string;
_replaceOuterTagBlocks: (buf: string, tagName: string, placeholder: string) => string;
@@ -54,6 +58,10 @@ const {
_replaceOuterAgentBlocks: (buf: string, placeholder: string) => string;
_stripSkillCreateContainer: (buf: string, fallbackPlaceholder: string) => string;
_stripSurvivingStructuralBlocks: (text: string) => string;
+ _stripUserStructuralBlocksForDisplay: (text: string) => string;
+ _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;
};
const PH = '⟨PLACEHOLDER⟩';
@@ -128,8 +136,8 @@ describe('set A — real <agent> containers must be stripped / replaced', () =>
// --- Set B: literal mentions must survive ---------------------------------
describe('set B — literal <agent> in code must be preserved', () => {
- it('B1. inside a fenced ```xml block', () => {
- const buf = 'Use this format:\n```xml\n<agent><name>X</name></agent>\n```\nafter';
+ it('B1. inside a fenced non-XML code block', () => {
+ const buf = 'Use this format:\n```\n<agent><name>X</name></agent>\n```\nafter';
expect(_stripSurvivingAgentBlocks(buf)).toBe(buf.trim());
expect(_replaceOuterAgentBlocks(buf, PH)).toBe(buf);
});
@@ -145,6 +153,30 @@ describe('set B — literal <agent> in code must be preserved', () => {
expect(_stripSurvivingAgentBlocks(buf)).toBe(buf);
expect(_replaceOuterAgentBlocks(buf, PH)).toBe(buf);
});
+
+ it('B4. inline quoted text survives', () => {
+ const buf = '请输出 "<agent>...</agent>" 这几个字符';
+ expect(_stripSurvivingAgentBlocks(buf)).toBe(buf);
+ expect(_replaceOuterAgentBlocks(buf, PH)).toBe(buf);
+ });
+});
+
+describe('explicit XML fences are treated as structural blocks', () => {
+ it('strips a complete agent container inside ```xml', () => {
+ const buf = '```xml\n<agent><name>X</name></agent>\n```';
+ expect(_stripSurvivingAgentBlocks(buf)).toBe('```xml\n\n```');
+ expect(_replaceOuterAgentBlocks(buf, PH)).toBe(`\`\`\`xml\n${PH}\n\`\`\``);
+ });
+
+ it('quoted XML at line start is still a structure block', () => {
+ const buf = '"<agent><name>X</name></agent>"';
+ expect(_replaceOuterAgentBlocks(buf, PH)).toBe(`"${PH}"`);
+ });
+
+ it('inline quoted XML inside ```xml is still structural', () => {
+ const buf = '```xml\nvalue="<agent><name>X</name></agent>"\n```';
+ expect(_replaceOuterAgentBlocks(buf, PH)).toBe(`\`\`\`xml\nvalue="${PH}"\n\`\`\``);
+ });
});
// --- Mixed: container + literal mention coexisting -------------------------
@@ -153,7 +185,7 @@ describe('mixed — real container + literal mention in one buffer', () => {
it('only the real container is replaced; quoted example survives', () => {
const buf = [
'Example format:',
- '```xml',
+ '```',
'<agent><name>Example</name></agent>',
'```',
'And here is the actual one:',
@@ -164,8 +196,8 @@ describe('mixed — real container + literal mention in one buffer', () => {
'done.',
].join('\n');
const stripped = _stripSurvivingAgentBlocks(buf);
- // Quoted example inside ```xml stays.
- expect(stripped).toContain('```xml');
+ // Quoted example inside a non-XML code fence stays.
+ expect(stripped).toContain('```');
expect(stripped).toContain('<agent><name>Example</name></agent>');
// Real one's tags / interior gone.
expect(stripped).not.toContain('<name>Real</name>');
@@ -191,11 +223,16 @@ describe('granularity invariant — the guard is anchored at the opening tag', (
expect(buf.slice(start, end)).toBe('<agent>a `b` c</agent>');
});
- it('opener inside fenced code → no range produced', () => {
+ it('opener inside non-XML fenced code → no range produced', () => {
const buf = '```\n<agent>x</agent>\n```';
expect(_findOuterAgentRanges(buf)).toEqual([]);
});
+ it('opener inside explicit XML fenced code → range produced', () => {
+ const buf = '```xml\n<agent>x</agent>\n```';
+ expect(_findOuterAgentRanges(buf)).toHaveLength(1);
+ });
+
it('opener inside inline backticks → no range produced', () => {
const buf = 'see `<agent>` token';
expect(_findOuterAgentRanges(buf)).toEqual([]);
@@ -245,8 +282,8 @@ describe('<agent-input-form> — set A (real form blocks must be replaced)', ()
});
describe('<agent-input-form> — set B (literal mentions must survive)', () => {
- it('B1. inside a fenced ```xml block (protocol explanation)', () => {
- const buf = 'Format:\n```xml\n<agent-input-form>\n[]\n</agent-input-form>\n```\nend';
+ it('B1. inside a fenced non-XML code block (protocol explanation)', () => {
+ const buf = 'Format:\n```\n<agent-input-form>\n[]\n</agent-input-form>\n```\nend';
expect(_replaceOuterTagBlocks(buf, 'agent-input-form', PH)).toBe(buf);
});
@@ -261,6 +298,13 @@ describe('<agent-input-form> — set B (literal mentions must survive)', () => {
});
});
+describe('<agent-input-form> — explicit XML fences are structural', () => {
+ it('replaces a form block inside ```xml', () => {
+ const buf = 'Format:\n```xml\n<agent-input-form>\n[]\n</agent-input-form>\n```\nend';
+ expect(_replaceOuterTagBlocks(buf, 'agent-input-form', PH)).toBe(`Format:\n\`\`\`xml\n${PH}\n\`\`\`\nend`);
+ });
+});
+
describe('<agent-input-submission> — set A (real submission tags stripped)', () => {
it('A1. submission tag with attributes and JSON body', () => {
const buf = 'You confirmed:\n<agent-input-submission form_id="abc12345" agent_id="my-agent">\n{"topic":"x"}\n</agent-input-submission>';
@@ -278,8 +322,8 @@ describe('<agent-input-submission> — set A (real submission tags stripped)', (
});
describe('<agent-input-submission> — set B (literal mentions survive)', () => {
- it('B1. inside a fenced ```xml block', () => {
- const buf = 'Reply format:\n```xml\n<agent-input-submission form_id="x" agent_id="y">\n{}\n</agent-input-submission>\n```';
+ it('B1. inside a fenced non-XML code block', () => {
+ const buf = 'Reply format:\n```\n<agent-input-submission form_id="x" agent_id="y">\n{}\n</agent-input-submission>\n```';
expect(_stripOuterTagBlocks(buf, 'agent-input-submission')).toBe(buf);
});
@@ -294,6 +338,102 @@ describe('<agent-input-submission> — set B (literal mentions survive)', () =>
});
});
+describe('<agent-input-submission> — explicit XML fences are structural', () => {
+ it('strips a submission block inside ```xml', () => {
+ const buf = 'Reply format:\n```xml\n<agent-input-submission form_id="x" agent_id="y">\n{}\n</agent-input-submission>\n```';
+ expect(_stripOuterTagBlocks(buf, 'agent-input-submission')).toBe('Reply format:\n```xml\n\n```');
+ });
+});
+
+describe('main-chat creation stream stripping', () => {
+ function streamDisplay(buf: string): string {
+ return _stripSkillCreateContainer(
+ _replaceOuterTagBlocks(
+ strip._replaceOuterSkillFileBlocks(buf, (path: string) => `\n[writing ${path || 'file'}]\n`),
+ 'agent',
+ PH,
+ ),
+ PH,
+ );
+ }
+
+ it('does not leak skill frontmatter or agent XML while bulk create output streams', () => {
+ const raw = [
+ '<skill>',
+ '<<<skill-file path=SKILL.md',
+ '---',
+ 'name: leio-sdlc-adapter',
+ 'description_zh: "把研发工作组织成带状态机和队列的流程"',
+ 'description_en: "Organize engineering work into an SDLC flow"',
+ '---',
+ '',
+ '# leio-sdlc-adapter',
+ '## 何时使用',
+ '- 用户提到 `LEIO SDLC`。',
+ '>>>',
+ '</skill>',
+ '',
+ '<agent>',
+ '<name>Plandex研发助手</name>',
+ '<description_zh>围绕大项目编码任务做计划。</description_zh>',
+ '<workflow>',
+ '### 1. 收集上下文',
+ '- `read_file` — 读取材料。',
+ '</workflow>',
+ '</agent>',
+ ].join('\n');
+
+ for (let i = 1; i <= raw.length; i++) {
+ 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]');
+ });
+});
+
+describe('user message display stripping', () => {
+ it('preserves ordinary one-line @agent messages', () => {
+ const buf = '@Agent Skill 搜集 你再次执行';
+ expect(_stripUserStructuralBlocksForDisplay(buf)).toBe(buf);
+ });
+
+ it('strips the routing @mention only for real form submission replays', () => {
+ const buf = [
+ '@Research Agent',
+ 'You confirmed:',
+ '<agent-input-submission form_id="abc12345" agent_id="research-agent">',
+ '{"topic":"x"}',
+ '</agent-input-submission>',
+ ].join('\n');
+ expect(_stripUserStructuralBlocksForDisplay(buf)).toBe('You confirmed:');
+ });
+});
+
+describe('skill id display replacement', () => {
+ const skills = [
+ { id: '16e1bfcb3426', name: 'agent-creator' },
+ { id: 'efb0fe5d9664', name: 'skill-creator' },
+ ];
+
+ it('renders marketplace skill ids as display names in prose', () => {
+ const buf = 'Use `16e1bfcb3426`, then follow efb0fe5d9664.';
+ expect(_replaceKnownSkillIdsForDisplay(buf, skills))
+ .toBe('Use `agent-creator`, then follow skill-creator.');
+ });
+
+ it('does not replace embedded hash fragments or unknown ids', () => {
+ const buf = 'x16e1bfcb3426y 000000000000';
+ expect(_replaceKnownSkillIdsForDisplay(buf, skills)).toBe(buf);
+ });
+
+ it('simplifies skill follow phrasing to a compact display reference', () => {
+ expect(_simplifyKnownSkillFollowPhrasesForDisplay('skill: follow the `agent-creator` skill,then continue', skills))
+ .toBe('`agent-creator` skill,then continue');
+ expect(_normalizeKnownSkillRefsForDisplay('`skill: follow the 16e1bfcb3426 skill` — create agents', skills))
+ .toBe('`agent-creator` skill — create agents');
+ });
+});
+
// `<artifact-result>` — the machine tag a renderer composes when an
// interactive artifact posts a result back; carried in a user message so
// the agent can parse it, stripped from the user bubble's display via
@@ -315,8 +455,8 @@ describe('<artifact-result> — set A (real result tags stripped from display)',
});
describe('<artifact-result> — set B (literal mentions survive)', () => {
- it('B1. inside a fenced ```xml block (e.g. the tool description quoting the protocol)', () => {
- const buf = 'Format:\n```xml\n<artifact-result artifact_id="x" agent_id="y">\n{...}\n</artifact-result>\n```';
+ it('B1. inside a fenced non-XML code block (e.g. the tool description quoting the protocol)', () => {
+ const buf = 'Format:\n```\n<artifact-result artifact_id="x" agent_id="y">\n{...}\n</artifact-result>\n```';
expect(_stripOuterTagBlocks(buf, 'artifact-result')).toBe(buf);
});
@@ -331,6 +471,13 @@ describe('<artifact-result> — set B (literal mentions survive)', () => {
});
});
+describe('<artifact-result> — explicit XML fences are structural', () => {
+ it('strips a result block inside ```xml', () => {
+ const buf = 'Format:\n```xml\n<artifact-result artifact_id="x" agent_id="y">\n{...}\n</artifact-result>\n```';
+ expect(_stripOuterTagBlocks(buf, 'artifact-result')).toBe('Format:\n```xml\n\n```');
+ });
+});
+
// --- Boundary check: tagName lookup must not bleed across siblings -------
describe('boundary check — `<agent>` lookup must not match `<agent-input-form>`', () => {
@@ -411,7 +558,7 @@ describe('_stripSurvivingStructuralBlocks (final-time safety strip)', () => {
it('preserves every literal mention inside fenced code', () => {
const buf = [
'Three protocol tags:',
- '```xml',
+ '```',
'<agent><name>X</name></agent>',
'<agent-input-form>\n[]\n</agent-input-form>',
'<agent-input-submission form_id="f" agent_id="a">{}</agent-input-submission>',
@@ -432,7 +579,7 @@ describe('_stripSurvivingStructuralBlocks (final-time safety strip)', () => {
it('mixed: real <agent> + literal forms in code → only <agent> stripped', () => {
const buf = [
'spec:',
- '```xml',
+ '```',
'<agent-input-form>\n[]\n</agent-input-form>',
'```',
'<agent><name>Real</name></agent>',
@@ -444,6 +591,24 @@ describe('_stripSurvivingStructuralBlocks (final-time safety strip)', () => {
expect(out).toContain('after');
});
+ it('strips structural tags inside explicit XML fences', () => {
+ const buf = [
+ 'Three protocol tags:',
+ '```xml',
+ '<agent><name>X</name></agent>',
+ '<agent-input-form>\n[]\n</agent-input-form>',
+ '<agent-input-submission form_id="f" agent_id="a">{}</agent-input-submission>',
+ '```',
+ 'end',
+ ].join('\n');
+ const out = _stripSurvivingStructuralBlocks(buf);
+ expect(out).not.toContain('<agent><name>X</name></agent>');
+ expect(out).not.toContain('<agent-input-form>');
+ expect(out).not.toContain('<agent-input-submission');
+ expect(out).toContain('```xml');
+ expect(out).toContain('end');
+ });
+
it('no-op when buffer has none of the three tags', () => {
const buf = 'plain prose with no structural tags';
expect(_stripSurvivingStructuralBlocks(buf)).toBe(buf);
@@ -582,6 +747,38 @@ describe('skill-file — set B (literal <<<skill-file>>> mentions must survive)'
expect(_stripOuterSkillFileBlocks(buf)).toBe(buf);
expect(_replaceOuterSkillFileBlocks(buf, SKILL_PH)).toBe(buf);
});
+
+ it('B4. inline quoted text survives', () => {
+ const buf = '请输出 "<<<skill-file path=SKILL.md>>>" 这几个字符';
+ expect(_stripOuterSkillFileBlocks(buf)).toBe(buf);
+ expect(_replaceOuterSkillFileBlocks(buf, SKILL_PH)).toBe(buf);
+ });
+});
+
+describe('skill-file — explicit XML fences are machine blocks', () => {
+ it('replaces a complete skill-file block inside ```xml', () => {
+ const buf = [
+ '```xml',
+ '<<<skill-file path=SKILL.md',
+ 'body',
+ '>>>',
+ '```',
+ ].join('\n');
+ expect(_stripOuterSkillFileBlocks(buf)).toBe('```xml\n\n```');
+ expect(_replaceOuterSkillFileBlocks(buf, SKILL_PH)).toBe('```xml\n⟨SKILL:SKILL.md⟩\n```');
+ });
+
+ it('replaces an inline quoted skill-file block inside ```xml', () => {
+ const buf = [
+ '```xml',
+ 'value="<<<skill-file path=SKILL.md',
+ 'body',
+ '>>>"',
+ '```',
+ ].join('\n');
+ expect(_stripOuterSkillFileBlocks(buf)).toBe('```xml\nvalue=""\n```');
+ expect(_replaceOuterSkillFileBlocks(buf, SKILL_PH)).toBe('```xml\nvalue="⟨SKILL:SKILL.md⟩"\n```');
+ });
});
describe('skill-file — mixed (real block + literal mention coexisting)', () => {
@@ -694,6 +891,32 @@ describe('_stripSkillCreateContainer — set A (real shapes)', () => {
expect(out).not.toContain('<skill>');
});
+ it('A2b. closed real container hides skill-file blocks even when the LLM fenced them', () => {
+ // The backend can still parse this because the `<skill>` container is
+ // real. If a raw `<<<skill-file>>>` survives until this later pass, the
+ // streaming renderer must not leak SKILL.md body content while waiting
+ // for the final parsed message.
+ const buf = [
+ '<skill>',
+ '```xml',
+ '<<<skill-file path=SKILL.md',
+ '---',
+ 'name: frontend-ui-engineering',
+ '---',
+ '',
+ '## Quick Reference: ARIA Live Regions',
+ '| Value | Behavior |',
+ '>>>',
+ '```',
+ '</skill>',
+ ].join('\n');
+ const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
+ expect(out).toContain('⟨FALLBACK⟩');
+ expect(out).not.toContain('<<<skill-file');
+ expect(out).not.toContain('frontend-ui-engineering');
+ expect(out).not.toContain('Quick Reference: ARIA Live Regions');
+ });
+
it('A3. unclosed container collapses to fallback placeholder', () => {
// Mid-stream: `<skill>` opened, no `</skill>` yet. Inner content may
// still be raw `<skill_id>` / token fragments — the fallback hides
@@ -736,12 +959,12 @@ describe('_stripSkillCreateContainer — set B (look-alikes must NOT match)', ()
expect(out).toBe(buf);
});
- it('B2. literal `<skill>` inside a fenced ```xml block (protocol explanation)', () => {
- // LLM showing the user the protocol shape inside a code fence must
- // not be processed as a real container.
+ it('B2. explicit `<skill>` inside a fenced ```xml block is structural', () => {
const buf = 'See:\n```xml\n<skill>\n<skill_id>foo</skill_id>\n</skill>\n```\nend';
const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
- expect(out).toBe(buf);
+ expect(out).not.toContain('<skill>');
+ expect(out).not.toContain('<skill_id>');
+ expect(out).not.toContain('foo');
});
it('B3. literal `<skill>` inside an inline backtick span', () => {
@@ -750,6 +973,12 @@ describe('_stripSkillCreateContainer — set B (look-alikes must NOT match)', ()
expect(out).toBe(buf);
});
+ it('B3b. inline quoted `<skill>` text survives', () => {
+ const buf = '请输出 "<skill>...</skill>" 这几个字符';
+ const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
+ expect(out).toBe(buf);
+ });
+
it('B4. bare prose with no `<skill>` token returns input unchanged', () => {
const buf = 'I will write a skill that does X';
const out = _stripSkillCreateContainer(buf, '⟨FALLBACK⟩');
diff --git a/test/renderer/utils-dashboard.test.ts b/test/renderer/utils-dashboard.test.ts
new file mode 100644
index 00000000..f6f2d2e3
--- /dev/null
+++ b/test/renderer/utils-dashboard.test.ts
@@ -0,0 +1,249 @@
+// Pin the `:::dashboard` directive renderer behavior in
+// `src/renderer/modules/utils.js`.
+//
+// Set A — shapes the renderer MUST handle:
+// - every component type (Stack / Grid / Card / Separator / Metric /
+// Chart / Table / Alert / Timeline / Code / Markdown / Image)
+// - nested trees (Stack wrapping Grid wrapping Metric)
+// - props enum coercion (gap=md, columns=3, tone=positive, level=warning)
+// - $-prefixed escaping in text (no regex-replacement footgun)
+//
+// Set B — shapes the renderer MUST NOT break:
+// - existing `:::chart-bar` directive still renders alongside `:::dashboard`
+// - plain markdown (headings, lists, tables) around a `:::dashboard` block
+// parses normally
+// - malformed JSON falls back to `.dashboard-parse-error` code block,
+// does NOT silently drop the block and does NOT throw
+// - unknown component `type` renders an inert `<div class="db-unknown">`
+// (no exception, surrounding tree continues)
+//
+// Per PC/CLAUDE.md §9 (LLM-output text munging): adding any guard / new
+// component / new enum value requires extending these fixtures and
+// keeping every prior fixture green.
+
+import { describe, it, expect } from 'vitest';
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const utils = require('../../src/renderer/modules/utils.js');
+const { renderMarkdown, renderDashboard } = utils as {
+ renderMarkdown: (md: string) => string;
+ renderDashboard: (spec: unknown) => string;
+};
+
+function fence(spec: unknown): string {
+ return '```fence-placeholder```\n\n:::dashboard\n' + JSON.stringify(spec) + '\n:::\n';
+}
+
+describe('renderDashboard — component coverage (set A)', () => {
+ it('renders the root wrapper with theme data attrs', () => {
+ const html = renderDashboard({ schema_version: 1, theme: { color: 'brand', style: 'card' }, root: null });
+ expect(html).toMatch(/class="dashboard"/);
+ expect(html).toMatch(/data-theme-color="brand"/);
+ expect(html).toMatch(/data-theme-style="card"/);
+ });
+
+ it('Stack: respects direction + gap', () => {
+ const html = renderDashboard({ root: { type: 'Stack', props: { direction: 'horizontal', gap: 'lg' }, children: [] } });
+ expect(html).toMatch(/data-direction="horizontal"/);
+ expect(html).toMatch(/data-gap="lg"/);
+ });
+
+ it('Grid: clamps columns to 1..4 and applies gap', () => {
+ const html = renderDashboard({ root: { type: 'Grid', props: { columns: 99, gap: 'sm' }, children: [] } });
+ expect(html).toMatch(/data-columns="4"/);
+ expect(html).toMatch(/data-gap="sm"/);
+ });
+
+ it('Card: emits title + tone', () => {
+ const html = renderDashboard({ root: { type: 'Card', props: { title: 'Status', tone: 'warning' }, children: [] } });
+ expect(html).toMatch(/data-tone="warning"/);
+ expect(html).toContain('Status');
+ });
+
+ it('Separator: renders <hr>', () => {
+ const html = renderDashboard({ root: { type: 'Separator' } });
+ expect(html).toMatch(/<hr class="db-separator">/);
+ });
+
+ it('Metric: label / value / delta with tone', () => {
+ const html = renderDashboard({ root: { type: 'Metric', props: { label: 'Revenue', value: '$164B', delta: '+18%', tone: 'positive' } } });
+ expect(html).toContain('Revenue');
+ expect(html).toContain('$164B');
+ expect(html).toContain('+18%');
+ expect(html).toMatch(/db-metric-delta[^>]*data-tone="positive"/);
+ });
+
+ it('Alert: level + title + body', () => {
+ const html = renderDashboard({ root: { type: 'Alert', props: { level: 'error', title: 'Down', body: 'Check uplink' } } });
+ expect(html).toMatch(/data-level="error"/);
+ expect(html).toContain('Down');
+ expect(html).toContain('Check uplink');
+ });
+
+ it('Table: emits columns + rows with numeric alignment', () => {
+ const html = renderDashboard({ root: { type: 'Table', props: {
+ columns: [{ key: 'host', label: 'Host' }, { key: 'rtt', label: 'RTT', numeric: true }],
+ rows: [{ host: '10.0.0.1', rtt: 12 }, { host: '10.0.0.2', rtt: 84 }],
+ } } });
+ expect(html).toContain('<th>Host</th>');
+ expect(html).toContain('<th data-numeric="1">RTT</th>');
+ expect(html).toContain('10.0.0.1');
+ expect(html).toMatch(/<td data-numeric="1">12<\/td>/);
+ });
+
+ it('Timeline: enumerates items', () => {
+ const html = renderDashboard({ root: { type: 'Timeline', props: { items: [
+ { time: '09:00', label: 'Deploy', body: 'rollout v3.4' },
+ { time: '09:12', label: 'Smoke OK' },
+ ] } } });
+ expect(html).toContain('09:00');
+ expect(html).toContain('Deploy');
+ expect(html).toContain('rollout v3.4');
+ expect(html).toContain('Smoke OK');
+ });
+
+ it('Code: emits language attr', () => {
+ const html = renderDashboard({ root: { type: 'Code', props: { lang: 'bash', code: 'ls -la' } } });
+ expect(html).toMatch(/data-lang="bash"/);
+ expect(html).toContain('ls -la');
+ });
+
+ it('Markdown: re-enters markdown renderer for nested text', () => {
+ const html = renderDashboard({ root: { type: 'Markdown', props: { text: '## hi\n- one\n- two' } } });
+ expect(html).toContain('<h2>hi</h2>');
+ expect(html).toContain('<li>one');
+ expect(html).toContain('<li>two');
+ });
+
+ it('Markdown: accepts `content` as an alias for `text` (model-guess shape)', () => {
+ const html = renderDashboard({ root: { type: 'Markdown', props: { content: '## body\nparagraph' } } });
+ expect(html).toContain('<h2>body</h2>');
+ expect(html).toContain('paragraph');
+ });
+
+ it('Markdown: `text` wins when both fields are present', () => {
+ const html = renderDashboard({ root: { type: 'Markdown', props: { text: 'from-text', content: 'from-content' } } });
+ expect(html).toContain('from-text');
+ expect(html).not.toContain('from-content');
+ });
+
+ it('Markdown: strips nested :::dashboard to prevent infinite recursion', () => {
+ const html = renderDashboard({ root: { type: 'Markdown', props: { text: 'before\n:::dashboard\n{}\n:::\nafter' } } });
+ expect(html).toContain('before');
+ expect(html).toContain('after');
+ // The stripped nested directive must not produce a second .dashboard wrap.
+ expect(html.match(/class="dashboard"/g)).toHaveLength(1);
+ });
+
+ it('Image: src + alt + caption', () => {
+ const html = renderDashboard({ root: { type: 'Image', props: { src: 'https://x.test/a.png', alt: 'A', caption: 'fig 1' } } });
+ expect(html).toContain('src="https://x.test/a.png"');
+ expect(html).toContain('alt="A"');
+ expect(html).toContain('fig 1');
+ });
+
+ it('Chart bar: emits one <rect> per data point', () => {
+ const html = renderDashboard({ root: { type: 'Chart', props: { kind: 'bar', data: [
+ { x: 'a', y: 3 }, { x: 'b', y: 5 }, { x: 'c', y: 1 },
+ ] } } });
+ expect(html).toMatch(/data-kind="bar"/);
+ expect((html.match(/<rect /g) || []).length).toBe(3);
+ });
+
+ it('Chart line: emits a <path class="db-chart-line">', () => {
+ const html = renderDashboard({ root: { type: 'Chart', props: { kind: 'line', data: [
+ { x: 't0', y: 0 }, { x: 't1', y: 4 },
+ ] } } });
+ expect(html).toMatch(/class="db-chart-line"/);
+ });
+
+ it('Chart pie: emits one slice per item and a legend', () => {
+ const html = renderDashboard({ root: { type: 'Chart', props: { kind: 'pie', data: [
+ { label: 'A', value: 1 }, { label: 'B', value: 2 }, { label: 'C', value: 3 },
+ ] } } });
+ expect((html.match(/db-chart-slice/g) || []).length).toBe(3);
+ expect(html).toContain('class="db-chart-legend"');
+ });
+
+ it('nested tree: Stack → Grid → Metric × 3', () => {
+ const html = renderDashboard({ root: { type: 'Stack', props: { gap: 'md' }, children: [
+ { type: 'Grid', props: { columns: 3 }, children: [
+ { type: 'Metric', props: { label: 'A', value: '1' } },
+ { type: 'Metric', props: { label: 'B', value: '2' } },
+ { type: 'Metric', props: { label: 'C', value: '3' } },
+ ] },
+ ] } });
+ expect((html.match(/db-metric"/g) || []).length).toBe(3);
+ expect(html).toMatch(/data-columns="3"/);
+ });
+});
+
+describe('renderDashboard — defensive / unknown shapes (set A safety)', () => {
+ it('unknown component type → inert placeholder, no throw', () => {
+ const html = renderDashboard({ root: { type: 'Nonsense', props: {} } });
+ expect(html).toContain('class="db-unknown"');
+ expect(html).toContain('data-type="Nonsense"');
+ });
+
+ it('missing props on Metric → still renders empty fields, no throw', () => {
+ expect(() => renderDashboard({ root: { type: 'Metric' } })).not.toThrow();
+ });
+
+ it('non-object spec → empty string', () => {
+ expect(renderDashboard(null)).toBe('');
+ expect(renderDashboard(42)).toBe('');
+ });
+
+ it('escapes HTML in user-supplied text', () => {
+ const html = renderDashboard({ root: { type: 'Metric', props: { label: '<script>x</script>', value: '"q"' } } });
+ expect(html).not.toContain('<script>x</script>');
+ expect(html).toContain('&lt;script&gt;');
+ expect(html).toContain('&quot;q&quot;');
+ });
+
+ it('handles $ in value without regex-replacement breakage', () => {
+ const html = renderDashboard({ root: { type: 'Metric', props: { label: 'Cost', value: '$1,234' } } });
+ expect(html).toContain('$1,234');
+ });
+});
+
+describe('renderMarkdown integration — set B (must not break existing surfaces)', () => {
+ it(':::chart-bar still renders alongside :::dashboard', () => {
+ const md = ':::chart-bar\n[{"label":"x","value":5}]\n:::\n\n:::dashboard\n' +
+ JSON.stringify({ root: { type: 'Metric', props: { label: 'A', value: '1' } } }) + '\n:::';
+ const html = renderMarkdown(md);
+ expect(html).toContain('chart-bar-container');
+ expect(html).toContain('db-metric');
+ });
+
+ it('plain markdown around a dashboard block parses normally', () => {
+ const md = '# Title\n\nSome **bold** text.\n\n' +
+ ':::dashboard\n' + JSON.stringify({ root: { type: 'Separator' } }) + '\n:::\n\n' +
+ '- item 1\n- item 2\n';
+ const html = renderMarkdown(md);
+ expect(html).toContain('<h1>Title</h1>');
+ expect(html).toContain('<strong>bold</strong>');
+ expect(html).toContain('db-separator');
+ expect(html).toContain('<li>item 1');
+ });
+
+ it('malformed JSON in :::dashboard falls back to code-view, no throw', () => {
+ const md = ':::dashboard\nnot { valid: json }\n:::';
+ const html = renderMarkdown(md);
+ expect(html).toContain('dashboard-parse-error');
+ // raw body is preserved (HTML-escaped) so the user can copy it
+ expect(html).toContain('not { valid: json }');
+ // and NO .dashboard wrapper was emitted
+ expect(html).not.toMatch(/class="dashboard"/);
+ });
+
+ it('unclosed :::dashboard at end of doc → not a dashboard, body kept', () => {
+ const md = ':::dashboard\n{ "root": null }\n';
+ const html = renderMarkdown(md);
+ // The regex requires a closing :::, so an unclosed block stays as text.
+ expect(html).not.toMatch(/class="dashboard"/);
+ // The literal `:::dashboard` line ends up as paragraph text — that's fine,
+ // the test pins the no-crash + no-wrong-render behavior, not the verbatim
+ // pre-paragraph output (markdown phase 2 may shape it).
+ expect(html.length).toBeGreaterThan(0);
+ });
+});