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(group_chat plan stability + Japanese locale + reflection + signals)

wyt3f63dd243767
diff --git a/CLAUDE.md b/CLAUDE.md
index 41929186..c67ecb23 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -107,14 +107,14 @@ Exception: env-var names with the project prefix (`ORKAS_NODE` / `ORKAS_PC_DIR`)
## 4. data sync domains
-Top-level three-way split: **☁️ cloud** (user-private, synced across devices) / **🔒 local** (machine-private, never synced) / **🌐 top-level** (globally shared).
+Top-level three-way split: **cloud** (user-private, synced across devices) / **local** (machine-private, never synced) / **top-level** (globally shared).
```
-PC/data/
-├── users.json 🌐 Local uid registry + current_user_id
-├── logs/ 🌐 Local logs (rolled daily, shared across uids)
+<container>/data/
+├── users.json top-level Local uid registry + current_user_id
+├── logs/ top-level Local logs (rolled daily, shared across uids)
└── <user_id>/
- ├── cloud/ ☁️ Cloud-sync domain
+ ├── cloud/ Cloud-sync domain
│ ├── chats/<cid>.jsonl + chats/<cid>/{members,state,plan,visibility/} group-chat runtime state (see §5)
│ ├── chats/{skill,agent}/<id>/chat.{json,jsonl} edit sessions
│ ├── chat_attachments/<cid>/ Main-conversation attachment pool (zero pre-processing)
@@ -128,7 +128,7 @@ PC/data/
│ ├── projects/<pid>/{project.json, bindings.json} Logical groups of conversations + per-project agent/skill scope (no aggregate index — list = directory scan)
│ ├── marketplace/installs.json Cloud-synced manifest of platform installs ({id, version, published_at, url} per agent + skill) — reconciled on startup
│ └── config/{preferences,component-enabled,connectors}.json (connectors.json: plaintext envelope + per-instance vault-encrypted `secrets_enc`; seed = OAuth user_id — see §6.5)
- └── local/ 🔒 Machine-private domain (never synced)
+ └── local/ Machine-private domain (never synced)
├── config/ User prefs (auth-profiles / connector-oauth / permissions / reflection-state / web-search-cache / account = `(user_id, session_id)` + device_id + cached profile) — NEVER user-clearable
├── biz/ Server-sourced business data (marketplace.json — 24h TTL category registry); refresh-on-need but NOT user-clearable
├── marketplace/{agents,skills}/<id>/ Platform-installed content (per-machine copy reconciled from cloud installs.json)
@@ -145,16 +145,16 @@ PC/data/
3. **Agent directory shape (per-agent asset aggregation)**: `<uid>/cloud/agents/<aid>/` contains `agent.json` (the sole UI display source — pure spec) + `meta/` (metacognition: COMPETENCE.md + LEARNING_STRATEGIES.md) + `skills/` (SkillStore self-evolved skills, visible only to this agent, not injected into the SkillLoader system-prompt block). Deleting an agent = `rm -rf <aid>/`, no cascade. See `docs/plans/agent-as-directory.md`. **Do not** revert to the old top-level `meta/` or `PC/skills/` (the SkillStore default cwd).
4. **`search/` indexes are purely derived**: never synced; mtime+size reconcile self-heals before each query; 1-second debounced flush + force flush on `before-quit`; rebuild automatically on schema change or corruption.
5. **The KB vector store is NOT cloud-synced (batch 2 decision)**: only `cloud/contexts/` source files cross devices; the `vector.db` + its `config.json` live at `<uid>/local/contexts/.kb/` (machine-private, NOT under cloud/). Each device's startup `kb_indexer.reconcile(uid)` rebuilds the index from the synced sources idempotently by sha1. One-shot migration `util/migrate-kb-to-local.ts` moves a pre-existing `<uid>/cloud/contexts/.kb/` directory into local/ on first launch (stamped under `.migrations`). **Why path mirrors cloud/contexts/ under local/contexts/**: keeps the mental model "KB lives under .../contexts/.kb/" intact across the cloud/local divide, so the cloud→local split is reflected in the path without renaming the `.kb` segment. **Why this changed from the earlier "vector.db IS synced" rule**: a single-doc edit kicks a hundreds-of-MB whole-DB re-upload — economics broke down once we wired the actual sync engine. Index rebuild is per-spec idempotent, so reuse it. **Journal mode is still DELETE, not WAL** (no benefit from switching; `kb_files` rows already use it).
-6. **Multi-device sync (plan: `PC/docs/plans/multi-device-sync.md`)**: COS bucket prefix = **`private/<oauth_user_id>/`** (NOT the local 8-digit `uid`); per-machine path stays `<container>/data/<local_uid>/cloud/`, and `private/<oauth_user_id>/` is the cloud-side mirror. **Why the `private/` namespace**: leaves the rest of the bucket (e.g. `public/marketplace/skills/`) freely STS-scoped for non-user-private content; without it, widening any future public scope risks colliding with user data prefixes. **Why oauth_user_id (not local uid)**: same OAuth user has different local `uid` on each device — using local uid would scatter cloud data. The `features/sync/` engine is the **sole** writer of cloud→COS traffic and `private/<oauth_user_id>/cloud/*` keys; `features/sync/manifest.ts::commitManifest` (POST `/sync/manifest/commit`) is the **sole** writer of `private/<oauth_user_id>/manifest.json` (Server enforces atomicity via per-user lock + generation CAS + quota delta; see `Server/CLAUDE.md` §4). PC's STS scope is `private/<oauth_user_id>/*` for read, `private/<oauth_user_id>/cloud/*` for write — `manifest.json` is read-only for PC by design. **Five canonical sync triggers** funnel through `DirtyBus` / `engine.syncNow`: startup (post-marketplace reconcile), debounce-fired dirty event, manual ("立即同步" button), 5-minute periodic safety-net ticker (`engine.ts::PERIODIC_INTERVAL_MS`, bound to engine lifetime so the master switch gates it for free), before-quit. The 30s global floor between auto runs (`engine.ts::GLOBAL_FLOOR_MS`) applies to all except manual + before-quit (which bypass it intentionally; periodic respects it — a recent pass for any reason defers the next tick).
+6. **Multi-device sync (plan: `PC/docs/plans/multi-device-sync.md`)**: COS bucket prefix = **`private/<oauth_user_id>/`** (NOT the local 8-digit `uid`); per-machine path stays `<container>/data/<local_uid>/cloud/`, and `private/<oauth_user_id>/` is the cloud-side mirror. **Why the `private/` namespace**: leaves the rest of the bucket (e.g. `public/marketplace/skills/`) freely STS-scoped for non-user-private content; without it, widening any future public scope risks colliding with user data prefixes. **Why oauth_user_id (not local uid)**: same OAuth user has different local `uid` on each device — using local uid would scatter cloud data. The `features/sync/` engine is the **sole** writer of cloud→COS traffic and `private/<oauth_user_id>/cloud/*` keys; `features/sync/manifest.ts::commitManifest` (POST `/sync/manifest/commit`) is the **sole** writer of `private/<oauth_user_id>/manifest.json` (Server enforces atomicity via per-user lock + generation CAS + quota delta; see `Server/CLAUDE.md` §4). PC's STS scope is `private/<oauth_user_id>/*` for read, `private/<oauth_user_id>/cloud/*` for write — `manifest.json` is read-only for PC by design. **Five canonical sync triggers** funnel through `DirtyBus` / `engine.syncNow`: startup (post-marketplace reconcile), debounce-fired dirty event, manual ("立即同步" button), 5-minute periodic safety-net ticker (`engine.ts::PERIODIC_INTERVAL_MS`, bound to engine lifetime so the master switch gates it for free), before-quit. The 30s global floor between auto runs (`engine.ts::GLOBAL_FLOOR_MS`) applies to all except manual + before-quit (which bypass it intentionally; periodic respects it — a recent pass for any reason defers the next tick). **3-way pull classification** (`manifest.ts::classifyPullCandidates`, called from `_passBody` step 5): every path `diff()` puts into `need_pull` is routed by the (base, disk, remote) sha tuple — case A `base==disk` (local untouched, remote moved) → straight overwrite, **never push**; case B `base==remote` (local moved, remote untouched) → reclassify to push (legacy 3-way diff); case C three-way divergence → content-aware merge, then push the merge result back. **Why case A must not push**: a path whose on-disk bytes differ from base usually came from a prior merge's residue, NOT a fresh user edit — pushing it would publish the engine's own historical output as if it were a user change. We shipped this bug for a while and saw `pulled: 4 / pushed: 0` every pass for the same set of jsonl + mutable-json paths; the case A bucket is the load-bearing fix.
7. **Master switch defaults OFF** (user opt-in). `local/sync/state.json::enabled = false` until the settings card toggle turns it on. The engine's `init()` is a no-op while off, so login alone does not trigger any upload — there is exactly one moment data starts crossing the wire, and the user clicked a toggle to cause it.
- **`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). Local-only, append-only, daily-rotated. **Sole writer = `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}`. **Why centralized**: scattered `emitSignal` across `features/*` 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. Phase 0 has NO redaction layer (see §10). Plan: `docs/plans/expert-signals-phase-0.md`.
-
**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}`, and `user_id` + `session_id` (+ the cached `user_info` profile) 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 (`/account/points`) re-validates it — 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` block — 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`.
+**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`.
+
+**Membership-and-billing surface** (`features/account/subscription.ts` + the same `account.json` row carrying `subscription`): the snapshot rides on the existing `account:changed` push (`state.statusPayload.subscription`) — there is no second IPC channel for "tier-changed". The renderer's `views/login/account_settings.js::renderSubscriptionSettings()` reads from there + visibility-change re-fetch via `account.fetchMe()`. **Cloud sync and voice input are Pro-only** (Server-side gate via `require_entitlement("sync_enabled" | "voice_enabled")` in `Server/api/{sync,voice}.py`); the PC sync engine's master-switch in `local/sync/state.json::enabled` stays user-controlled, but writes will be 50403-rejected when `subscription.tier !== 'pro'` or status is non-active+non-grace — so the renderer's `sync_settings.js` should treat that as an expected failure mode (existing error UI surfaces it), not a bug. The renderer's only billing-action path is `account.openWebAccount()` → `/account/web_session/start` → `shell.openExternal` to the Web Account page; `BILLING_ACTIVE_PROVIDER=none` profiles render the Subscribe button as "Coming soon" (`account.subscription.billing_enabled` carries the answer; never gate on profile name). **Don't** mint a Stripe / Paddle URL inside the renderer — provider URL construction is server-side only (the entire reason the abstraction exists, see Server/CLAUDE.md §4).
**Voice-to-text in the chat composers** — the mic button next to the "+" attach button streams mic audio (renderer `getUserMedia` + AudioWorklet → 16 kHz PCM) over a WebSocket to the Orkas Server's `/voice/asr_ws` proxy (VolcEngine ASR). Renderer-side in `modules/voice-input.js`; the WS URL comes from the `voice.asrWsUrl` IPC handler, which resolves the same Server base as `features/account/server.ts::accountApiBase()` (`orkas.ai` prod; `ORKAS_VOICE_API_BASE` / `ORKAS_API_BASE_URL` override) and **requires login** — it reads `user_id`+`session_id` from the account session (in main) and appends them as a query pair (a browser `WebSocket` can't set an Authorization header); no session → the handler returns `{ok:false, error:'E_NOT_LOGGED_IN'}` and `voice-input.js` shows `chat.mic_login_required`. Mic access needs the renderer permission gate in `index.ts` (`setPermissionRequestHandler` grants `media`) plus `build.mac.extendInfo.NSMicrophoneUsageDescription` so packaged macOS shows the OS prompt. **Server-dependent → stripped from the OrkasOpen build** (offline client, no Server): `modules/voice-input.js`, the mic-button markup + `<script>` line in `index.html`, the `.chat-mic-btn` CSS, the `chat.mic_*` i18n keys, the `voice` namespace in `preload.js`, the `voice.asrWsUrl` handler in `ipc/index.ts` — single-sourced in `OpenSource/SyncCode/strip-rules.json`. (The permission gate + Info.plist key stay — they're feature-agnostic and a no-op without the mic button.)
@@ -219,15 +219,6 @@ 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.
@@ -346,24 +337,25 @@ 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). 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).
+- 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.
- `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`.
-- Process-info-row icons use only Unicode Geometric Shapes (`▶ ● ◆ ◇ ■ ▣ ▷ ◐ ◉ ○ ◯ ▪`); **no colored emoji**.
+- 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`.
- The UI shares one set of classes (`.btn / .btn-sm / .btn-primary / .btn-danger / .detail-actions / .empty / .muted`); differences are expressed via `.is-*` modifiers; **don't open near-duplicate classes**.
- **Inventory lists sort A→Z by display name**: any UI list of user-named entities the user scans by name (agents / skills / project bindings + candidate pickers / similar future inventories) defaults to A→Z using `(a.name || a.id || '').localeCompare(other, undefined, { sensitivity: 'base', numeric: true })` — case + diacritics fold, `Item 2` precedes `Item 10`, zh + en mix sorts under default locale collation. **Why:** insertion / mtime order isn't a stable mental model for a name-lookup UI — re-renders shuffle it and users report "很乱" the moment a list grows past a screen. **Exempt** lists where the ordering IS the signal: conversation sidebar (last_active_at desc), project sidebar (created_at desc), search results (score desc), plan rail (step index asc), KB tree (path hierarchy), agent / skill picker fuzzy-search results (match-quality desc — see `agents.js::_renderAgentPickerList`).
- **IME composition guard on Enter / Arrow shortcuts**: every keydown handler on an `<input>` / `<textarea>` that triggers an action (Enter→submit / search-jump / form-confirm; Arrow→list selection) **must early-return when `e.isComposing || e.keyCode === 229`**. **Why:** Chinese / Japanese / Korean IMEs use Enter to commit a composition candidate; without this guard, "Enter to confirm an English candidate when the primary suggestion is already English" silently fires the action and the user navigates away mid-typing. We've already hit this on the global search overlay; the chat input (`modules/conversation.js`) and the new-chat input (`modules/state.js`) had it from the start, the search input was missing it. Pattern to copy: `if (e.isComposing || e.keyCode === 229) return;` at the top of the handler. The `keyCode === 229` arm covers older Electron / Safari builds where `isComposing` is occasionally inaccurate.
- **Network / long-running actions MUST show a loading affordance**: any user-initiated action that triggers a network round-trip, file IO, or any other operation that can run > ~100 ms (install / uninstall / upload / delete / publish / sync trigger / detail fetch / list fetch) **must surface progress**. **Prefer non-blocking inline loading** over modal blocking: (a) inline spinner inside the trigger button (`.marketplace-btn-spinner` pattern — see `marketplace.js::_mpRenderDetail`) + replace the label with `…ing`, (b) a thin status banner above the affected area (`marketplace.js::_mpUpdateReconcileBanner` pattern), or (c) skeleton / spinner inside the panel body (`.marketplace-detail-loading` — also used by the listing grid on cold open). **Modal blocking overlay is the last resort** — only when the action invalidates other UI surfaces or the user can't safely interact with anything else mid-flight (publish-upload uses one; everything else stays inline). **Why:** without a loading affordance the user can't tell "click registered" from "request hanging" — they click again, fire duplicate requests, or assume failure and abandon the task. Failed actions surface via `uiAlert` after the spinner clears.
- **Stale-while-revalidate (SWR) for read-heavy network data**: any data that's (a) fetched on every panel open / view enter, (b) tolerant of being seconds-to-minutes out of date, and (c) likely to be re-rendered before the user notices drift (marketplace listings / categories / future "public catalog" panels) **must follow the SWR pattern**, NOT fire-on-every-open: **(1) render from cache immediately** (no blank loading flash when cache exists), **(2) check freshness against a TTL** (in-memory `ts` per entry), **(3) skip the network fetch entirely when within TTL**; outside TTL, fire a background fetch and update both the in-memory cache and (when applicable) a persisted file under `<uid>/local/cache/<bucket>/`. The reference implementation is `marketplace.js::_mpLoadListings` + `marketplace_cache.ts::{get,set}ListingsCache`; TTL there is **10 minutes** (`MP_LISTINGS_TTL_MS`). Pick TTL by data churn: high churn (download counts, online status) → 1-5min; low churn (categories, taxonomy) → 1-24h. **Why:** the previous "fetch every open" behavior hit the server N times per session even when the user just toggled views; SWR cuts traffic by ~one order of magnitude without the user noticing staleness in practice, and the persisted layer kills the cold-start blank flash. **Loading affordance still applies** — on a true cold miss (no cache) the body shows the spinner described above; on a cache hit subsequent background fetches are silent (the cached items already render, no spinner needed).
-### i18n (zh / en)
+### i18n
-Strings live in `src/{renderer,main}/locales/{zh,en}.json`; lookup goes through `i18n.{js,ts}::t(key, vars?)` (flat dot-separated keys, fallback `en` → raw key on miss). Language preference is stored in `<uid>/cloud/config/preferences.json`; runtime switches dispatch the `i18n-change` event.
+Strings live in `src/{renderer,main}/locales/*.json`; supported UI languages are registered in `src/main/i18n.ts` and mirrored by the renderer i18n module. Lookup goes through `i18n.{js,ts}::t(key, vars?)` (flat dot-separated keys, fallback chain → raw key on miss). Language preference is stored in `<uid>/cloud/config/preferences.json`; runtime switches dispatch the `i18n-change` event.
**Hard requirements**:
-- All user-visible strings (button / title / status / placeholder / tooltip / empty state / toast / dialog) **must go through i18n** with both zh and en keys.
+- All user-visible strings (button / title / status / placeholder / tooltip / empty state / toast / dialog) **must go through i18n** with keys for every supported UI language, or an explicit fallback plan while translation is in progress.
- Static HTML uses `data-i18n*` (`applyDomI18n()` auto-fills); **JS-injected text must subscribe to `i18n-change` and re-render** — common misses: sidebar lists / settings dynamic rows / status-toggle buttons.
- Decide the i18n key first, then write the code; **no hard-coded Chinese with "I'll backfill later"**.
+- Agent / skill descriptions remain `description_zh` / `description_en`; Chinese UI uses `description_zh`, every other UI language uses `description_en` with cross-fallback only when the preferred side is empty.
- **Not i18n-ed**: LLM prompts (`prompts/*.md` — the source language IS the prompt), logs, telemetry event names, user content.
---
@@ -496,7 +488,6 @@ 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). New signal kinds extend the extractor registry; never spread emit calls across `features/*`.
---
diff --git a/bin/gcal-mcp-server.cjs b/bin/gcal-mcp-server.cjs
index 94143658..0bf4b8c3 100644
--- a/bin/gcal-mcp-server.cjs
+++ b/bin/gcal-mcp-server.cjs
@@ -358,7 +358,11 @@ async function main() {
await server.connect(new StdioServerTransport());
}
-main().catch((err) => {
- process.stderr.write(`gcal-mcp-server fatal: ${err && err.message || err}\n`);
- process.exit(1);
-});
+module.exports = { TOOLS, callTool };
+
+if (require.main === module) {
+ main().catch((err) => {
+ process.stderr.write(`gcal-mcp-server fatal: ${err && err.message || err}\n`);
+ process.exit(1);
+ });
+}
diff --git a/bin/gdocs-mcp-server.cjs b/bin/gdocs-mcp-server.cjs
index 31ff5dda..897465b4 100644
--- a/bin/gdocs-mcp-server.cjs
+++ b/bin/gdocs-mcp-server.cjs
@@ -257,7 +257,11 @@ async function main() {
await server.connect(new StdioServerTransport());
}
-main().catch((err) => {
- process.stderr.write(`gdocs-mcp-server fatal: ${err && err.message || err}\n`);
- process.exit(1);
-});
+module.exports = { TOOLS, callTool };
+
+if (require.main === module) {
+ main().catch((err) => {
+ process.stderr.write(`gdocs-mcp-server fatal: ${err && err.message || err}\n`);
+ process.exit(1);
+ });
+}
diff --git a/bin/gmail-mcp-server.cjs b/bin/gmail-mcp-server.cjs
index 031c09c6..601550ac 100644
--- a/bin/gmail-mcp-server.cjs
+++ b/bin/gmail-mcp-server.cjs
@@ -652,8 +652,12 @@ async function main() {
await server.connect(transport);
}
-main().catch((err) => {
- // Last-resort log to stderr; PC's main process tails this when diagnosing spawn failures.
- process.stderr.write(`gmail-mcp-server fatal: ${err && err.message || err}\n`);
- process.exit(1);
-});
+module.exports = { TOOLS, callTool };
+
+if (require.main === module) {
+ main().catch((err) => {
+ // Last-resort log to stderr; PC's main process tails this when diagnosing spawn failures.
+ process.stderr.write(`gmail-mcp-server fatal: ${err && err.message || err}\n`);
+ process.exit(1);
+ });
+}
diff --git a/bin/google-workspace-mcp-server.cjs b/bin/google-workspace-mcp-server.cjs
new file mode 100644
index 00000000..6085f1a9
--- /dev/null
+++ b/bin/google-workspace-mcp-server.cjs
@@ -0,0 +1,69 @@
+#!/usr/bin/env node
+// Google Workspace MCP server (stdio). This is the independent one-click connector: one OAuth
+// grant with the union of Google Workspace scopes, one connector instance, and one MCP process
+// exposing the Gmail / Calendar / Docs / Sheets / Tasks tools together. The five per-service
+// connectors use their own adapters and remain separate install/enable/remove states.
+
+const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
+const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
+const {
+ ListToolsRequestSchema,
+ CallToolRequestSchema,
+} = require('@modelcontextprotocol/sdk/types.js');
+
+const ADAPTERS = [
+ { label: 'Gmail', mod: require('./gmail-mcp-server.cjs') },
+ { label: 'Calendar', mod: require('./gcal-mcp-server.cjs') },
+ { label: 'Docs', mod: require('./gdocs-mcp-server.cjs') },
+ { label: 'Sheets', mod: require('./gsheets-mcp-server.cjs') },
+ { label: 'Tasks', mod: require('./gtasks-mcp-server.cjs') },
+];
+
+const ROUTES = new Map();
+const TOOLS = [];
+
+for (const { label, mod } of ADAPTERS) {
+ for (const tool of mod.TOOLS || []) {
+ if (ROUTES.has(tool.name)) {
+ throw new Error(`duplicate Google Workspace tool name: ${tool.name}`);
+ }
+ ROUTES.set(tool.name, mod.callTool);
+ TOOLS.push({
+ ...tool,
+ description: `[${label}] ${tool.description || ''}`,
+ });
+ }
+}
+
+async function callTool(name, args) {
+ const handler = ROUTES.get(name);
+ if (!handler) throw new Error(`Unknown tool: ${name}`);
+ return handler(name, args || {});
+}
+
+async function main() {
+ const server = new Server({ name: 'google-workspace-rest', version: '0.1.0' }, { capabilities: { tools: {} } });
+
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
+
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
+ const { name, arguments: args = {} } = req.params;
+ try {
+ const result = await callTool(name, args || {});
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: (err && err.message) || String(err) }], isError: true };
+ }
+ });
+
+ await server.connect(new StdioServerTransport());
+}
+
+module.exports = { TOOLS, callTool };
+
+if (require.main === module) {
+ main().catch((err) => {
+ process.stderr.write(`google-workspace-mcp-server fatal: ${err && err.message || err}\n`);
+ process.exit(1);
+ });
+}
diff --git a/bin/gsheets-mcp-server.cjs b/bin/gsheets-mcp-server.cjs
index 778ea1ec..3f5d432c 100644
--- a/bin/gsheets-mcp-server.cjs
+++ b/bin/gsheets-mcp-server.cjs
@@ -393,7 +393,11 @@ async function main() {
await server.connect(new StdioServerTransport());
}
-main().catch((err) => {
- process.stderr.write(`gsheets-mcp-server fatal: ${err && err.message || err}\n`);
- process.exit(1);
-});
+module.exports = { TOOLS, callTool };
+
+if (require.main === module) {
+ main().catch((err) => {
+ process.stderr.write(`gsheets-mcp-server fatal: ${err && err.message || err}\n`);
+ process.exit(1);
+ });
+}
diff --git a/bin/gtasks-mcp-server.cjs b/bin/gtasks-mcp-server.cjs
index a371100b..5c52a443 100644
--- a/bin/gtasks-mcp-server.cjs
+++ b/bin/gtasks-mcp-server.cjs
@@ -302,7 +302,11 @@ async function main() {
await server.connect(new StdioServerTransport());
}
-main().catch((err) => {
- process.stderr.write(`gtasks-mcp-server fatal: ${err && err.message || err}\n`);
- process.exit(1);
-});
+module.exports = { TOOLS, callTool };
+
+if (require.main === module) {
+ main().catch((err) => {
+ process.stderr.write(`gtasks-mcp-server fatal: ${err && err.message || err}\n`);
+ process.exit(1);
+ });
+}
diff --git a/package-lock.json b/package-lock.json
index b3cb08f7..6c6e181a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -3635,6 +3635,19 @@
"version": "1.0.1",
"license": "BSD-3-Clause"
},
+ "node_modules/builder-util-runtime": {
+ "version": "9.5.1",
+ "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.5.1.tgz",
+ "integrity": "sha512-qt41tMfgHTllhResqM5DcnHyDIWNgzHvuY2jDcYP9iaGpkWxTUzV6GQjDeLnlR1/DtdlcsWQbA7sByMpmJFTLQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.3.4",
+ "sax": "^1.2.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -4180,6 +4193,63 @@
"engines": {
"node": ">= 14"
}
+ },
+ "version": "6.8.3",
+ "integrity": "sha512-Z6sgw3jgbikWKXei1ENdqFOxBP0WlXg3TtKfz0rgw2vIZFJUyI4pD7ZN7jrkm7EoMK+tcm/qTnPUdqfZukBlBQ==",
+ "license": "MIT",
+ "dependencies": {
+ "builder-util-runtime": "9.5.1",
+ "fs-extra": "^10.1.0",
+ "js-yaml": "^4.1.0",
+ "lazy-val": "^1.0.5",
+ "lodash.escaperegexp": "^4.1.2",
+ "lodash.isequal": "^4.5.0",
+ "semver": "~7.7.3",
+ "tiny-typed-emitter": "^2.1.0"
+ }
+ },
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
+ "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^6.0.1",
+ "universalify": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "version": "6.2.1",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
+ "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
+ "license": "MIT",
+ "dependencies": {
+ "universalify": "^2.0.0"
+ },
+ "optionalDependencies": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "version": "7.7.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
+ "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10.0.0"
+ }
},
"node_modules/electron/node_modules/@types/node": {
"version": "20.19.39",
@@ -5129,7 +5199,6 @@
},
"node_modules/graceful-fs": {
"version": "4.2.11",
- "dev": true,
"license": "ISC"
},
"node_modules/har-schema": {
@@ -5477,6 +5546,24 @@
"integrity": "sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==",
"license": "BSD-3-Clause"
},
+ "node_modules/js-yaml": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
+ "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
+ "license": "MIT",
+ "dependencies": {
+ "argparse": "^2.0.1"
+ },
+ "bin": {
+ "js-yaml": "bin/js-yaml.js"
+ }
+ },
+ "node_modules/js-yaml/node_modules/argparse": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
+ "license": "Python-2.0"
+ },
"node_modules/jsbn": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz",
@@ -5620,6 +5707,12 @@
"json-buffer": "3.0.1"
}
},
+ "node_modules/lazy-val": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/lazy-val/-/lazy-val-1.0.5.tgz",
+ "integrity": "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==",
+ "license": "MIT"
+ },
"node_modules/lie": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
@@ -5903,6 +5996,19 @@
"node": ">=6"
}
},
+ "node_modules/lodash.escaperegexp": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz",
+ "integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isequal": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
+ "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==",
+ "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.",
+ "license": "MIT"
+ },
"node_modules/long": {
"version": "5.3.2",
"license": "Apache-2.0"
@@ -7606,6 +7712,12 @@
"node": ">=10"
}
},
+ "node_modules/tiny-typed-emitter": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/tiny-typed-emitter/-/tiny-typed-emitter-2.1.0.tgz",
+ "integrity": "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==",
+ "license": "MIT"
+ },
"node_modules/tinybench": {
"version": "2.9.0",
"dev": true,
diff --git a/package.json b/package.json
index 61f0ce6f..d1cb43ec 100644
--- a/package.json
+++ b/package.json
@@ -24,7 +24,12 @@
"pack": "electron-builder --dir",
"dist": "electron-builder",
"dist:mac": "electron-builder --mac",
- "dist:win": "electron-builder --win"
+ "dist:win": "electron-builder --win",
+ "release:bump-version": "node scripts/release-desktop/bump-version.mjs",
+ "release:desktop:sh": "bash scripts/release-desktop/release.sh",
+ "release:desktop": "node scripts/release-desktop/release.mjs",
+ "release:upload-feed": "node scripts/release-desktop/upload-feed.mjs",
+ "release:verify-feed": "node scripts/release-desktop/verify-feed.mjs"
},
"devDependencies": {
"@types/adm-zip": "^0.5.7",
@@ -113,7 +118,6 @@
"afterPack": "scripts/codesign-adhoc.cjs",
"mac": {
"category": "public.app-category.productivity",
- "identity": null,
"target": [
{
"target": "dmg",
@@ -121,6 +125,13 @@
"arm64",
"x64"
]
+ },
+ {
+ "target": "zip",
+ "arch": [
+ "arm64",
+ "x64"
+ ]
}
],
"icon": "src/resources/icons/icon.icns"
diff --git a/scripts/codesign-adhoc.cjs b/scripts/codesign-adhoc.cjs
index 7183ac5a..fcc4657b 100644
--- a/scripts/codesign-adhoc.cjs
+++ b/scripts/codesign-adhoc.cjs
@@ -15,6 +15,10 @@ const path = require('node:path');
module.exports = async function afterPack(context) {
if (context.electronPlatformName !== 'darwin') return;
+ if (process.env.CSC_LINK || process.env.CSC_NAME) {
+ console.log('[codesign-adhoc] formal signing env detected; skipping ad-hoc signing');
+ return;
+ }
const appName = context.packager.appInfo.productFilename;
const appPath = path.join(context.appOutDir, `${appName}.app`);
console.log(`[codesign-adhoc] signing ${appPath}`);
diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs
index ac249743..1f80eeca 100644
--- a/scripts/run-tests.mjs
+++ b/scripts/run-tests.mjs
@@ -24,10 +24,18 @@ import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const swapScript = resolve(here, 'swap-sqlite-abi.mjs');
+function describeResult(result) {
+ const parts = [];
+ if (typeof result.status === 'number') parts.push(`exit ${result.status}`);
+ if (result.signal) parts.push(`signal ${result.signal}`);
+ if (result.error) parts.push(`error ${result.error.message}`);
+ return parts.join(', ') || 'unknown termination';
+}
+
function swap(mode) {
const r = spawnSync(process.execPath, [swapScript, mode], { stdio: 'inherit' });
if (r.status !== 0) {
- console.error(`[run-tests] ABI swap to ${mode} failed (exit ${r.status}).`);
+ console.error(`[run-tests] ABI swap to ${mode} failed (${describeResult(r)}).`);
if (mode === 'electron') {
console.error('[run-tests] Recover manually: npm run rebuild:sqlite:electron');
}
diff --git a/scripts/swap-sqlite-abi.mjs b/scripts/swap-sqlite-abi.mjs
index 41b30104..12da8def 100644
--- a/scripts/swap-sqlite-abi.mjs
+++ b/scripts/swap-sqlite-abi.mjs
@@ -38,22 +38,60 @@ if (mode !== 'electron' && mode !== 'node') {
const prebuildInstallBin = require_.resolve('prebuild-install/bin.js');
const sqliteDir = resolve(pcRoot, 'node_modules', 'better-sqlite3');
+const nativeAddon = resolve(sqliteDir, 'build', 'Release', 'better_sqlite3.node');
-// Fast-path: when target is `node`, the swap script itself runs under Node,
-// so a successful `require()` of the .node file proves it already matches
-// current Node's ABI — no need to invoke prebuild-install. Saves 1-2s on
-// repeat runs and dodges environments where spawning a grandchild Node
-// process is blocked (e.g. sandboxed shells that SIGKILL nested execve).
-//
-// `electron` mode has no symmetric check (current process is Node, can't
-// verify Electron ABI without spawning Electron-as-Node) — fall through.
-if (mode === 'node') {
- try {
- require_(resolve(sqliteDir, 'build', 'Release', 'better_sqlite3.node'));
- process.exit(0);
- } catch {
- /* mismatch / missing → run prebuild-install below */
+function describeResult(result) {
+ const parts = [];
+ if (typeof result.status === 'number') parts.push(`exit ${result.status}`);
+ if (result.signal) parts.push(`signal ${result.signal}`);
+ if (result.error) parts.push(`error ${result.error.message}`);
+ return parts.join(', ') || 'unknown termination';
+}
+
+function firstUsefulLine(text) {
+ return String(text || '').split(/\r?\n/).map((s) => s.trim()).find(Boolean) || '';
+}
+
+function probeAbi(targetMode, { quiet = false } = {}) {
+ const requireSnippet = `require(${JSON.stringify(nativeAddon)})`;
+ const args = targetMode === 'electron'
+ ? [require_.resolve('electron/cli.js'), '-e', requireSnippet]
+ : ['-e', requireSnippet];
+ const result = spawnSync(process.execPath, args, {
+ cwd: pcRoot,
+ encoding: 'utf8',
+ stdio: 'pipe',
+ env: targetMode === 'electron'
+ ? { ...process.env, ELECTRON_RUN_AS_NODE: '1' }
+ : process.env,
+ });
+ if (result.status === 0) return true;
+ if (!quiet) {
+ const detail = describeResult(result);
+ const reason = firstUsefulLine(result.stderr) || firstUsefulLine(result.stdout);
+ console.error(`[swap-sqlite-abi] ${targetMode} ABI probe failed (${detail})${reason ? `: ${reason}` : ''}`);
}
+ return false;
+}
+
+function rebuildNodeFromSource() {
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
+ return spawnSync(npm, ['rebuild', 'better-sqlite3'], {
+ cwd: pcRoot,
+ stdio: 'inherit',
+ env: {
+ ...process.env,
+ npm_config_build_from_source: 'better-sqlite3',
+ },
+ });
+}
+
+// Fast-path: probe the target runtime before touching the binary. Probe in a
+// child process instead of `require()`ing in this process: a bad native addon
+// can be killed by the OS before JS can catch an exception, and the wrapper
+// would only see `exit null`.
+if (probeAbi(mode, { quiet: true })) {
+ process.exit(0);
}
const args = [prebuildInstallBin];
@@ -76,7 +114,23 @@ const result = spawnSync(process.execPath, args, {
stdio: 'inherit',
});
-if (result.status !== 0) {
- console.error(`[swap-sqlite-abi] prebuild-install exited with ${result.status}`);
- process.exit(result.status ?? 1);
+// Some local environments have killed `prebuild-install` after the tarball was
+// already unpacked. Treat the post-install ABI probe as authoritative.
+if (probeAbi(mode, { quiet: true })) {
+ process.exit(0);
+}
+
+if (mode === 'node') {
+ console.error(`[swap-sqlite-abi] prebuild-install did not produce a loadable node ABI (${describeResult(result)}); rebuilding better-sqlite3 from source...`);
+ const rebuild = rebuildNodeFromSource();
+ if (probeAbi('node', { quiet: true })) {
+ process.exit(0);
+ }
+ console.error(`[swap-sqlite-abi] source rebuild did not produce a loadable node ABI (${describeResult(rebuild)})`);
+ probeAbi('node');
+ process.exit(rebuild.status ?? result.status ?? 1);
}
+
+console.error(`[swap-sqlite-abi] prebuild-install did not produce a loadable ${mode} ABI (${describeResult(result)})`);
+probeAbi(mode);
+process.exit(result.status ?? 1);
diff --git a/scripts/watch-signals.sh b/scripts/watch-signals.sh
deleted file mode 100755
index b698f6ff..00000000
--- a/scripts/watch-signals.sh
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/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 f88b9bb0..3b6992c5 100644
--- a/src/core-agent/src/agent/runner.ts
+++ b/src/core-agent/src/agent/runner.ts
@@ -10,7 +10,6 @@ import {
import { createLogger } from "../shared/logger.js";
import type { CoreAgentConfig } from "../config/schema.js";
import type { EvolutionConfig } from "../evolution/types.js";
-import { detectUserCorrection } from "../evolution/metacognition.js";
import type { LLMProvider, CompletionResult } from "../providers/base.js";
import { ProviderRegistry } from "../providers/registry.js";
import type { AgentTool, ToolContext } from "../tools/base.js";
@@ -517,11 +516,6 @@ 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) {
@@ -529,8 +523,8 @@ export class AgentRunner {
return null;
}
- const metrics = this.buildRunMetrics(result, inboundMessage);
- log.debug(`evaluateReflection: metrics toolCalls=${metrics.toolCalls} errors=${metrics.errorCount} errorKind=${metrics.errorKind} transient=${metrics.transientErrorCount} corrections=${metrics.userCorrections} skills=[${metrics.skillsLoaded.join(',')}]`);
+ const 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 reflection = shouldReflect(metrics, metaConfig, competence);
if (!reflection.shouldReflect) {
@@ -629,11 +623,8 @@ export class AgentRunner {
return lines.join('\n');
}
- /** Convert AgentRunResult.meta into RunMetrics for the trigger evaluator.
- * When `inboundMessage` is provided, runs `detectUserCorrection` to set
- * `userCorrections` (otherwise 0). Reuses the same heuristic the bus-side
- * expert_signals extractor uses — same input, same boolean. */
- private buildRunMetrics(result: AgentRunResult, inboundMessage?: string): RunMetrics {
+ /** Convert AgentRunResult.meta into RunMetrics for the trigger evaluator. */
+ private buildRunMetrics(result: AgentRunResult): RunMetrics {
const meta = result.meta;
const transient = meta.transientToolErrors ?? 0;
const permanent = meta.permanentToolErrors ?? 0;
@@ -654,7 +645,7 @@ export class AgentRunner {
hadErrors,
recovered: hadErrors && result.text.length > 0,
errorCount: totalToolErrors + (meta.error ? 1 : 0),
- userCorrections: inboundMessage && detectUserCorrection(inboundMessage) ? 1 : 0,
+ userCorrections: 0,
errorKind,
transientErrorCount: transient,
};
diff --git a/src/core-agent/src/skills/loader.ts b/src/core-agent/src/skills/loader.ts
index 9e930c8e..021aa0b4 100644
--- a/src/core-agent/src/skills/loader.ts
+++ b/src/core-agent/src/skills/loader.ts
@@ -75,7 +75,8 @@ export class SkillLoader {
* splicing into a system prompt so the LLM knows what skills exist and
* when to reach for each one. Returns empty string if no skills.
*
- * `lang` selects which description (zh / en) is rendered; falls back per
+ * `lang` selects which description is rendered; unsupported description
+ * locales use English first, then fall back per
* `pickDescription`. Defaults to `'en'` for safety in non-UI callers.
*/
// Default convenience renderer for hosts without their own block builder.
@@ -87,7 +88,7 @@ export class SkillLoader {
// need to consult a separate path-constants section. Other hosts may use
// this default helper, in which case Source is taken from the dirs[]
// basename.
- renderSystemPromptBlock(lang: 'zh' | 'en' = 'en'): string {
+ renderSystemPromptBlock(lang: string = 'en'): string {
const skills = this.list();
if (!skills.length) return "";
const lines = ["## Available skills (skills)", ""];
diff --git a/src/core-agent/src/skills/types.ts b/src/core-agent/src/skills/types.ts
index 15b711f7..12d04699 100644
--- a/src/core-agent/src/skills/types.ts
+++ b/src/core-agent/src/skills/types.ts
@@ -27,22 +27,27 @@ export interface SkillSpec {
source: string;
}
+function descriptionLocale(lang: string): 'zh' | 'en' {
+ return String(lang || '').split(/[-_]/)[0] === 'zh' ? 'zh' : 'en';
+}
+
/** Pick a description for a target language with cross-language fallback.
*
- * `lang === 'zh'`: `description_zh` || `description_en` || `''`. Mirror for
- * `'en'`. Cross-fallback guarantees non-empty when any description exists,
- * so the user never sees a blank entry just because the matching locale
- * hasn't been filled. Loader migrates legacy single-`description` files
- * into one of the two slots at parse time — nothing else needs to look at
- * the legacy field. */
+ * Description storage is intentionally zh/en only: non-Chinese UI languages
+ * use English first. Cross-fallback guarantees non-empty when any description
+ * exists, so the user never sees a blank entry just because the matching
+ * locale hasn't been filled. Loader migrates legacy single-`description`
+ * files into one of the two slots at parse time. */
export function pickDescription(
spec: { description_zh?: string; description_en?: string },
- lang: 'zh' | 'en',
+ lang: string,
): string {
- const zh = (spec.description_zh || '').trim();
- const en = (spec.description_en || '').trim();
- if (lang === 'zh') return zh || en || '';
- return en || zh || '';
+ const primaryLocale = descriptionLocale(lang);
+ const primary = spec[`description_${primaryLocale}`];
+ if (primary && primary.trim()) return primary.trim();
+ const fallbackLocale = ({ zh: 'en', en: 'zh' } as const)[primaryLocale];
+ const fallback = spec[`description_${fallbackLocale}`];
+ return (fallback || '').trim();
}
/** Input to `SkillLoader`. */
diff --git a/src/core-agent/src/tools/web-fetch.ts b/src/core-agent/src/tools/web-fetch.ts
index dc917a6c..9cfee351 100644
--- a/src/core-agent/src/tools/web-fetch.ts
+++ b/src/core-agent/src/tools/web-fetch.ts
@@ -13,6 +13,10 @@ const MAX_RESPONSE_BYTES = 2_000_000;
const USER_AGENT =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36";
+function acceptLanguage(): string {
+ return process.env.ORKAS_ACCEPT_LANGUAGE || "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7";
+}
+
/**
* Pick the charset for decoding raw response bytes.
*
@@ -146,7 +150,7 @@ export const webFetchTool: AgentTool = defineTool({
headers: {
"User-Agent": USER_AGENT,
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
- "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
+ "Accept-Language": acceptLanguage(),
},
signal: controller.signal,
redirect: "follow",
diff --git a/src/core-agent/src/tools/web-search.ts b/src/core-agent/src/tools/web-search.ts
index 357d368b..83afea3e 100644
--- a/src/core-agent/src/tools/web-search.ts
+++ b/src/core-agent/src/tools/web-search.ts
@@ -33,6 +33,10 @@ const MAX_COUNT = 20;
const USER_AGENT =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36";
+function acceptLanguage(): string {
+ return process.env.ORKAS_ACCEPT_LANGUAGE || "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7";
+}
+
export type SearchProvider = "brave" | "bing";
type SearchResult = {
@@ -290,7 +294,7 @@ async function runProviderSearch(
headers: {
"User-Agent": USER_AGENT,
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
- "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
+ "Accept-Language": acceptLanguage(),
},
signal: controller.signal,
redirect: "follow",
diff --git a/src/main/features/agents.ts b/src/main/features/agents.ts
index 8b0da639..8fb1f691 100644
--- a/src/main/features/agents.ts
+++ b/src/main/features/agents.ts
@@ -140,21 +140,6 @@ 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;
@@ -192,20 +177,8 @@ 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' }
@@ -264,12 +237,12 @@ const INPUT_ID_RE = /^[a-z_][a-z0-9_]{0,31}$/;
const ALLOWED_INPUT_TYPES: readonly AgentInputType[] = ['text', 'textarea', 'select', 'multiselect', 'number', 'boolean', 'file', 'directory'];
// Reserved agent display names — collide with the commander role surfaced in
-// the chat-recipient chip and the sidebar tab (Chinese localizations are
-// "指挥官" and "总指挥" respectively). The bus router also keys "commander"
-// as a member id, so we guard the English form too. Comparison is
-// case-insensitive after stripping all whitespace, so " Commander " or
-// the spaced Chinese form "总 指挥" all resolve to the same canonical key.
-const RESERVED_AGENT_NAMES = new Set(['指挥官', '总指挥', 'commander']);
+// the chat-recipient chip and the sidebar tab. The bus router also keys
+// "commander" as a member id, so we guard localized display names and the
+// English form. Comparison is case-insensitive after stripping all whitespace,
+// so " Commander " or the spaced Chinese form "总 指挥" all resolve to the
+// same canonical key.
+const RESERVED_AGENT_NAMES = new Set(['指挥官', '总指挥', 'コマンダー', '司令官', 'commander']);
function _agentNameKey(name: string): string {
return String(name || '').replace(/\s+/g, '').toLowerCase();
}
@@ -529,12 +502,6 @@ 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;
}
@@ -723,11 +690,6 @@ export interface CreateAgentOptions {
/** Marketplace category code (e.g. `education`). Empty string / omitted = uncategorized;
* required only at marketplace publish time. */
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.
@@ -750,12 +712,12 @@ function resolveBilingualDescription(
}
/**
- * Create a blank custom agent. Initial fields are optional — the user typically
- * enters the edit page right after creation and fills them in via chat or
- * manual edit. Returns the created agent.
+ * 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, output_format }: CreateAgentOptions = {},
+ { name = '', description = '', description_zh, description_en, workflow = '', icon, color, interactive, runtime, category }: CreateAgentOptions = {},
): Promise<Agent | null> {
assertAgentNameAllowed(name);
await assertAgentNameUnique(String(name || '').trim());
@@ -783,13 +745,6 @@ export async function createCustomAgent(
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.
@@ -892,12 +847,6 @@ 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;
}
/**
@@ -1054,16 +1003,6 @@ 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;
diff --git a/src/main/features/config.ts b/src/main/features/config.ts
index f38b86d6..0fad2596 100644
--- a/src/main/features/config.ts
+++ b/src/main/features/config.ts
@@ -2,7 +2,7 @@
* User preferences bag — `<uid>/cloud/config/preferences.json`.
*
* Cross-device user preferences (cloud-synced). Currently stores the
- * UI language only (`language: 'zh' | 'en'`).
+ * UI language only (`language` from i18n.SUPPORTED_LANGS).
*
* History: the old `data/config/config.json` also held legacy
* `provider` / `model` fields (the default model pair written by
@@ -45,6 +45,8 @@ export interface UserPreferences {
* `ORKAS_METACOGNITION='0'` remains a higher-priority kill switch.
* Reads go through `features/metacognition.isFeatureEnabled`. */
metacognition_enabled?: boolean;
+ /** Desktop auto-update toggle. Defaults to enabled so signed release
+ * builds check the stable feed and download available updates. */
[key: string]: unknown;
}
@@ -148,6 +150,18 @@ export function setMetacognitionEnabled(enabled: boolean): boolean {
return !!enabled;
}
+// ── Desktop auto-update ─────────────────────────────────────────────────
+// Defaults to ON. Packaged app support is handled by features/app_update.ts;
+// this preference only captures the user's intent.
+
+export function getAutoUpdateEnabled(): boolean {
+ return v !== false;
+}
+
+export function setAutoUpdateEnabled(enabled: boolean): boolean {
+ return !!enabled;
+}
+
/** Production wrapper: reads the system locale from Electron's `app`. */
export function initLanguageFromApp(): Lang {
let locale = '';
diff --git a/src/main/features/connectors/catalog-google.ts b/src/main/features/connectors/catalog-google.ts
index afb1a6b7..e919cfce 100644
--- a/src/main/features/connectors/catalog-google.ts
+++ b/src/main/features/connectors/catalog-google.ts
@@ -6,22 +6,24 @@
* `OpenSource/SyncCode/strip-rules.json` `forbidden_files`).
*
* Includes:
- * - `google-workspace` (UI-only bundle; `bundle_member_ids` fans out OAuth to all 5)
- * - `gmail`, `gcal`, `gdocs`, `gsheets`, `gtasks` (the 5 member entries, each backed by a
- * local stdio adapter under `PC/bin/`)
+ * - `google-workspace` (one independent all-in-one connector backed by
+ * `bin/google-workspace-mcp-server.cjs`)
+ * - `gmail`, `gcal`, `gdocs`, `gsheets`, `gtasks` (5 independent per-service connectors,
+ * each backed by a local stdio adapter under `PC/bin/`)
*
- * Adding a new Google service: drop a new entry here + `bin/<svc>-mcp-server.cjs` adapter +
- * Server's `_SCOPES_BY_CATALOG_ID` row, and union the scope into `google-workspace`'s
- * member list if you want it covered by the bundle's single consent.
+ * Adding a new Google service: drop a new entry here + `bin/<svc>-mcp-server.cjs` adapter,
+ * Server's `_SCOPES_BY_CATALOG_ID` row, and wire the adapter into
+ * `bin/google-workspace-mcp-server.cjs` if you want it covered by the all-in-one connector.
*/
import type { CatalogEntry } from './types';
export const GOOGLE_ENTRIES: CatalogEntry[] = [
// ── Google Workspace ────────────────────────────────────────────────────
- // One UI bundle (`google-workspace`) groups the 5 service entries below — a single OAuth
- // flow with `union(scopes)` provisions all 5 instances. Each member entry keeps its own
- // stdio adapter / tool surface so the model still sees 5 independent connectors with
- // service-specific tool names. Bypasses Google's MCP wrapper service
+ // Optional one-click suite (`google-workspace`) requests the union of the 5 service scopes and
+ // exposes all tools through one independent connector instance. The individual service entries
+ // are also shown so users can grant only the Google product they need. There is intentionally
+ // no state sync between the suite card and the 5 single-service cards. Bypasses Google's MCP
+ // wrapper service
// (`gmailmcp.googleapis.com`) which is in Developer Preview with a project-level allowlist
// that third-party OAuth clients can't reach. See `bin/gmail-mcp-server.cjs` header for
// rationale and PC/CLAUDE.md §6.5.
@@ -30,13 +32,16 @@ export const GOOGLE_ENTRIES: CatalogEntry[] = [
display_name: 'Google Workspace',
icon_svg: '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#4285f4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34a853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#fbbc05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#ea4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>',
category: 'productivity',
- description_zh: 'Gmail / Google 日历 / Google 文档 / Google 表格 / Google 任务 — 一次授权,5 项服务一起接入。',
- description_en: 'Gmail / Google Calendar / Google Docs / Google Sheets / Google Tasks — one consent, all 5 services connected.',
+ description_zh: '一次授权接入 Gmail、日历、文档、表格和任务;也可以单独连接各项服务。',
+ description_en: 'Connect Gmail, Calendar, Docs, Sheets, and Tasks in one consent; individual services can also be connected separately.',
auth_mode: 'server_bridge',
oauth: { provider_id: 'google' },
- // Bundle: no transport of its own; OAuth fans out to the 5 member instances below.
- transport_template: null,
- bundle_member_ids: ['gmail', 'gcal', 'gdocs', 'gsheets', 'gtasks'],
+ transport_template: {
+ kind: 'stdio',
+ command: '${ORKAS_NODE}',
+ args: ['${ORKAS_PC_DIR}/bin/google-workspace-mcp-server.cjs'],
+ oauth_env_key: 'GOOGLE_ACCESS_TOKEN',
+ },
},
{
id: 'gmail',
diff --git a/src/main/features/connectors/manager.ts b/src/main/features/connectors/manager.ts
index f290b154..9034625f 100644
--- a/src/main/features/connectors/manager.ts
+++ b/src/main/features/connectors/manager.ts
@@ -12,6 +12,8 @@
* MCP connection up. Tokens are lazily refreshed at boot / refresh-tools / reconnect; mid-call
* expiry surfaces as a tool error and the user re-clicks "刷新工具".
*/
+import * as crypto from 'node:crypto';
+
import * as registry from './registry';
import { McpConnection } from './mcp-client';
import { findCatalogEntry } from './catalog';
@@ -44,12 +46,11 @@ const REFRESH_BUFFER_MS = 5 * 60 * 1000;
function _now(): number { return Date.now(); }
function _nowIso(): string { return new Date().toISOString(); }
-/** Truncated token fingerprint for diagnostic logs — first 12 chars is enough to correlate
- * across PC + Server logs without leaking the full token. Returns 'none' for missing tokens
- * and 'null' for the literal-null fallback some refresh endpoints emit. */
+/** Non-reversible token fingerprint for diagnostic logs. Twelve SHA-256 hex chars are enough
+ * to correlate PC + Server events without leaking a usable token prefix. */
function _tokPrefix(t: string | null | undefined): string {
if (!t) return 'none';
- return t.slice(0, 12) + (t.length > 12 ? '…' : '');
+ return crypto.createHash('sha256').update(t).digest('hex').slice(0, 12);
}
/** Refresh the access_token if stale, dedupe concurrent callers, and persist the rotated grant
@@ -57,9 +58,9 @@ function _tokPrefix(t: string | null | undefined): string {
* another caller that just released the lock may have written a new grant; using the caller's
* in-memory `inst` snapshot would re-trigger an unnecessary (and stale-token-using!) refresh.
*
- * Diagnostic logging: every refresh attempt prints the RT prefix being sent so a future
+ * Diagnostic logging: every refresh attempt prints the RT fingerprint being sent so a future
* `bad_refresh_token` failure can be correlated with the exchange/refresh that originally
- * issued that RT. Rotation (old → new RT prefix) is also logged so we can verify the new
+ * issued that RT. Rotation (old → new RT fingerprint) is also logged so we can verify the new
* RT actually made it onto disk via the post-write read-back in `registry._writeSync`. */
async function _refreshGrantIfStale(uid: string, entry: CatalogEntry, instId: string): Promise<OAuthGrant> {
const existing = _refreshLocks.get(instId);
@@ -337,8 +338,8 @@ async function _provisionMemberInstance(
};
// Diagnostic: capture which RT just got issued by the provider so a later refresh failure
// can be matched against this exchange (the `_refreshGrantIfStale` logs print the same
- // _tokPrefix shape — `bad_refresh_token` mid-day means the on-disk RT no longer matches
- // what the provider has on record; correlating prefixes pinpoints whether the write here
+ // _tokPrefix fingerprint — `bad_refresh_token` mid-day means the on-disk RT no longer matches
+ // what the provider has on record; correlating fingerprints pinpoints whether the write here
// didn't land or got overwritten by another path).
log.info('provision: fresh grant from exchange', {
id: entry.id,
diff --git a/src/main/features/connectors/registry.ts b/src/main/features/connectors/registry.ts
index 68db6e4c..c584766a 100644
--- a/src/main/features/connectors/registry.ts
+++ b/src/main/features/connectors/registry.ts
@@ -30,6 +30,7 @@
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
+import * as crypto from 'node:crypto';
import { Mutex } from 'async-mutex';
import { userConnectorsConfigFile } from '../../paths';
@@ -40,7 +41,7 @@ import type { ConnectorInstance, ConnectorsFile, OAuthGrant, DcrClientCredential
const log = createLogger('connectors:registry');
const _writeMutex = new Mutex();
-const EMPTY: ConnectorsFile = { version: 1, connections: {} };
+const EMPTY: ConnectorsFile = { version: 2, connections: {} };
// On-disk shape: ConnectorInstance with all token-bearing fields collapsed into one
// vault-encrypted `secrets_enc` string. **`transport` is in the blob too** — even though it's
@@ -142,9 +143,9 @@ function _readSync(uid: string): ConnectorsFile {
if (code !== 'ENOENT') {
log.warn('reading connectors.json failed', { error: (err as Error).message });
}
- return { version: 1, connections: {} };
+ return { version: 2, connections: {} };
}
- if (!raw.trim()) return { version: 1, connections: {} };
+ if (!raw.trim()) return { version: 2, connections: {} };
// Legacy whole-file vault format: decrypt once, plaintext JSON already has oauth_grant /
// dcr_client as plain fields per instance — return as-is. Next write upgrades to per-field.
@@ -152,17 +153,17 @@ function _readSync(uid: string): ConnectorsFile {
const json = _tryDecrypt(uid, raw);
if (json === null) {
log.warn('decrypt connectors.json (legacy whole-file) failed with both seeds — treating as empty');
- return { version: 1, connections: {} };
+ return { version: 2, connections: {} };
}
try {
const obj = JSON.parse(json);
if (obj && typeof obj === 'object' && obj.connections && typeof obj.connections === 'object') {
- return { version: 1, connections: obj.connections as Record<string, ConnectorInstance> };
+ return { version: 2, connections: obj.connections as Record<string, ConnectorInstance> };
}
} catch (err) {
log.warn('parse connectors.json (legacy whole-file) failed', { error: (err as Error).message });
}
- return { version: 1, connections: {} };
+ return { version: 2, connections: {} };
}
// Current format: plaintext JSON envelope, secrets_enc per instance.
@@ -173,12 +174,12 @@ function _readSync(uid: string): ConnectorsFile {
for (const [id, disk] of Object.entries(obj.connections as Record<string, InstanceOnDisk>)) {
conns[id] = _hydrateSecrets(uid, disk);
}
- return { version: 1, connections: conns };
+ return { version: 2, connections: conns };
}
} catch (err) {
log.warn('parse connectors.json failed', { error: (err as Error).message });
}
- return { version: 1, connections: {} };
+ return { version: 2, connections: {} };
}
function _writeSync(uid: string, data: ConnectorsFile): void {
@@ -224,7 +225,7 @@ export function load(uid: string): ConnectorsFile {
function _rt(grant: ConnectorInstance['oauth_grant']): string {
const t = grant?.refresh_token;
if (!t) return 'none';
- return t.slice(0, 12) + (t.length > 12 ? '…' : '');
+ return crypto.createHash('sha256').update(t).digest('hex').slice(0, 12);
}
export async function upsert(uid: string, inst: ConnectorInstance): Promise<void> {
diff --git a/src/main/features/connectors/tools-adapter.ts b/src/main/features/connectors/tools-adapter.ts
index 40f921c9..d5738f97 100644
--- a/src/main/features/connectors/tools-adapter.ts
+++ b/src/main/features/connectors/tools-adapter.ts
@@ -50,7 +50,13 @@ export function stringifyMcpResult(raw: unknown): string {
/** Resolve the connectors visible to a given actor + the tool subset each one exposes.
* Returns one entry per visible instance; `tools` is post-`enabled_subtools` filter. Instances
* whose `tools_cache` is empty (e.g. cold-start before the first successful list_tools) are
- * still returned with `tools: []`. */
+ * still returned with `tools: []`.
+ *
+ * Google Workspace overlap: the all-in-one `google-workspace` connector intentionally coexists
+ * with the five single-service connectors. When both are visible to the current actor, the
+ * single-service connector wins for its service and the duplicate Workspace tools are hidden.
+ * This keeps the model from seeing two Gmail/Calendar/etc. routes for the same action while
+ * still letting Workspace provide any services the user did not connect separately. */
export async function resolveVisibleConnectors(
uid: string,
agentId: string | undefined,
@@ -72,13 +78,14 @@ export async function resolveVisibleConnectors(
const userEnabled = connected.filter((i) => isConnectorEnabled(uid, i.id));
if (!userEnabled.length) return [];
const scope = await _enabledInstancesForActor(uid, agentId, userEnabled);
- return scope.map((instance) => {
+ const resolved = scope.map((instance) => {
const allowed = instance.enabled_subtools;
const tools = allowed === null
? instance.tools_cache
: instance.tools_cache.filter((t) => allowed.includes(t.name));
return { instance, tools };
});
+ return _dedupeGoogleWorkspaceTools(resolved);
}
async function _enabledInstancesForActor(
@@ -93,3 +100,57 @@ async function _enabledInstancesForActor(
const allowSet = new Set(allowed);
return allInstances.filter((i) => allowSet.has(i.id));
}
+
+const GOOGLE_WORKSPACE_ID = 'google-workspace';
+type GoogleWorkspaceService = 'gmail' | 'gcal' | 'gdocs' | 'gsheets' | 'gtasks';
+
+const GOOGLE_SERVICE_BY_CONNECTOR_ID: Record<string, GoogleWorkspaceService> = {
+ gmail: 'gmail',
+ gcal: 'gcal',
+ gdocs: 'gdocs',
+ gsheets: 'gsheets',
+ gtasks: 'gtasks',
+};
+
+const GOOGLE_WORKSPACE_TOOL_PREFIX_BY_SERVICE: Record<GoogleWorkspaceService, string> = {
+ gmail: '[Gmail]',
+ gcal: '[Calendar]',
+ gdocs: '[Docs]',
+ gsheets: '[Sheets]',
+ gtasks: '[Tasks]',
+};
+
+function _dedupeGoogleWorkspaceTools(
+ visible: Array<{ instance: ConnectorInstance; tools: ToolSchema[] }>,
+): Array<{ instance: ConnectorInstance; tools: ToolSchema[] }> {
+ const workspace = visible.find((v) => v.instance.id === GOOGLE_WORKSPACE_ID);
+ if (!workspace) return visible;
+
+ const shadowedPrefixes = new Set<string>();
+ for (const { instance } of visible) {
+ const service = GOOGLE_SERVICE_BY_CONNECTOR_ID[instance.id];
+ if (!service) continue;
+ shadowedPrefixes.add(GOOGLE_WORKSPACE_TOOL_PREFIX_BY_SERVICE[service]);
+ }
+ if (!shadowedPrefixes.size) return visible;
+
+ return visible
+ .map((v) => {
+ if (v.instance.id !== GOOGLE_WORKSPACE_ID) return v;
+ return {
+ instance: v.instance,
+ tools: v.tools.filter((t) => !_hasShadowedWorkspacePrefix(t, shadowedPrefixes)),
+ };
+ })
+ // When all five single-service connectors are visible, the Workspace connector has no unique
+ // tools left to expose to the model. Hide that empty duplicate route entirely.
+ .filter((v) => v.instance.id !== GOOGLE_WORKSPACE_ID || v.tools.length > 0);
+}
+
+function _hasShadowedWorkspacePrefix(tool: ToolSchema, shadowedPrefixes: Set<string>): boolean {
+ const desc = typeof tool.description === 'string' ? tool.description.trimStart() : '';
+ for (const prefix of shadowedPrefixes) {
+ if (desc.startsWith(prefix)) return true;
+ }
+ return false;
+}
diff --git a/src/main/features/connectors/types.ts b/src/main/features/connectors/types.ts
index ed9b90a2..93088af0 100644
--- a/src/main/features/connectors/types.ts
+++ b/src/main/features/connectors/types.ts
@@ -65,7 +65,7 @@ export interface ConnectorInstance {
}
export interface ConnectorsFile {
- version: 1;
+ version: 2;
connections: Record<string, ConnectorInstance>;
}
diff --git a/src/main/features/expert_signals/extractors/event.ts b/src/main/features/expert_signals/extractors/event.ts
deleted file mode 100644
index ea70b940..00000000
--- a/src/main/features/expert_signals/extractors/event.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-/**
- * 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 } 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),
- },
- };
-}
-
-// ── 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
deleted file mode 100644
index 0f97689b..00000000
--- a/src/main/features/expert_signals/extractors/silence.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 7db407fa..00000000
--- a/src/main/features/expert_signals/extractors/text.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-/**
- * 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
deleted file mode 100644
index f48c5b5c..00000000
--- a/src/main/features/expert_signals/index.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * 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/storage.ts b/src/main/features/expert_signals/storage.ts
deleted file mode 100644
index 66598f58..00000000
--- a/src/main/features/expert_signals/storage.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-/**
- * 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
deleted file mode 100644
index 124f871b..00000000
--- a/src/main/features/expert_signals/turn_hooks.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-/**
- * 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 } from './extractors/event';
-import {
- scheduleSilenceCheck,
- cancelSilenceCheck,
-} from './extractors/silence';
-import { createLogger } from '../../logger';
-
-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}`; }
-
-/**
- * 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
deleted file mode 100644
index 7afa41da..00000000
--- a/src/main/features/expert_signals/types.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * 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
-
-/** 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]',
-} 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';
-}
-
-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;
- /** Bus turn id; signals from the same turn share this so consumers can
- * group-by to recover "the correction + edit + accept from this turn". */
- 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 93fe29d0..79101409 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -32,6 +32,7 @@ import {
} from './state';
import {
GroupMessage, appendVisible, readSlice, buildReplayPrefix,
+ type MarketplaceInstallRequest,
} from './visibility';
import {
resolveRecipients, parseMentions, buildMention,
@@ -50,7 +51,9 @@ import {
} from '../../paths';
import * as agentsFeat from '../agents';
import { isAgentEnabled } from '../component_enabled';
-import { buildLanguageDirective, t } from '../../i18n';
+import { buildLanguageDirective, descriptionLang, t } from '../../i18n';
+import * as marketplaceFeat from '../marketplace';
+import { readInstalls } from '../marketplace_installs';
const log = createLogger('group_chat.bus');
@@ -180,6 +183,15 @@ interface WorkerState {
* placeholder cleaned. Same staging pattern as pendingPlanAnnouncement +
* deferred planExecutor.reconcile, just for direct dispatches. */
pendingDispatches?: Array<{ to: string; message: string }>;
+ /** Marketplace install confirmations requested during a commander turn.
+ * The model can stage these via `marketplace_request_install`; the user
+ * decides in the renderer before any install side effect happens. */
+ pendingMarketplaceRequests?: MarketplaceInstallRequest[];
+ /** Last marketplace rows returned to the model in this turn, keyed by
+ * `${kind}:${id}`. `marketplace_request_install` uses this to carry UI
+ * metadata such as agent avatar tokens without relying on the model to
+ * copy every field back. */
+ marketplaceSearchResults?: Map<string, Partial<MarketplaceInstallRequest>>;
}
interface CidState {
@@ -318,6 +330,7 @@ export interface EnqueueParams {
* `agent_id` is the producing actor — the renderer routes a user→artifact
* interaction result back to it. */
artifacts?: Array<{ id: string; title: string; agent_id: string }>;
+ marketplace_requests?: MarketplaceInstallRequest[];
plan_announcement?: boolean;
/** Override resolved recipients (commander emitting plan announcement
* uses this to force `to=[user]`). Otherwise router decides. */
@@ -615,6 +628,9 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
...(params.created_agents && params.created_agents.length ? { created_agents: params.created_agents } : {}),
...(params.created_skills && params.created_skills.length ? { created_skills: params.created_skills } : {}),
...(params.artifacts && params.artifacts.length ? { artifacts: params.artifacts } : {}),
+ ...(params.marketplace_requests && params.marketplace_requests.length
+ ? { marketplace_requests: params.marketplace_requests }
+ : {}),
...(params.plan_announcement ? { plan_announcement: true } : {}),
...(params.dispatch ? { dispatch: true } : {}),
...(params.process && params.process.length ? { process: params.process } : {}),
@@ -921,7 +937,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, item.attachments);
+ extraTools = await buildCommanderExtraTools(state, w);
// skillList stays undefined for commander — every skill is globally
// visible (skills are NOT project-scoped this round; see CLAUDE.md §6).
} else {
@@ -1446,6 +1462,19 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
outcome = { ...outcome, text: t('chat.commander_dispatch_only', { agents: tags.join(', ') }) };
}
+ // Marketplace install requests are visible side effects of a commander
+ // turn. They are staged by `marketplace_request_install` and attached to
+ // the final message so the renderer can show user-confirmation cards. If
+ // the model followed the tool instruction and produced no prose, still
+ // persist a bubble: the card itself is the thing the user needs to see.
+ const turnMarketplaceRequests = actor.kind === 'commander' && w.pendingMarketplaceRequests?.length
+ ? w.pendingMarketplaceRequests.slice()
+ : [];
+ if (actor.kind === 'commander') w.pendingMarketplaceRequests = undefined;
+ if (turnMarketplaceRequests.length > 0 && outcome.kind === 'silent') {
+ outcome = { kind: 'persist', text: '' };
+ }
+
// Abort post-processing — single source of truth for both "promote silent
// to persist when there's still something visible to keep" AND the
// "(stopped)" suffix.
@@ -1497,6 +1526,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
...(turnArtifacts.length
? { artifacts: turnArtifacts.map((a) => ({ id: a.id, title: a.title, agent_id: actor.id })) }
: {}),
+ ...(turnMarketplaceRequests.length ? { marketplace_requests: turnMarketplaceRequests } : {}),
...(pendingPlan && actor.kind === 'commander'
? { plan_announcement: true, forceTo: [USER_ID] } : {}),
...(processItems.length ? { process: processItems } : {}),
@@ -1542,14 +1572,6 @@ 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({
@@ -1558,9 +1580,6 @@ 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}`);
@@ -1679,7 +1698,7 @@ export async function _buildAgentsIndexBlockForTest(uid: string): Promise<string
async function buildAgentsIndexBlock(uid: string, allowedIds?: readonly string[] | null): Promise<string> {
const { getCurrentLang } = await import('../../i18n');
const { pickDescription } = await import('#core-agent');
- const lang = getCurrentLang();
+ const lang = descriptionLang(getCurrentLang());
const customRoot = path.resolve(userAgentsDir(uid));
const builtinRoot = path.resolve(userMarketplaceAgentsDir(uid));
const header = [
@@ -1721,7 +1740,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; output_format?: string },
+ agent: { name?: string; description?: string; workflow?: string; agent_id: string; inputs?: unknown },
workingDir: string,
): Promise<string> {
const { prompts } = await import('../../prompts/loader');
@@ -1747,47 +1766,102 @@ 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 } {
+ return { content: JSON.stringify(data) };
+}
+
+function _toolError(error: string): { content: string; isError: true } {
+ return { content: JSON.stringify({ ok: false, error }), isError: true };
+}
+
+function _clampLimit(raw: unknown, fallback: number, min: number, max: number): number {
+ const n = Number(raw);
+ if (!Number.isFinite(n)) return fallback;
+ return Math.max(min, Math.min(max, Math.floor(n)));
+}
+
+function _trimText(raw: unknown, max = 2000): string {
+ const s = typeof raw === 'string' ? raw.trim() : '';
+ return s.length > max ? s.slice(0, max) : s;
+}
+
+function _normaliseMarketplaceKind(raw: unknown, allowBoth = false): 'agent' | 'skill' | 'both' | null {
+ const v = String(raw || (allowBoth ? 'both' : '')).trim().toLowerCase();
+ if (v === 'agent' || v === 'skill') return v;
+ if (allowBoth && v === 'both') return 'both';
+ return null;
+}
+
+function _compactMarketplaceItem(
+ kind: 'agent' | 'skill',
+ item: marketplaceFeat.MarketplaceAgent | marketplaceFeat.MarketplaceSkill,
+ installedIds: Set<string>,
+) {
+ const installed = installedIds.has(item.id);
+ const base = {
+ kind,
+ id: item.id,
+ name: item.name,
+ description_zh: item.description_zh || '',
+ description_en: item.description_en || '',
+ category: item.category || '',
+ version: item.version,
+ published_at: item.published_at,
+ create_uid: item.create_uid || '',
+ download_count: item.download_count || 0,
+ installed,
+ };
+ if (kind !== 'agent') return base;
+ const agent = item as marketplaceFeat.MarketplaceAgent;
+ return {
+ ...base,
+ icon: agent.icon || '',
+ color: agent.color || '',
+ };
+}
+
+function _marketplaceSearchTerms(query: string): string[] {
+ const out: string[] = [];
+ const push = (s: string) => {
+ const v = s.trim();
+ if (v.length < 2) return;
+ if (out.includes(v)) return;
+ out.push(v);
+ };
+ const commonHanTerms = [
+ '学习', '论文', '学术', '阅读', '精读', '研究', '导师', '助教', '助手',
+ '教育', '课程', '知识', '写作', '编程', '产品', '设计', '数据', '分析',
+ '营销', '法律', '财务', '医学', '心理', '苏格拉底',
+ ];
+ const hanRuns: string[] = [];
+ push(query);
+ for (const token of query.split(/[\s,,;;::|/]+/g)) {
+ push(token);
+ const runs = token.match(/[\u3400-\u9fff]{2,}/g) || [];
+ hanRuns.push(...runs);
+ for (const run of runs) {
+ for (const term of commonHanTerms) {
+ if (run.includes(term)) push(term);
+ }
+ }
}
+ // Last-resort fallback for unknown Chinese compounds. Keep this after
+ // full tokens + common terms so weird cross-boundary bigrams ("文学",
+ // "习助") do not crowd out better English/user-supplied terms.
+ for (const run of hanRuns) {
+ for (let i = 0; i < run.length - 1; i += 1) push(run.slice(i, i + 2));
+ }
+ return out.slice(0, 12);
}
-// ── Commander tools (plan_set / plan_update) ────────────────────────────
-
-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[]> {
+async function buildCommanderExtraTools(state: CidState, w: WorkerState): Promise<AgentTool[]> {
const { uid, cid } = w;
const tools: AgentTool[] = [];
tools.push({
@@ -1854,9 +1928,6 @@ async function buildCommanderExtraTools(
...(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),
@@ -1894,6 +1965,259 @@ async function buildCommanderExtraTools(
},
});
+ tools.push({
+ name: 'marketplace_search',
+ description: [
+ 'Search the official marketplace catalog for agents and skills that are not already installed.',
+ 'Use this only when the currently installed agents/skills and built-in tools do not adequately cover the user task, and a marketplace resource could materially help.',
+ 'This tool only searches; it never installs. If you find one best candidate, call marketplace_request_install and then wait for the user decision.',
+ ].join(' '),
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: {
+ type: 'string',
+ description: 'Search text describing the needed capability. Use the user language when possible.',
+ },
+ kind: {
+ type: 'string',
+ enum: ['agent', 'skill', 'both'],
+ description: 'Resource kind to search. Default: both.',
+ },
+ category: {
+ type: 'string',
+ description: 'Optional marketplace category code.',
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum results per kind (1-20). Default: 5.',
+ },
+ include_installed: {
+ type: 'boolean',
+ description: 'Include resources already installed. Default: false.',
+ },
+ official_only: {
+ type: 'boolean',
+ description: 'When true, only return platform-authored rows (create_uid == "0"). Default: false.',
+ },
+ },
+ required: ['query'],
+ additionalProperties: false,
+ },
+ async execute(input) {
+ const query = _trimText(input?.query, 300);
+ if (!query) return _toolError('`query` is required');
+ const kind = _normaliseMarketplaceKind(input?.kind, true) || 'both';
+ const category = _trimText(input?.category, 80);
+ const limit = _clampLimit(input?.limit, 5, 1, 20);
+ const includeInstalled = input?.include_installed === true;
+ const officialOnly = input?.official_only === true;
+ const size = Math.max(10, Math.min(50, limit * (includeInstalled ? 1 : 3)));
+ try {
+ const installs = await readInstalls(uid);
+ const installedAgentIds = new Set(installs.agents.map((a) => a.id));
+ const installedSkillIds = new Set(installs.skills.map((s) => s.id));
+ const terms = _marketplaceSearchTerms(query);
+ const filterRows = <T extends { id: string; create_uid?: string }>(
+ rows: T[],
+ installedIds: Set<string>,
+ ): T[] => rows
+ .filter((row) => includeInstalled || !installedIds.has(row.id))
+ .filter((row) => !officialOnly || String(row.create_uid || '') === '0')
+ .slice(0, limit);
+ const collectRows = async <T extends { id: string }>(
+ fetchRows: (term: string) => Promise<{ list: T[]; total: number }>,
+ ): Promise<{ rows: T[]; total: number }> => {
+ const merged = new Map<string, T>();
+ let maxTotal = 0;
+ for (const term of terms) {
+ const res = await fetchRows(term);
+ maxTotal = Math.max(maxTotal, res.total || 0);
+ for (const row of res.list || []) {
+ if (!merged.has(row.id)) merged.set(row.id, row);
+ }
+ if (merged.size >= limit * 3) break;
+ }
+ return { rows: Array.from(merged.values()), total: maxTotal };
+ };
+
+ const result: {
+ ok: true;
+ query: string;
+ searched_terms: string[];
+ agents?: ReturnType<typeof _compactMarketplaceItem>[];
+ skills?: ReturnType<typeof _compactMarketplaceItem>[];
+ totals: { agents?: number; skills?: number };
+ } = { ok: true, query, searched_terms: terms, totals: {} };
+
+ if (kind === 'agent' || kind === 'both') {
+ const res = await collectRows((term) => marketplaceFeat.listMarketplaceAgents({
+ q: term,
+ ...(category ? { category } : {}),
+ size,
+ }));
+ const rows = filterRows(res.rows || [], installedAgentIds);
+ result.agents = rows.map((a) => _compactMarketplaceItem('agent', a, installedAgentIds));
+ if (result.agents.length) {
+ if (!w.marketplaceSearchResults) w.marketplaceSearchResults = new Map();
+ for (const agent of result.agents) {
+ const meta = agent as {
+ id: string;
+ icon?: string;
+ color?: string;
+ description_zh?: string;
+ description_en?: string;
+ category?: string;
+ create_uid?: string;
+ };
+ w.marketplaceSearchResults.set(`agent:${agent.id}`, {
+ icon: meta.icon || '',
+ color: meta.color || '',
+ description_zh: meta.description_zh || '',
+ description_en: meta.description_en || '',
+ category: meta.category || '',
+ create_uid: meta.create_uid || '',
+ });
+ }
+ }
+ result.totals.agents = res.total || 0;
+ }
+ if (kind === 'skill' || kind === 'both') {
+ const res = await collectRows((term) => marketplaceFeat.listMarketplaceSkills({
+ q: term,
+ ...(category ? { category } : {}),
+ size,
+ }));
+ const rows = filterRows(res.rows || [], installedSkillIds);
+ result.skills = rows.map((s) => _compactMarketplaceItem('skill', s, installedSkillIds));
+ if (result.skills.length) {
+ if (!w.marketplaceSearchResults) w.marketplaceSearchResults = new Map();
+ for (const skill of result.skills) {
+ w.marketplaceSearchResults.set(`skill:${skill.id}`, {
+ description_zh: skill.description_zh || '',
+ description_en: skill.description_en || '',
+ category: skill.category || '',
+ create_uid: skill.create_uid || '',
+ });
+ }
+ }
+ result.totals.skills = res.total || 0;
+ }
+ return _toolJson(result);
+ } catch (err) {
+ return _toolError((err as Error).message || 'marketplace search failed');
+ }
+ },
+ });
+
+ tools.push({
+ name: 'marketplace_request_install',
+ description: [
+ 'Ask the user to approve installing exactly one marketplace agent or skill found via marketplace_search.',
+ 'This tool does not install anything. It renders a confirmation card for the user; after calling it, stop and wait for the user decision.',
+ 'Use it only when the candidate is clearly useful for the current task. Prefer one best candidate over several speculative requests.',
+ ].join(' '),
+ inputSchema: {
+ type: 'object',
+ properties: {
+ kind: { type: 'string', enum: ['agent', 'skill'] },
+ id: { type: 'string', description: 'Marketplace resource id from marketplace_search.' },
+ name: { type: 'string', description: 'Human-readable resource name from marketplace_search.' },
+ icon: { type: 'string', description: 'For agents only: icon token from marketplace_search.' },
+ color: { type: 'string', description: 'For agents only: color token from marketplace_search.' },
+ description_zh: { type: 'string', description: 'Chinese description from marketplace_search.' },
+ description_en: { type: 'string', description: 'English description from marketplace_search.' },
+ category: { type: 'string', description: 'Category code from marketplace_search.' },
+ 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.' },
+ reason: {
+ type: 'string',
+ description: 'Short user-facing reason this resource helps the current task.',
+ },
+ },
+ required: ['kind', 'id', 'name', 'version', 'published_at', 'reason'],
+ additionalProperties: false,
+ },
+ async execute(input) {
+ const kind = _normaliseMarketplaceKind(input?.kind, false);
+ if (kind !== 'agent' && kind !== 'skill') return _toolError('`kind` must be agent or skill');
+ const id = _trimText(input?.id, 128);
+ if (!safeId(id)) return _toolError('invalid marketplace id');
+ const version = _trimText(input?.version, 80);
+ if (!version) return _toolError('`version` is required');
+ const publishedAt = Number(input?.published_at);
+ if (!Number.isFinite(publishedAt)) return _toolError('`published_at` must be a number');
+ const name = _trimText(input?.name, 160) || id;
+ const reason = _trimText(input?.reason, 800);
+ if (!reason) return _toolError('`reason` is required');
+ const searchMeta = w.marketplaceSearchResults?.get(`${kind}:${id}`);
+ const icon = kind === 'agent'
+ ? (_trimText(input?.icon, 64) || _trimText(searchMeta?.icon, 64))
+ : '';
+ const color = kind === 'agent'
+ ? (_trimText(input?.color, 64) || _trimText(searchMeta?.color, 64))
+ : '';
+ const descriptionZh = _trimText(input?.description_zh, 1200) || _trimText(searchMeta?.description_zh, 1200);
+ const descriptionEn = _trimText(input?.description_en, 1200) || _trimText(searchMeta?.description_en, 1200);
+ const reqCategory = _trimText(input?.category, 80) || _trimText(searchMeta?.category, 80);
+ const createUid = _trimText(input?.create_uid, 80) || _trimText(searchMeta?.create_uid, 80);
+
+ try {
+ const installs = await readInstalls(uid);
+ const alreadyInstalled = kind === 'agent'
+ ? installs.agents.some((a) => a.id === id)
+ : installs.skills.some((s) => s.id === id);
+ if (alreadyInstalled) {
+ return _toolJson({
+ ok: true,
+ already_installed: true,
+ kind,
+ id,
+ instruction: 'This resource is already installed; use the installed agent or skill directly.',
+ });
+ }
+ } catch (err) {
+ log.warn(`marketplace_request_install readInstalls failed cid=${cid}: ${(err as Error).message}`);
+ }
+
+ if (!w.pendingMarketplaceRequests) w.pendingMarketplaceRequests = [];
+ const existing = w.pendingMarketplaceRequests.find((r) => r.kind === kind && r.id === id);
+ if (existing) {
+ return _toolJson({
+ ok: true,
+ request_id: existing.request_id,
+ status: 'pending_user_confirmation',
+ note: 'A confirmation request for this resource is already staged in this turn. Stop and wait for the user decision.',
+ });
+ }
+ const req: MarketplaceInstallRequest = {
+ request_id: genId12(),
+ kind,
+ id,
+ name,
+ ...(kind === 'agent' && icon ? { icon } : {}),
+ ...(kind === 'agent' && color ? { color } : {}),
+ ...(descriptionZh ? { description_zh: descriptionZh } : {}),
+ ...(descriptionEn ? { description_en: descriptionEn } : {}),
+ ...(reqCategory ? { category: reqCategory } : {}),
+ ...(createUid ? { create_uid: createUid } : {}),
+ version,
+ published_at: publishedAt,
+ reason,
+ status: 'pending',
+ requested_at: nowIso(),
+ };
+ w.pendingMarketplaceRequests.push(req);
+ return _toolJson({
+ ok: true,
+ request_id: req.request_id,
+ status: 'pending_user_confirmation',
+ instruction: 'Stop and wait for the user to install or skip this marketplace resource.',
+ });
+ },
+ });
+
tools.push({
name: 'dispatch_to',
description: [
@@ -2092,7 +2416,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 } : {}),
});
},
diff --git a/src/main/features/group_chat/index.ts b/src/main/features/group_chat/index.ts
index 026eb85d..0bcc4a15 100644
--- a/src/main/features/group_chat/index.ts
+++ b/src/main/features/group_chat/index.ts
@@ -14,9 +14,10 @@ import * as path from 'node:path';
import { userChatsDir, groupChatVisibilityFile } from '../../paths';
import { readJsonl, rewriteJsonlLine, nowIso, safeId } from '../../storage';
import { createLogger } from '../../logger';
+import { t } from '../../i18n';
import {
- USER_ID, readMembers, readState, seedReservedActors, purgeGroupDir,
+ COMMANDER_ID, USER_ID, readMembers, readState, seedReservedActors, purgeGroupDir,
setCodingProjectDir,
} from './state';
import { isPlaceholderTitle } from './conv_workspace';
@@ -43,6 +44,8 @@ import type { GroupMessage } from './visibility';
import {
type ChatFormPayload, encodeSubmission, buildMention,
} from './router';
+import type { MarketplaceInstallRequest } from './visibility';
+import * as marketplace from '../marketplace';
const log = createLogger('group_chat.facade');
@@ -143,9 +146,7 @@ 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' };
- const result = await planExecutor.retryStep(userId, cid, stepIndex);
- if (result.ok) _emitPlanSignal(userId, cid, stepIndex, 'retry');
- return result;
+ return planExecutor.retryStep(userId, cid, stepIndex);
}
/** User-initiated skip of a failed plan step (rail "Skip" button). */
@@ -154,31 +155,7 @@ 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' };
- 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, then emit retry/skip signal.
- * Fire-and-forget; failures never block the IPC reply. */
-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 { emitSignal } = await import('../expert_signals');
- const { buildRetrySignal, buildSkipSignal } = await import('../expert_signals/extractors/event');
- const turn_id = `${cid}:plan:${stepIndex}`; // stable across retries of same step
- emitSignal(uid, (kind === 'retry' ? buildRetrySignal : buildSkipSignal)({
- cid, aid, turn_id, step_index: stepIndex,
- }));
- } catch (err) {
- log.warn(`expert-signals plan ${kind} emit failed cid=${cid} step=${stepIndex}: ${(err as Error).message}`);
- }
- })();
+ return planExecutor.skipStep(userId, cid, stepIndex);
}
// ── Streaming events ─────────────────────────────────────────────────────
@@ -250,8 +227,10 @@ export interface MarkFormSubmittedInput {
* here would either dispatch silently (no renderer subscription = lost
* events) or double-enqueue (if renderer also sends).
*
- * Returns the encoded submission text and the recipient agent_id so the
- * renderer can fire the send without re-encoding client-side.
+ * Returns the encoded submission text and the recipient actor id so the
+ * renderer can fire the send without re-encoding client-side. Agent-owned
+ * forms route back to that agent; user-owned plan forms route to `@user`
+ * so the executor can close the user step without waking commander.
*/
export async function markFormSubmittedAndDispatch(
input: MarkFormSubmittedInput,
@@ -284,24 +263,6 @@ 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
@@ -354,14 +315,19 @@ export async function markFormSubmittedAndDispatch(
);
// `buildMention` keeps the display name verbatim (whitespace included);
// falling back to the id keeps the dispatch working if the agent was
- // renamed/disabled between form emit and submit.
+ // renamed/disabled between form emit and submit. User-owned plan forms
+ // deliberately keep `@user`: it is stripped from persisted text while
+ // routing the replay to the user actor, which lets plan reconciliation
+ // consume the answer without starting a commander turn.
let mention = buildMention(agentId);
- try {
- const agentsFeat = await import('../agents');
- const ag = await agentsFeat.getAgent(agentId);
- if (ag && ag.name) mention = buildMention(ag.name);
- } catch (err) {
- log.warn(`form-submit name lookup failed agent=${agentId}: ${(err as Error).message}`);
+ if (agentId !== USER_ID) {
+ try {
+ const agentsFeat = await import('../agents');
+ const ag = await agentsFeat.getAgent(agentId);
+ if (ag && ag.name) mention = buildMention(ag.name);
+ } catch (err) {
+ log.warn(`form-submit name lookup failed agent=${agentId}: ${(err as Error).message}`);
+ }
}
// Newline (not space) between the @-mention and the bullet list so the
// markdown renderer treats them as a paragraph followed by a list. With a
@@ -371,6 +337,232 @@ export async function markFormSubmittedAndDispatch(
return { ok: true, submission: { text: `${mention}\n${encoded}`, agent_id: agentId } };
}
+// ── Marketplace install confirmation ────────────────────────────────────
+
+export interface ResolveMarketplaceInstallRequestInput {
+ userId: string;
+ cid: string;
+ msgId: string;
+ requestId: string;
+ decision: 'install' | 'skip';
+}
+
+function _xmlAttr(value: unknown): string {
+ return String(value ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/"/g, '&quot;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;');
+}
+
+function _marketplaceResultSummary(req: MarketplaceInstallRequest, status: 'installed' | 'skipped' | 'failed', error?: string): string {
+ const name = req.name || req.id;
+ const kind = req.kind === 'skill'
+ ? t('marketplace_install_result.kind_skill')
+ : t('marketplace_install_result.kind_agent');
+ if (status === 'installed') {
+ return t('marketplace_install_result.installed', { kind, name });
+ }
+ if (status === 'skipped') {
+ return t('marketplace_install_result.skipped', { kind, name });
+ }
+ return t('marketplace_install_result.failed', { kind, name, error: error || 'unknown error' });
+}
+
+function _encodeMarketplaceInstallResult(
+ req: MarketplaceInstallRequest,
+ status: 'installed' | 'skipped' | 'failed',
+ error?: string,
+): string {
+ const payload = {
+ request_id: req.request_id,
+ kind: req.kind,
+ id: req.id,
+ name: req.name,
+ version: req.version,
+ published_at: req.published_at,
+ status,
+ ...(error ? { error } : {}),
+ };
+ const json = JSON.stringify(payload, null, 2)
+ .replace(/<\/marketplace-install-result/gi, '<\\/marketplace-install-result');
+ return [
+ _marketplaceResultSummary(req, status, error),
+ `<marketplace-install-result request_id="${_xmlAttr(req.request_id)}" kind="${_xmlAttr(req.kind)}" id="${_xmlAttr(req.id)}" status="${_xmlAttr(status)}">`,
+ json,
+ '</marketplace-install-result>',
+ ].join('\n');
+}
+
+async function _rewriteMarketplaceRequestInFile(
+ file: string,
+ msgId: string,
+ requestId: string,
+ patch: Partial<MarketplaceInstallRequest>,
+): Promise<void> {
+ if (!fs.existsSync(file)) return;
+ const rows = await readJsonl<GroupMessage>(file, 100_000);
+ const idx = rows.findIndex((m) => m.id === msgId);
+ if (idx < 0) return;
+ await rewriteJsonlLine<GroupMessage>(file, idx, (rec) => {
+ if (!rec || rec.id !== msgId || !Array.isArray(rec.marketplace_requests)) return null;
+ const reqIdx = rec.marketplace_requests.findIndex((r) => r.request_id === requestId);
+ if (reqIdx < 0) return null;
+ const nextReqs = rec.marketplace_requests.slice();
+ nextReqs[reqIdx] = { ...nextReqs[reqIdx], ...patch };
+ return { ...rec, marketplace_requests: nextReqs };
+ });
+}
+
+async function _patchMarketplaceRequest(
+ userId: string,
+ cid: string,
+ msgId: string,
+ requestId: string,
+ patch: Partial<MarketplaceInstallRequest>,
+): Promise<{ ok: true; request: MarketplaceInstallRequest; message: GroupMessage } | { ok: false; error: string }> {
+ const file = mainJsonlFile(userId, cid);
+ const all = await readJsonl<GroupMessage>(file, 100_000);
+ const idx = all.findIndex((m) => m.id === msgId);
+ if (idx < 0) return { ok: false, error: 'message not found' };
+ const target = all[idx];
+ const requests = Array.isArray(target.marketplace_requests) ? target.marketplace_requests : [];
+ const reqIdx = requests.findIndex((r) => r.request_id === requestId);
+ if (reqIdx < 0) return { ok: false, error: 'request not found' };
+
+ let updatedReq: MarketplaceInstallRequest | null = null;
+ const r = await rewriteJsonlLine<GroupMessage>(file, idx, (rec) => {
+ if (!rec || rec.id !== msgId || !Array.isArray(rec.marketplace_requests)) return null;
+ const currentIdx = rec.marketplace_requests.findIndex((x) => x.request_id === requestId);
+ if (currentIdx < 0) return null;
+ const nextReqs = rec.marketplace_requests.slice();
+ updatedReq = { ...nextReqs[currentIdx], ...patch };
+ nextReqs[currentIdx] = updatedReq;
+ return { ...rec, marketplace_requests: nextReqs };
+ });
+ if (r.ok === false || !updatedReq) return { ok: false, error: r.ok === false ? r.error : 'request update failed' };
+
+ // Keep the commander's replay slice in sync; other actors do not need the
+ // card state for reasoning, and the main jsonl is the renderer source.
+ try {
+ await _rewriteMarketplaceRequestInFile(
+ groupChatVisibilityFile(userId, cid, target.from),
+ msgId,
+ requestId,
+ patch,
+ );
+ } catch (err) {
+ log.warn(`marketplace request slice update failed user=${userId} cid=${cid} msgId=${msgId}: ${(err as Error).message}`);
+ }
+ return { ok: true, request: updatedReq, message: r.record };
+}
+
+async function _autoBindInstalledMarketplaceResource(
+ userId: string,
+ cid: string,
+ req: MarketplaceInstallRequest,
+): Promise<void> {
+ try {
+ const chats = await import('../chats');
+ const conv = await chats.getConversation(userId, cid);
+ const projectId = (conv as any)?.project_id;
+ if (typeof projectId !== 'string' || !projectId) return;
+ const projectsFeat = await import('../projects');
+ if (req.kind === 'agent') {
+ await projectsFeat.addAgentBinding(userId, projectId, req.id);
+ } else {
+ await projectsFeat.addSkillBinding(userId, projectId, req.id);
+ }
+ log.info(`auto-bound marketplace ${req.kind} ${req.id} to project ${projectId} after install`);
+ } catch (err) {
+ log.warn(`marketplace install auto-bind failed user=${userId} cid=${cid} id=${req.id}: ${(err as Error).message}`);
+ }
+}
+
+export async function resolveMarketplaceInstallRequest(
+ input: ResolveMarketplaceInstallRequestInput,
+): Promise<{
+ ok: boolean;
+ error?: string;
+ request?: MarketplaceInstallRequest;
+ submission?: { text: string; agent_id: string };
+}> {
+ const { userId, cid, msgId, requestId, decision } = input;
+ if (!safeId(cid)) return { ok: false, error: 'invalid cid' };
+ if (!safeId(msgId) || !safeId(requestId)) return { ok: false, error: 'invalid request' };
+ if (decision !== 'install' && decision !== 'skip') return { ok: false, error: 'invalid decision' };
+
+ const file = mainJsonlFile(userId, cid);
+ const all = await readJsonl<GroupMessage>(file, 100_000);
+ const target = all.find((m) => m.id === msgId);
+ const req = target?.marketplace_requests?.find((r) => r.request_id === requestId) || null;
+ if (!target || !req) return { ok: false, error: 'request not found' };
+ if (req.status !== 'pending') return { ok: false, error: 'request already resolved' };
+ if (req.kind !== 'agent' && req.kind !== 'skill') return { ok: false, error: 'invalid request kind' };
+ if (!safeId(req.id) || !req.version || !Number.isFinite(req.published_at)) {
+ return { ok: false, error: 'invalid marketplace request payload' };
+ }
+
+ if (decision === 'skip') {
+ const patched = await _patchMarketplaceRequest(userId, cid, msgId, requestId, {
+ status: 'skipped',
+ resolved_at: nowIso(),
+ });
+ if (!patched.ok) return patched;
+ return {
+ ok: true,
+ request: patched.request,
+ submission: {
+ text: _encodeMarketplaceInstallResult(patched.request, 'skipped'),
+ agent_id: COMMANDER_ID,
+ },
+ };
+ }
+
+ try {
+ if (req.kind === 'agent') {
+ await marketplace.installMarketplaceAgent(req.id, { version: req.version, published_at: req.published_at });
+ } else {
+ await marketplace.installMarketplaceSkill(req.id, { version: req.version, published_at: req.published_at });
+ }
+ await _autoBindInstalledMarketplaceResource(userId, cid, req);
+ const patched = await _patchMarketplaceRequest(userId, cid, msgId, requestId, {
+ status: 'installed',
+ resolved_at: nowIso(),
+ });
+ const request = patched.ok
+ ? patched.request
+ : { ...req, status: 'installed' as const, resolved_at: nowIso() };
+ if (patched.ok === false) {
+ log.warn(`marketplace request status update failed after install user=${userId} cid=${cid} msgId=${msgId}: ${patched.error}`);
+ }
+ return {
+ ok: true,
+ request,
+ submission: {
+ text: _encodeMarketplaceInstallResult(request, 'installed'),
+ agent_id: COMMANDER_ID,
+ },
+ };
+ } catch (err) {
+ const error = (err as Error).message || String(err);
+ const patched = await _patchMarketplaceRequest(userId, cid, msgId, requestId, {
+ status: 'failed',
+ resolved_at: nowIso(),
+ error,
+ });
+ const request = patched.ok ? patched.request : { ...req, status: 'failed' as const, resolved_at: nowIso(), error };
+ return {
+ ok: true,
+ request,
+ submission: {
+ text: _encodeMarketplaceInstallResult(request, 'failed', error),
+ agent_id: COMMANDER_ID,
+ },
+ };
+ }
+}
+
// ── Read messages (UI initial load) ──────────────────────────────────────
export async function readMessages(userId: string, cid: string, limit = 500): Promise<GroupMessage[]> {
diff --git a/src/main/features/group_chat/plan.ts b/src/main/features/group_chat/plan.ts
index 68608ff7..27823f31 100644
--- a/src/main/features/group_chat/plan.ts
+++ b/src/main/features/group_chat/plan.ts
@@ -88,14 +88,6 @@ 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;
@@ -116,9 +108,6 @@ 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),
};
@@ -171,10 +160,6 @@ 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> {
@@ -196,17 +181,11 @@ 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}`,
@@ -223,7 +202,6 @@ 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 ca4a9842..64d17065 100644
--- a/src/main/features/group_chat/plan_executor.ts
+++ b/src/main/features/group_chat/plan_executor.ts
@@ -22,9 +22,13 @@
*/
import { Mutex } from 'async-mutex';
+import * as crypto from 'node:crypto';
+import * as path from 'node:path';
import { createLogger } from '../../logger';
import { t } from '../../i18n';
+import { userChatsDir } from '../../paths';
+import { readJsonl } from '../../storage';
import { COMMANDER_ID, USER_ID, readMembers } from './state';
import {
readPlan, updateStep, markPlanCompletedSignaled,
@@ -32,7 +36,8 @@ import {
type PlanFile, type PlanStep, type FailurePolicy,
} from './plan';
import type { ChatFormPayload } from './router';
-import { buildMention } from './router';
+import { buildMention, decodeSubmission } from './router';
+import type { GroupMessage } from './visibility';
/** Per-cid mutex guarding plan-state transitions. Without this, when N
* parallel-group agents finish nearly simultaneously, their reconcile
@@ -191,16 +196,14 @@ 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. `attachments` lets
- * the executor forward the plan's `initial_attachments` so worker agents
- * receive the same image / file bytes the originating user turn carried. */
+ * but with one extra optional `triggered_step` knob. */
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
* a chat message — used for the synthesis / commander-self steps where
@@ -584,6 +587,18 @@ export async function retryStep(
const step = plan.steps.find((s) => s.index === stepIndex);
if (!step) return { ok: false, error: 'step not found' };
if (step.status !== 'failed') {
+ // The UI can issue a duplicate retry from stale DOM while the first
+ // retry has already re-armed the step. Treat those post-retry states as
+ // success so users do not see a false failure after recovery started.
+ if (
+ step.status === 'pending'
+ || step.status === 'in_progress'
+ || step.status === 'blocked'
+ || step.status === 'done'
+ ) {
+ log.info(`plan-step retry-noop cid=${cid} step=${stepIndex} current=${step.status}`);
+ return { ok: true };
+ }
return { ok: false, error: `step is not in failed state (current: ${step.status})` };
}
await updateStep(uid, cid, stepIndex, 'pending', {
@@ -699,10 +714,41 @@ async function maybeMarkFinished(uid: string, cid: string, plan: PlanFile, ctx:
&& assigneeMatches(s.assignee, actorId, members.actors),
);
if (!match) return;
+ if (actorId === USER_ID && !await acceptsUserStepCompletion(uid, cid, match, ctx)) return;
await applyTermination(uid, cid, match, ctx);
}
}
+async function acceptsUserStepCompletion(
+ uid: string,
+ cid: string,
+ step: PlanStep,
+ ctx: ReconcileCtx,
+): Promise<boolean> {
+ const file = path.join(userChatsDir(uid), `${cid}.jsonl`);
+ const messages = await readJsonl<GroupMessage>(file, 100_000);
+ const userForms = messages.filter((m) => m.form?.agent_id === USER_ID);
+ const stepForms = userForms.filter((m) => m.form?.plan_step_index === step.index);
+ const candidates = stepForms.length ? stepForms : userForms;
+ const relevant = candidates.length ? candidates[candidates.length - 1] : undefined;
+ // Legacy conversations created before user-owned forms existed still need
+ // plain-text replies to complete user steps.
+ if (!relevant?.form) return true;
+
+ const text = ctx.finishedMessage?.text || '';
+ const submission = decodeSubmission(text);
+ const expectedFormId = relevant.form.form_id;
+ if (!submission || submission.agent_id !== USER_ID || submission.form_id !== expectedFormId) {
+ log.info(`plan-user-step ignored non-matching user message cid=${cid} step=${step.index} expected_form=${expectedFormId}`);
+ return false;
+ }
+ if (relevant.form.submitted !== true) {
+ log.info(`plan-user-step ignored unmarked submission cid=${cid} step=${step.index} form=${expectedFormId}`);
+ return false;
+ }
+ return true;
+}
+
async function applyTermination(
uid: string, cid: string, step: PlanStep, ctx: ReconcileCtx,
): Promise<void> {
@@ -817,20 +863,18 @@ 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.
+ // Step asks user for input. Commander voice; render goes to user with
+ // a user-owned form so the reply can route back to the plan machinery
+ // without waking commander as an extra side conversation.
await _hooks.enqueue({
uid, cid,
fromActorId: COMMANDER_ID,
text: rendered,
forceTo: [USER_ID],
triggered_step: step.index,
- ...(inheritedAttachments && inheritedAttachments.length ? { attachments: inheritedAttachments } : {}),
+ form: buildUserStepForm(step),
});
return;
}
@@ -871,7 +915,6 @@ async function dispatchStep(
forceTo: [agentId],
triggered_step: step.index,
dispatch: true,
- ...(inheritedAttachments && inheritedAttachments.length ? { attachments: inheritedAttachments } : {}),
});
}
@@ -883,6 +926,23 @@ function assigneeDisplayPrefix(assignee: string): string {
return buildMention(assignee.replace(/^@+/, ''));
}
+function buildUserStepForm(step: PlanStep): ChatFormPayload {
+ const label = step.title.trim() || (step.input || '').trim() || 'response';
+ return {
+ form_id: crypto.randomBytes(8).toString('hex'),
+ agent_id: USER_ID,
+ plan_step_index: step.index,
+ fields: [{
+ id: 'response',
+ label,
+ type: 'textarea',
+ required: true,
+ default: '',
+ }],
+ submitted: false,
+ };
+}
+
// ── Plan-complete signal ─────────────────────────────────────────────────
async function firePlanComplete(uid: string, cid: string, plan: PlanFile): Promise<void> {
diff --git a/src/main/features/group_chat/router.ts b/src/main/features/group_chat/router.ts
index ae38446c..6b1c31fc 100644
--- a/src/main/features/group_chat/router.ts
+++ b/src/main/features/group_chat/router.ts
@@ -270,6 +270,9 @@ export interface ChatFormPayload {
/** `agent_id` of the agent that owns this form. The submission is routed
* back to this id (the bus will @-prefix on the user's behalf). */
agent_id: string;
+ /** Executor-created user forms use this to bind the form submission to
+ * the exact plan step it is allowed to complete. Agent forms omit it. */
+ plan_step_index?: number;
fields: AgentInput[];
submitted: boolean;
values?: Record<string, unknown>;
diff --git a/src/main/features/group_chat/visibility.ts b/src/main/features/group_chat/visibility.ts
index f9dcfebc..8db4f815 100644
--- a/src/main/features/group_chat/visibility.ts
+++ b/src/main/features/group_chat/visibility.ts
@@ -63,6 +63,10 @@ export interface GroupMessage {
* interaction result back to it. Rendered as a sandboxed `<iframe>`
* (`chat-app://`) at the bottom of the bubble. */
artifacts?: Array<{ id: string; title: string; agent_id: string }>;
+ /** Commander-requested marketplace installs. The model can search the
+ * official marketplace and request a user decision, but the install only
+ * happens after the human clicks the rendered card. */
+ marketplace_requests?: MarketplaceInstallRequest[];
/** Marks this message as a plan announcement (rendered with a folded
* plan card in UI). Set by `plan_set` first-time emission. */
plan_announcement?: boolean;
@@ -82,6 +86,27 @@ export interface GroupMessage {
>;
}
+export interface MarketplaceInstallRequest {
+ request_id: string;
+ kind: 'agent' | 'skill';
+ id: string;
+ name: string;
+ /** Agent avatar tokens from the marketplace row. Skills do not render an avatar. */
+ icon?: string;
+ color?: string;
+ description_zh?: string;
+ description_en?: string;
+ category?: string;
+ create_uid?: string;
+ version: string;
+ published_at: number;
+ reason?: string;
+ status: 'pending' | 'installed' | 'skipped' | 'failed';
+ requested_at: string;
+ resolved_at?: string;
+ error?: string;
+}
+
// ── Slice IO ─────────────────────────────────────────────────────────────
function isVisibleTo(actorId: string, msg: GroupMessage): boolean {
diff --git a/src/main/features/local_agents/runner.ts b/src/main/features/local_agents/runner.ts
index 3f035e14..7da319b6 100644
--- a/src/main/features/local_agents/runner.ts
+++ b/src/main/features/local_agents/runner.ts
@@ -284,41 +284,14 @@ export async function run(opts: RunCliAgentOpts): Promise<RunCliAgentResult> {
// shows the human-readable CLI name; model = version string when
// detected, falling back to the user-picked model id, falling back
// to "(default)".
- const brand = _cliBrandLabel(opts.cli);
- const modelDisplay = entry.version
- ? `${entry.version}${opts.model ? ` · ${opts.model}` : ''}`
- : (opts.model || '(default)');
- // Date-prefixed id matching the LLM-archive convention. Without
- // it, archive filenames mix random-hex (CLI runId) with
- // date-prefixed (LLM newArchiveId) and the lexicographic sort in
- // `listFilesDesc` puts hex BEFORE dates regardless of when the
- // run actually happened — the panel ends up out of order AND the
- // 30-slot prune drops recent LLM calls. The runtime runId is
- // preserved separately on `local-agent-runs/<runId>/`.
- id: newArchiveId(new Date(startedAtMs)),
- startedAt: startedAtIso,
- endedAt: new Date(endedAtMs).toISOString(),
- durationMs: endedAtMs - startedAtMs,
- userId: opts.uid,
- sessionId: `cli-${opts.cli}-${handle.runId}`,
- input: {
- message: opts.prompt,
- provider: brand,
- model: modelDisplay,
- },
- context: {
- agentId: opts.agentId,
- cid: opts.cid,
- workingDir: opts.cwd,
- hasAbortSignal: true,
- },
- events: archiveEvents,
- output: {
- text: finalOutput,
- aborted: terminal.status === 'cancelled',
- error: terminal.error || null,
- },
- });
+ // The dev devtools LLM-call archive is stripped from this build; the runtime
+ // `local-agent-runs/<runId>/` directory is the only persistence path.
+ void _cliBrandLabel(opts.cli);
+ void entry.version;
+ void startedAtMs;
+ void endedAtMs;
+ void startedAtIso;
+ void archiveEvents;
return { runId: handle.runId, status: terminal.status, output: finalOutput, error: terminal.error };
}
diff --git a/src/main/features/marketplace.ts b/src/main/features/marketplace.ts
index ed113f1c..f760e2ad 100644
--- a/src/main/features/marketplace.ts
+++ b/src/main/features/marketplace.ts
@@ -135,6 +135,7 @@ export interface MarketplaceAgent {
download_count: number;
published_at: number;
updated_at: number;
+ default_install?: boolean | number;
}
export interface MarketplaceSkill {
@@ -148,6 +149,7 @@ export interface MarketplaceSkill {
download_count: number;
published_at: number;
updated_at: number;
+ default_install?: boolean | number;
}
export interface AgentDetail {
@@ -164,6 +166,7 @@ export interface AgentDetail {
/** Author uid from the server row. Recorded in `_install.json` so the in-app detail can
* render the author badge without a marketplace round-trip. May be `''` on cache-hit. */
create_uid: string;
+ default_install?: boolean;
}
export interface SkillDetail {
@@ -178,6 +181,7 @@ export interface SkillDetail {
bundle_url: string;
/** Same as `AgentDetail.create_uid`. */
create_uid: string;
+ default_install?: boolean;
}
// ── listing ───────────────────────────────────────────────────────────────
@@ -220,11 +224,11 @@ export async function getAgentDetail(
}
}
// 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 }>(
+ 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 }>(
'/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 || '' };
+ 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 };
}
export async function getSkillDetail(
@@ -236,11 +240,11 @@ export async function getSkillDetail(
return { id: skillId, version: expect.version, category: '', published_at: expect.published_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 }>(
+ const meta = await postJson<{ bundle_url: string; version: string; category: string; published_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 || '' };
+ 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 };
}
/** Fetch a skill .zip from COS and extract into the local cache (idempotent: wipe-and-replace). */
@@ -297,13 +301,14 @@ 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 }>(
+ 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 }>(
'/marketplace/agents/detail', { id: agentId },
);
detail = {
id: agentId, version: fresh.version, category: fresh.category, published_at: fresh.published_at,
agent_json: fresh.agent_json, agent_json_url: fresh.agent_json_url || '',
create_uid: fresh.create_uid || '',
+ default_install: fresh.default_install === true,
};
}
@@ -374,10 +379,10 @@ export async function installMarketplaceSkill(
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 }>(
+ const fresh = await postJson<{ bundle_url: string; version: string; category: string; published_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 || '' };
+ detail = { ...detail, bundle_url: fresh.bundle_url, create_uid: fresh.create_uid || '', default_install: fresh.default_install === true };
}
const cacheDir = getSkillCacheDir(skillId);
diff --git a/src/main/features/marketplace_biz.ts b/src/main/features/marketplace_biz.ts
index 8b9b1566..d19997e6 100644
--- a/src/main/features/marketplace_biz.ts
+++ b/src/main/features/marketplace_biz.ts
@@ -38,20 +38,21 @@ export interface MarketplaceCategory {
code: string;
name_zh: string;
name_en: string;
+ name_ja?: string;
/** Display order — lower first. Kept on the wire purely for client-side rendering. */
sort_order: number;
}
/** Hard-coded fallback used only when both the persisted cache and the server are unreachable
- * on a cold start. Mirrors the server `SEED_CATEGORIES` so the UI behaves identically when
+ * 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`. */
const FALLBACK_CATEGORIES: readonly MarketplaceCategory[] = [
- { code: 'education', name_zh: '教育', name_en: 'Education', sort_order: 10 },
- { code: 'ecommerce', name_zh: '电商', name_en: 'E-commerce', sort_order: 20 },
- { code: 'rnd', name_zh: '产研', name_en: 'R&D', sort_order: 30 },
- { code: 'writing', name_zh: '写作', name_en: 'Writing', sort_order: 40 },
- { code: 'data', name_zh: '数据', name_en: 'Data', sort_order: 50 },
- { code: 'general', name_zh: '通用', name_en: 'General', sort_order: 60 },
+ { code: 'education', name_zh: '教育', name_en: 'Education', name_ja: '教育', sort_order: 10 },
+ { code: 'ecommerce', name_zh: '电商', name_en: 'E-commerce', name_ja: 'EC', sort_order: 20 },
+ { code: 'rnd', name_zh: '产研', name_en: 'R&D', name_ja: '研究開発', sort_order: 30 },
+ { code: 'writing', name_zh: '写作', name_en: 'Writing', name_ja: 'ライティング', sort_order: 40 },
+ { code: 'data', name_zh: '数据', name_en: 'Data', name_ja: 'データ', sort_order: 50 },
+ { code: 'general', name_zh: '通用', name_en: 'General', name_ja: '汎用', sort_order: 60 },
];
interface PersistedBiz {
@@ -96,6 +97,7 @@ async function _fetchFromServer(): Promise<MarketplaceCategory[]> {
code: String(row.code || ''),
name_zh: String(row.name_zh || ''),
name_en: String(row.name_en || ''),
+ name_ja: String(row.name_ja || ''),
sort_order: typeof row.sort_order === 'number' ? row.sort_order : 0,
}))
.filter((c) => c.code);
diff --git a/src/main/features/reflection-digest.ts b/src/main/features/reflection-digest.ts
index c244a9ae..8bd674ef 100644
--- a/src/main/features/reflection-digest.ts
+++ b/src/main/features/reflection-digest.ts
@@ -8,11 +8,10 @@
* cooldown window — see `reflection-trigger.ts` for the call site.
*
* Scope:
- * - `<uid>-gconv-*.jsonl` (commander session) AND
- * - `<uid>-gmember-<cid>-<aid>.jsonl` (agent worker session) for the
- * target agent — added per plan §1.3 P0 because agent worker tool
- * calls / errors are the largest reflection blind spot when only
- * the commander session is read.
+ * - 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).
*
* Output target: ~800 chars, ~250 tokens.
*/
@@ -21,7 +20,6 @@ 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');
@@ -159,43 +157,26 @@ export async function buildAgentReflectionDigest(
for (const conv of convs) {
if (!targetMatches(conv.agent_id || '')) continue;
- // Two sessions per matched conv: the commander gconv-* (already on
- // conv.session_id), and — when the target agent is a specific one
- // (not '_default') — the agent worker's gmember-* derived from
- // (cid, agentId). _default = commander-only convs.
- const sessionIds: string[] = [];
- if (conv.session_id) sessionIds.push(conv.session_id);
- if (agentId !== '_default') {
- sessionIds.push(buildGmemberSessionId(conv.conversation_id, agentId));
- }
- for (const sessionId of sessionIds) {
- _scanSessionFile(uid, sessionId, sinceMs, metrics);
+ 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 */ }
}
+ 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/search/index.ts b/src/main/features/search/index.ts
index bff9eabb..394da9b8 100644
--- a/src/main/features/search/index.ts
+++ b/src/main/features/search/index.ts
@@ -298,17 +298,18 @@ function _descSnippet(description: string, qLower: string): string {
return (start > 0 ? '…' : '') + flat.slice(start, end) + (end < flat.length ? '…' : '');
}
-async function _currentLang(): Promise<'zh' | 'en'> {
+async function _currentDescriptionLang(): Promise<'zh' | 'en'> {
try {
- const { getCurrentLang } = await import('../../i18n');
- return getCurrentLang() === 'zh' ? 'zh' : 'en';
+ const { descriptionLang, getCurrentLang } = await import('../../i18n');
+ return descriptionLang(getCurrentLang());
} catch { return 'en'; }
}
function _pickDesc(item: { description_zh?: string; description_en?: string }, lang: 'zh' | 'en'): string {
- const primary = lang === 'zh' ? item.description_zh : item.description_en;
+ const primary = item[`description_${lang}`];
if (primary && primary.trim()) return primary;
- const fallback = lang === 'zh' ? item.description_en : item.description_zh;
+ const fallbackLang = ({ zh: 'en', en: 'zh' } as const)[lang];
+ const fallback = item[`description_${fallbackLang}`];
return fallback || '';
}
@@ -316,7 +317,7 @@ export async function searchAgents(_userId: string, query: string): Promise<Sear
const q = (query || '').trim();
if (!q) return [];
const qLower = q.toLowerCase();
- const lang = await _currentLang();
+ const lang = await _currentDescriptionLang();
const { listAgents } = await import('../agents');
const list = await listAgents();
const scored: SearchResult[] = [];
@@ -343,7 +344,7 @@ export async function searchSkills(_userId: string, query: string): Promise<Sear
const q = (query || '').trim();
if (!q) return [];
const qLower = q.toLowerCase();
- const lang = await _currentLang();
+ const lang = await _currentDescriptionLang();
const { listSkills } = await import('../skills');
const list = await listSkills();
const scored: SearchResult[] = [];
diff --git a/src/main/features/user_workspace.ts b/src/main/features/user_workspace.ts
index 7de3ac57..7e254611 100644
--- a/src/main/features/user_workspace.ts
+++ b/src/main/features/user_workspace.ts
@@ -42,7 +42,6 @@ import { DEFAULT_USER_WORKSPACE, userWorkspaceConfigFile } from '../paths';
import { createLogger } from '../logger';
import { t } from '../i18n';
import { pruneOrphans } from './file_indexer';
-import { getConversation } from './chats';
const log = createLogger('user-workspace');
@@ -194,6 +193,7 @@ export function getWorkspacePath(userId: string, projectId?: string): string {
export async function resolveProjectIdForCid(userId: string, cid?: string): Promise<string | undefined> {
if (!cid) return undefined;
try {
+ const { getConversation } = await import('./chats');
const conv = await getConversation(userId, cid);
const pid = (conv as any)?.project_id;
return typeof pid === 'string' && pid ? pid : undefined;
diff --git a/src/main/features/window_state.ts b/src/main/features/window_state.ts
new file mode 100644
index 00000000..91e7f875
--- /dev/null
+++ b/src/main/features/window_state.ts
@@ -0,0 +1,126 @@
+import { screen, type BrowserWindow, type BrowserWindowConstructorOptions, type Rectangle } from 'electron';
+
+import { WINDOW_STATE_FILE } from '../paths';
+import { readJsonSync, writeJsonSync } from '../storage';
+
+const DEFAULT_BOUNDS: Pick<Rectangle, 'width' | 'height'> = { width: 1280, height: 800 };
+const MIN_WIDTH = 640;
+const MIN_HEIGHT = 480;
+const MIN_VISIBLE_PX = 80;
+
+export interface SavedWindowState {
+ x?: number;
+ y?: number;
+ width?: number;
+ height?: number;
+ isMaximized?: boolean;
+}
+
+export interface RestoredWindowState {
+ bounds: BrowserWindowConstructorOptions;
+ isMaximized: boolean;
+}
+
+type WindowStateSource = Pick<
+ BrowserWindow,
+ 'getBounds' | 'getNormalBounds' | 'isDestroyed' | 'isMaximized' | 'isMinimized'
+>;
+
+function finiteInt(value: unknown): number | null {
+ if (typeof value !== 'number' || !Number.isFinite(value)) return null;
+ return Math.round(value);
+}
+
+function workAreas(): Rectangle[] {
+ const displays = screen.getAllDisplays();
+ if (displays.length) return displays.map((d) => d.workArea);
+ return [screen.getPrimaryDisplay().workArea];
+}
+
+function maxWorkAreaSize(): Pick<Rectangle, 'width' | 'height'> {
+ return workAreas().reduce(
+ (acc, area) => ({
+ width: Math.max(acc.width, area.width),
+ height: Math.max(acc.height, area.height),
+ }),
+ { width: DEFAULT_BOUNDS.width, height: DEFAULT_BOUNDS.height },
+ );
+}
+
+function clampDimension(value: unknown, min: number, max: number, fallback: number): number {
+ const n = finiteInt(value);
+ if (n === null || n <= 0) return fallback;
+ const effectiveMax = Math.max(min, max);
+ return Math.min(Math.max(n, min), effectiveMax);
+}
+
+function intersects(a: Rectangle, b: Rectangle): boolean {
+ const x1 = Math.max(a.x, b.x);
+ const y1 = Math.max(a.y, b.y);
+ const x2 = Math.min(a.x + a.width, b.x + b.width);
+ const y2 = Math.min(a.y + a.height, b.y + b.height);
+ return x2 - x1 >= MIN_VISIBLE_PX && y2 - y1 >= MIN_VISIBLE_PX;
+}
+
+function hasVisiblePosition(bounds: Rectangle): boolean {
+ return workAreas().some((area) => intersects(bounds, area));
+}
+
+function sanitizeBounds(raw: SavedWindowState): BrowserWindowConstructorOptions {
+ const max = maxWorkAreaSize();
+ const width = clampDimension(raw.width, MIN_WIDTH, max.width, DEFAULT_BOUNDS.width);
+ const height = clampDimension(raw.height, MIN_HEIGHT, max.height, DEFAULT_BOUNDS.height);
+ const x = finiteInt(raw.x);
+ const y = finiteInt(raw.y);
+ if (x === null || y === null) return { width, height };
+
+ const positioned = { x, y, width, height };
+ if (!hasVisiblePosition(positioned)) return { width, height };
+ return positioned;
+}
+
+export function restoreWindowState(): RestoredWindowState {
+ const raw = readJsonSync<SavedWindowState>(WINDOW_STATE_FILE);
+ const bounds = sanitizeBounds(raw);
+ return {
+ bounds,
+ isMaximized: raw.isMaximized === true,
+ };
+}
+
+export function saveWindowStateNow(win: WindowStateSource): void {
+ if (win.isDestroyed() || win.isMinimized()) return;
+ const bounds = win.isMaximized() ? win.getNormalBounds() : win.getBounds();
+ writeJsonSync(WINDOW_STATE_FILE, {
+ x: bounds.x,
+ y: bounds.y,
+ width: bounds.width,
+ height: bounds.height,
+ isMaximized: win.isMaximized(),
+ } satisfies SavedWindowState);
+}
+
+export function watchWindowState(win: BrowserWindow): void {
+ let timer: NodeJS.Timeout | null = null;
+ const scheduleSave = () => {
+ if (timer) clearTimeout(timer);
+ timer = setTimeout(() => {
+ timer = null;
+ saveWindowStateNow(win);
+ }, 300);
+ timer.unref?.();
+ };
+ const saveNow = () => {
+ if (timer) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ saveWindowStateNow(win);
+ };
+
+ win.on('resize', scheduleSave);
+ win.on('move', scheduleSave);
+ win.on('maximize', scheduleSave);
+ win.on('unmaximize', scheduleSave);
+ win.on('close', saveNow);
+}
diff --git a/src/main/i18n.ts b/src/main/i18n.ts
index 313d8020..9dfcc1bd 100644
--- a/src/main/i18n.ts
+++ b/src/main/i18n.ts
@@ -1,9 +1,8 @@
/**
* i18n — minimal lookup for main-side user-facing strings.
*
- * Two locales only: `zh` (简体中文) / `en` (English). Tables live in
- * `src/main/locales/{zh,en}.json` as flat key → string maps (dot-separated
- * keys like `errors.not_utf8`).
+ * Tables live in `src/main/locales/*.json` as flat key → string maps
+ * (dot-separated keys like `errors.not_utf8`).
*
* Lookup order: current lang → `en` → raw key (so missing keys stand out in
* UI instead of going silently blank).
@@ -18,20 +17,100 @@ import * as fs from 'node:fs';
import { SRC_ROOT } from './paths';
-export type Lang = 'zh' | 'en';
-export const SUPPORTED_LANGS: readonly Lang[] = ['zh', 'en'] as const;
+export type Lang = 'zh' | 'en' | 'ja';
+
+export interface LocaleMeta {
+ code: Lang;
+ label: string;
+ htmlLang: string;
+ intlLocale: string;
+ llmName: string;
+ fallback: Lang | null;
+}
+
+export const LOCALES: readonly LocaleMeta[] = [
+ {
+ code: 'zh',
+ label: '简体中文',
+ htmlLang: 'zh-CN',
+ intlLocale: 'zh-CN',
+ llmName: 'Chinese (简体中文)',
+ fallback: 'en',
+ },
+ {
+ code: 'en',
+ label: 'English',
+ htmlLang: 'en',
+ intlLocale: 'en-US',
+ llmName: 'English',
+ fallback: null,
+ },
+ {
+ code: 'ja',
+ label: '日本語',
+ htmlLang: 'ja',
+ intlLocale: 'ja-JP',
+ llmName: 'Japanese (日本語)',
+ fallback: 'en',
+ },
+] as const;
+
+export const SUPPORTED_LANGS: readonly Lang[] = LOCALES.map((l) => l.code);
+const LOCALE_BY_CODE: Readonly<Record<Lang, LocaleMeta>> = LOCALES.reduce((acc, meta) => {
+ acc[meta.code] = meta;
+ return acc;
+}, {} as Record<Lang, LocaleMeta>);
export function isLang(v: unknown): v is Lang {
- return v === 'zh' || v === 'en';
+ return typeof v === 'string' && SUPPORTED_LANGS.includes(v as Lang);
+}
+
+export function normalizeLang(rawLocale: unknown): Lang | null {
+ const s = typeof rawLocale === 'string' ? rawLocale.trim().toLowerCase() : '';
+ if (!s) return null;
+ for (const lang of SUPPORTED_LANGS) {
+ if (s === lang || s.startsWith(`${lang}-`) || s.startsWith(`${lang}_`)) return lang;
+ }
+ return null;
+}
+
+export function getLocaleMeta(lang: Lang): LocaleMeta {
+ return LOCALE_BY_CODE[lang] ?? LOCALE_BY_CODE.en;
+}
+
+export function acceptLanguageHeader(lang: Lang): string {
+ const parts: string[] = [];
+ for (const [idx, candidate] of fallbackChain(lang).entries()) {
+ const meta = getLocaleMeta(candidate);
+ const q = idx === 0 ? '' : `;q=${Math.max(0.1, 0.9 - idx * 0.1).toFixed(1)}`;
+ parts.push(`${meta.intlLocale}${q}`);
+ if (candidate !== meta.intlLocale.split('-')[0]) parts.push(`${candidate}${q}`);
+ }
+ return parts.join(',');
+}
+
+export function fallbackChain(lang: Lang): Lang[] {
+ const out: Lang[] = [];
+ const seen = new Set<Lang>();
+ let cur: Lang | null = lang;
+ while (cur && !seen.has(cur)) {
+ out.push(cur);
+ seen.add(cur);
+ cur = getLocaleMeta(cur).fallback;
+ }
+ return out;
+}
+
+export function descriptionLang(lang: Lang): 'zh' | 'en' {
+ return lang === 'zh' ? 'zh' : 'en';
}
/**
- * Map an Electron `app.getLocale()` / BCP-47 tag to our two-locale space.
- * Anything starting with `zh` → `zh`; everything else → `en`.
+ * Map an Electron `app.getLocale()` / BCP-47 tag to the supported UI language
+ * space. Unknown input falls back to English.
*/
export function detectSystemLang(rawLocale: unknown): Lang {
- const s = typeof rawLocale === 'string' ? rawLocale.trim().toLowerCase() : '';
- return s.startsWith('zh') ? 'zh' : 'en';
+ return normalizeLang(rawLocale) ?? 'en';
}
// ── Table loading ────────────────────────────────────────────────────────
@@ -61,10 +140,10 @@ function loadTable(lang: Lang): Table {
/** Clear cached tables; test-only — app code never needs this. */
export function _resetCacheForTests(): void {
- _tables.zh = undefined;
- _tables.en = undefined;
- _rendererTables.zh = undefined;
- _rendererTables.en = undefined;
+ for (const lang of SUPPORTED_LANGS) {
+ _tables[lang] = undefined;
+ _rendererTables[lang] = undefined;
+ }
}
// ── Renderer-side tables (shipped under src/renderer/locales/) ───────────
@@ -92,12 +171,11 @@ function loadRendererTable(lang: Lang): Table {
return table;
}
-/** Returns both renderer tables for the renderer-side i18n module. */
-export function getRendererTables(): { zh: Table; en: Table } {
- return {
- zh: loadRendererTable('zh'),
- en: loadRendererTable('en'),
- };
+/** Returns all renderer tables for the renderer-side i18n module. */
+export function getRendererTables(): Record<Lang, Table> {
+ const out = {} as Record<Lang, Table>;
+ for (const lang of SUPPORTED_LANGS) out[lang] = loadRendererTable(lang);
+ return out;
}
// ── Current lang ─────────────────────────────────────────────────────────
@@ -105,6 +183,7 @@ let _current: Lang = 'en';
export function setCurrentLang(lang: Lang): void {
_current = lang;
+ try { process.env.ORKAS_ACCEPT_LANGUAGE = acceptLanguageHeader(lang); } catch { /* non-node test harness */ }
}
export function getCurrentLang(): Lang {
@@ -117,13 +196,8 @@ export function getCurrentLang(): Lang {
// runtime injection) — this is the most volatile part of the prompt, so
// keeping it last avoids invalidating the KV-cache prefix.
-const LANG_NAMES: Record<Lang, string> = {
- zh: 'Chinese (简体中文)',
- en: 'English',
-};
-
export function buildLanguageDirective(lang: Lang = _current): string {
- const name = LANG_NAMES[lang] ?? LANG_NAMES.en;
+ const name = getLocaleMeta(lang).llmName;
return [
'## User language',
'',
@@ -147,10 +221,12 @@ export function buildLanguageDirective(lang: Lang = _current): string {
*/
export function t(key: string, vars?: Record<string, string | number>, lang?: Lang): string {
const primary = lang && isLang(lang) ? lang : _current;
- const fromPrimary = loadTable(primary)[key];
- const raw = fromPrimary != null
- ? fromPrimary
- : (primary === 'en' ? key : (loadTable('en')[key] ?? key));
+ let raw: string | undefined;
+ for (const candidate of fallbackChain(primary)) {
+ raw = loadTable(candidate)[key];
+ if (raw != null) break;
+ }
+ raw = raw ?? key;
if (!vars) return raw;
return raw.replace(/\{(\w+)\}/g, (m, name: string) => {
const v = vars[name];
diff --git a/src/main/index.ts b/src/main/index.ts
index 97cc8cf5..5fc07908 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -129,20 +129,25 @@ import * as chatsFeature from './features/chats';
import * as searchFeature from './features/search';
import * as authFeature from './features/auth';
import * as appConfig from './features/config';
+import { getRendererTables } from './i18n';
import * as reflectionTrigger from './features/reflection-trigger';
import * as scheduledTasks from './features/scheduled_tasks';
import * as chatAttachments from './features/chat_attachments';
import * as chatArtifacts from './features/chat_artifacts';
// `features/sync/*` and `ipc/sync.ts` are stripped in OrkasOpen (depends on account).
import * as connectorsFeature from './features/connectors';
+import * as windowState from './features/window_state';
// (sync + relay both depend on account; connectors depends on the Server OAuth bridge).
function createWindow(): BrowserWindow {
const dev = !app.isPackaged;
+ const dev = false;
+ const restored = windowState.restoreWindowState();
const win = new BrowserWindow({
width: 1280,
height: 800,
+ ...restored.bounds,
title: '',
backgroundColor: '#ffffff',
icon: path.join(paths.SRC_ROOT, 'resources', 'icons', 'icon.png'),
@@ -160,6 +165,8 @@ function createWindow(): BrowserWindow {
plugins: true,
},
});
+ windowState.watchWindowState(win);
+ if (restored.isMaximized) win.maximize();
win.loadFile(path.join(paths.SRC_ROOT, 'renderer', 'index.html'));
@@ -228,10 +235,7 @@ function registerIpc(): void {
ipcMain.on('orkas:bootI18n', (event) => {
try {
const lang = appConfig.getLanguage();
- const localesDir = path.join(paths.SRC_ROOT, 'renderer', 'locales');
- const zh = JSON.parse(fs.readFileSync(path.join(localesDir, 'zh.json'), 'utf-8'));
- const en = JSON.parse(fs.readFileSync(path.join(localesDir, 'en.json'), 'utf-8'));
- event.returnValue = { ok: true, lang, tables: { zh, en } };
+ event.returnValue = { ok: true, lang, tables: getRendererTables() };
} catch (err) {
log.warn('bootI18n failed', { error: (err as Error)?.message });
event.returnValue = { ok: false };
@@ -720,7 +724,6 @@ if (!gotLock) {
connectorsFeature.bootstrap(users.getActiveUserId()).catch(() => {
/* errors logged inside the feature; never block app startup */
});
- createWindow();
// Background: pick up any out-of-band changes to source files (sync
// drop-in, manual edits) into the search idx. Query path does not run
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 17610823..247d2678 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -229,6 +229,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {
let result;
if (kind === 'agent') {
if (!agents.isValidAgentId(id)) throw new Error('invalid id');
+ const agent = await agents.getAgent(id);
+ if (!agent || agent.enabled === false) throw new Error('agent_disabled');
result = await projects.addAgentBinding(ctx.userId, projectId, id);
} else if (kind === 'skill') {
result = await projects.addSkillBinding(ctx.userId, projectId, id);
@@ -254,9 +256,9 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { bindings: result.bindings };
},
- // Candidates = full [builtin + custom] minus already-bound. Powers the
- // "Add" picker on the project detail page so the renderer doesn't have
- // to subtract client-side.
+ // Candidates = enabled [builtin + custom] minus already-bound. Powers the
+ // "Add" picker on the project detail page so disabled agents never appear
+ // as addable project members.
'projects.bindings.candidates': async ({ projectId }, ctx) => {
if (!safeId(projectId)) throw new Error('invalid projectId');
if (!await projects.projectExists(ctx.userId, projectId)) throw new Error('not_found');
@@ -268,7 +270,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
skills.listSkills(),
]);
return {
- agents: agentList.filter((a: any) => !boundAgents.has(a.agent_id)),
+ agents: agentList.filter((a: any) => a.enabled !== false && !boundAgents.has(a.agent_id)),
skills: skillList.filter((s: any) => !boundSkills.has(s.id)),
};
},
@@ -362,6 +364,20 @@ const invokeHandlers: Record<string, InvokeHandler> = {
});
},
+ 'groupChat.resolveMarketplaceInstallRequest': async ({ cid, msgId, requestId, decision }, ctx) => {
+ if (!safeId(cid)) throw new Error('invalid cid');
+ if (typeof msgId !== 'string' || !safeId(msgId)) throw new Error('invalid msgId');
+ if (typeof requestId !== 'string' || !safeId(requestId)) throw new Error('invalid requestId');
+ if (decision !== 'install' && decision !== 'skip') throw new Error('invalid decision');
+ return groupChat.resolveMarketplaceInstallRequest({
+ userId: ctx.userId,
+ cid,
+ msgId,
+ requestId,
+ decision,
+ });
+ },
+
// Generic native directory picker. Used by the agent-input-form
// `directory` type so coding agents (claude / codex) collect their
// project directory through the standard input-form pipeline.
@@ -471,8 +487,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { agent };
},
- '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 }) };
+ '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 }) };
},
@@ -858,6 +874,10 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { enabled: appConfig.setMetacognitionEnabled(!!enabled) };
},
+ // Desktop auto-update. The updater feature owns runtime support checks
+ // (packaged macOS/Windows only), feed configuration, download state, and
+ // quit-and-install coordination.
+
// ── Auth / model config (settings page) ──
'auth.listProviders': async () => auth.listProviders(),
'auth.listModels': async ({ provider }) => auth.listModels(provider),
@@ -1277,8 +1297,8 @@ async function resolveContext(sender: WebContents): Promise<IpcContext> {
}
/** Send a push-event to every open renderer. Channel name must match preload's
- * `PUSH_EVENT_PREFIXES` allow-list (currently `marketplace:` / `sync:`). Used by main-initiated
- * status broadcasts (boot-time reconcile / future cloud-sync state). */
+ * `PUSH_EVENT_PREFIXES` allow-list. Used by main-initiated status broadcasts
+ * (boot-time reconcile / sync / updater state). */
export function broadcastToRenderer(channel: string, payload: unknown): void {
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) win.webContents.send(channel, payload);
diff --git a/src/main/locales/en.json b/src/main/locales/en.json
index 8b55001b..5bcdc7e8 100644
--- a/src/main/locales/en.json
+++ b/src/main/locales/en.json
@@ -84,6 +84,11 @@
"chat.agent_load_failed": "⚠️ Agent “{name}” failed to load — its config file may be corrupt or removed. Visit the agents page to inspect, repair, or rebuild it.",
"agent.cli.project_dir.label": "Project directory",
"chat.commander_dispatch_only": "Forwarded to {agents}.",
+ "marketplace_install_result.kind_agent": "agent",
+ "marketplace_install_result.kind_skill": "skill",
+ "marketplace_install_result.installed": "Installed marketplace {kind} “{name}”.",
+ "marketplace_install_result.skipped": "Skipped installing marketplace {kind} “{name}”.",
+ "marketplace_install_result.failed": "Marketplace {kind} “{name}” failed to install: {error}",
"plan.announcement.heading": "I'll proceed with the following steps:",
"plan.announcement.assignee_self": "me",
"plan.announcement.assignee_user": "you",
diff --git a/src/main/locales/ja.json b/src/main/locales/ja.json
new file mode 100644
index 00000000..7b98e56b
--- /dev/null
+++ b/src/main/locales/ja.json
@@ -0,0 +1,120 @@
+{
+ "errors.not_utf8": "テキストファイルは UTF-8 エンコードである必要があります",
+ "errors.path_not_dir": "選択したパスはディレクトリではありません",
+ "errors.dir_not_exists": "ディレクトリが存在しません",
+ "errors.target_not_dir": "対象はディレクトリではありません",
+ "errors.cant_edit_index": "システムインデックスを直接編集することはできません",
+ "errors.cant_delete_index": "システムインデックスを削除することはできません",
+ "errors.file_already_exists": "同じ名前のファイルがすでに存在します",
+ "errors.kb_duplicate_sha1": "同一内容のファイルがナレッジベースにすでに存在します: {existingPath}",
+ "errors.kb_name_too_long": "ファイル名が長すぎます: 「{name}」。約 100 ASCII 文字または約 50 CJK 文字以内にしてください。",
+ "errors.builtin_agent_not_editable": "組み込みエージェントはチャットから編集できません",
+ "errors.builtin_skill_not_editable": "組み込みスキルはチャットから編集できません",
+ "errors.agent_disabled": "この会話に紐づくエージェントは無効です。再度有効にするか、会話を切り替えてください。",
+ "errors.no_files_to_organize": "整理するファイルがありません",
+ "errors.skill_write_failed": "書き込みに失敗しました(パスが無効、またはスキルが見つかりません)",
+ "workspace.picker_title": "ワークスペースディレクトリを選択",
+ "errors.file_too_large_mb": "ファイルがサイズ上限を超えています({mb}MB)",
+ "process.agent.update_field": "▶ {field} を更新しました",
+ "process.agent.update_skills": "▶ スキルを更新しました · {list}",
+ "process.agent.clear_skills": "▶ スキルをクリアしました",
+ "process.agent.update_inputs": "▶ 入力を更新しました · {list}",
+ "process.agent.clear_inputs": "▶ 入力をクリアしました",
+ "process.agent.update_interactive": "▶ interactive を更新しました · {value}",
+ "process.skill.file_written": "▶ {path} を書き込みました",
+ "process.skill.file_rejected": "◯ {path} の書き込みを拒否しました",
+ "image_gen.no_capable_model": "画像生成に対応したモデルが設定されていません。OpenAI または Google の API キーを追加してください(サブスクリプション / OAuth 認証情報では画像生成を利用できません)。",
+ "oauth.minimax.requesting": "MiniMax に認証をリクエストしています…",
+ "oauth.minimax.waiting": "MiniMax の認証完了を待っています…",
+ "oauth.minimax.instructions": "開いたページで次のコードを入力してください:\n\n {code}\n\n認証後、Orkas が認証情報を自動取得します。このウィンドウへ戻ってコピーする必要はありません。",
+ "oauth.minimax.timeout": "MiniMax OAuth がタイムアウトしました。もう一度お試しください。",
+ "oauth.minimax.failed": "MiniMax OAuth に失敗しました: {message}",
+ "oauth.minimax.failed_default": "認証に失敗しました",
+ "oauth.minimax.auth_request_failed": "MiniMax OAuth 認証リクエストに失敗しました({status}): {body}",
+ "oauth.minimax.response_missing_fields": "MiniMax OAuth 応答に user_code / verification_uri がありません",
+ "oauth.minimax.state_mismatch": "MiniMax OAuth の state 検証に失敗しました(CSRF 攻撃またはセッション破損の可能性)",
+ "oauth.minimax.refresh_failed_status": "MiniMax refresh_token に失敗しました({status}): {body}",
+ "oauth.minimax.refresh_failed": "MiniMax refresh_token に失敗しました: {message}",
+ "oauth.minimax.refresh_failed_default": "更新に失敗しました",
+ "oauth.minimax.refresh_missing_fields": "MiniMax refresh_token 応答に必要なフィールドがありません",
+ "auth.progress.processing": "処理中…",
+ "skills.errors.name_required": "スキル名を入力してください",
+ "skills.errors.name_too_long": "スキル名が長すぎます(最大 64 文字)",
+ "skills.errors.name_invalid": "スキル名は英字で始め、英字・数字・アンダースコア(_)・ハイフン(-)を使用できます。英字間の単一スペースも使用できます",
+ "skills.errors.skill_exists": "スキル「{name}」はすでに存在します。別の名前を選んでください。",
+ "skills.errors.builtin_conflict": "スキル名「{name}」は組み込みスキルと競合します。別の名前を選んでください。",
+ "skills.errors.url_scheme": "URL は http(s):// で始まる必要があります",
+ "skills.errors.create_failed": "スキルの作成に失敗しました",
+ "skills.errors.validation_blocked": "スキル内容が品質検証に失敗したため、作成を中止しました",
+ "skills.errors.container_empty": "空の `<skill>` コンテナです。書き込む内容がありません",
+ "skills.errors.create_missing_skill_md": "スキルを作成できません: SKILL.md ブロックがありません",
+ "skills.errors.create_missing_name": "スキルを作成できません: SKILL.md フロントマターに `name` フィールドがありません",
+ "skills.errors.skill_not_found": "スキルが見つかりません: {id}",
+ "skills.errors.path_not_absolute": "絶対パスのディレクトリを選択してください",
+ "skills.errors.dir_inaccessible": "ディレクトリにアクセスできません",
+ "skills.errors.path_not_dir": "ディレクトリを選択してください(ファイルではありません)",
+ "skills.errors.import_refused": "インポートを拒否しました: {reason}",
+ "skills.errors.dir_empty": "ディレクトリが空、またはフィルター対象のファイルのみです",
+ "skills.errors.too_many_files": "ファイル数が多すぎます({count} > {max})",
+ "skills.errors.too_large": "合計サイズが上限を超えています({mb} MiB > 50 MiB)",
+ "skills.errors.copy_failed": "ファイルのコピーに失敗しました: {message}",
+ "skills.import.seed_url": "このスキルをインストールするのを手伝って: {url}",
+ "skills.import.seed_dir": "このスキルをインストールするのを手伝って: {path}",
+ "skills.import.default_desc_url": "{url} からインポートしたスキル(整理待ち)",
+ "skills.import.default_desc_dir": "ローカルディレクトリからインポートしたスキル(整理待ち)",
+ "errors.unsupported_file_ext": "未対応のファイルタイプです({ext})",
+ "errors.unsupported_file_no_ext": "拡張子なし",
+ "errors.contexts.formats_only": "対応形式は次のみです: {allowed}",
+ "errors.unknown_actor": "不明な actor: 「{name}」。名前は「エージェント一覧」の `name` フィールドと一致する必要があります。エージェントが無効になっていないかも確認してください。",
+ "errors.no_model_configured": "モデルが設定されていません。設定ページで API キーを追加するかサインインしてください。",
+ "errors.network": "ネットワークエラー",
+ "errors.network.unavailable": "サービスは一時的に利用できません",
+ "errors.network.timeout": "応答がタイムアウトしました",
+ "errors.network.connection_dropped": "接続が切断されました",
+ "errors.network.rate_limited": "サービスのレート制限に達しました",
+ "errors.network.server_error": "サーバーエラー",
+ "errors.network.overloaded": "サービスが混雑しています",
+ "errors.network.refused": "接続が拒否されました",
+ "errors.network.unreachable": "ネットワークに到達できません",
+ "model.call_failed": "⚠️ モデル呼び出しに失敗しました: {message}",
+ "model.retrying": "再試行中",
+ "model.retrying_n": "再試行 {attempt} 回目",
+ "model.aborted": "(停止しました)",
+ "cli_agent.missing": "⚠️ エージェント「{name}」にはローカル CLI「{cli}」が必要ですが、インストールされていません。インストールして再試行するか、別のタイプへ切り替えてください。",
+ "cli_agent.slash_no_output": "コマンド `{cmd}` を送信しました。",
+ "chat.agent_load_failed": "⚠️ エージェント「{name}」を読み込めませんでした。設定ファイルが破損または削除されている可能性があります。エージェントページで確認、修復、または再作成してください。",
+ "agent.cli.project_dir.label": "プロジェクトディレクトリ",
+ "chat.commander_dispatch_only": "{agents} に転送しました。",
+ "marketplace_install_result.kind_agent": "エージェント",
+ "marketplace_install_result.kind_skill": "スキル",
+ "marketplace_install_result.installed": "マーケットプレイスの{kind}「{name}」をインストールしました。",
+ "marketplace_install_result.skipped": "マーケットプレイスの{kind}「{name}」のインストールをスキップしました。",
+ "marketplace_install_result.failed": "マーケットプレイスの{kind}「{name}」のインストールに失敗しました: {error}",
+ "plan.announcement.heading": "次の手順で進めます:",
+ "plan.announcement.assignee_self": "自分",
+ "plan.announcement.assignee_user": "あなた",
+ "attachments.skipped.missing": "ファイルが存在しなくなりました",
+ "attachments.skipped.too_many_images": "メッセージあたりの画像上限を超えました({max})",
+ "attachments.skipped.compress_failed": "画像圧縮に失敗しました: {message}",
+ "attachments.skipped.video_for_display": "動画は表示専用で、モデルには読み込まれません",
+ "chat.default_title": "新しい会話",
+ "agent.default_name": "無題のエージェント",
+ "dialog.choose_directory": "ディレクトリを選択",
+ "dialog.choose_skill_source_directory": "インポートするスキルのソースディレクトリを選択",
+ "contexts.index.heading": "ナレッジベースインデックス",
+ "contexts.index.maintained_note": "自動管理されています。直接編集しないでください。最終更新: {stamp}",
+ "contexts.index.model_access_note": "モデルは `kb_search` / `kb_read` ツールを通じてこのナレッジベースにアクセスします。このファイルは Finder / File Explorer で閲覧するためのものです。",
+ "contexts.index.empty_section": "(空)",
+ "contexts.index.dirs_heading": "フォルダ",
+ "contexts.index.root_files_heading": "ルートファイル",
+ "contexts.index.file_count": "{count} 個のファイル",
+ "contexts.index.empty_kb": "(ナレッジベースは空です)",
+ "skills.import_block.self_dir": "Orkas 自身のディレクトリ",
+ "skills.import_block.home_root": "ユーザーホームディレクトリのルート",
+ "skills.import_block.system_dir": "システムディレクトリ",
+ "skills.import_block.credentials_dir": "ユーザー認証情報ディレクトリ",
+ "oauth.minimax.unparseable_response": "MiniMax OAuth 応答を解析できませんでした",
+ "oauth.minimax.register_error_hint": "(MiniMax OAuth 登録エラー: {message})",
+ "provider.moonshot.note_paygo": "従量課金のオープンプラットフォーム API キーです。Kimi Coding Plan サブスクリプションとは別課金で、2 種類のキーは互換性がありません",
+ "provider.kimi_coding.note_subscription": "Kimi Coding Plan 月額サブスクリプション専用です。Anthropic 互換エンドポイントを使用し、従量課金の Moonshot API キーとは別です"
+}
diff --git a/src/main/locales/zh.json b/src/main/locales/zh.json
index d1f9aacb..f6d5ca28 100644
--- a/src/main/locales/zh.json
+++ b/src/main/locales/zh.json
@@ -84,6 +84,11 @@
"chat.agent_load_failed": "⚠️ 智能体「{name}」加载失败:配置文件可能损坏或已被删除。请前往智能体页面检查、修复或重建。",
"agent.cli.project_dir.label": "项目目录",
"chat.commander_dispatch_only": "已转给 {agents}。",
+ "marketplace_install_result.kind_agent": "智能体",
+ "marketplace_install_result.kind_skill": "技能",
+ "marketplace_install_result.installed": "已安装市场{kind}「{name}」。",
+ "marketplace_install_result.skipped": "已跳过安装市场{kind}「{name}」。",
+ "marketplace_install_result.failed": "市场{kind}「{name}」安装失败:{error}",
"plan.announcement.heading": "我准备按下面的步骤推进:",
"plan.announcement.assignee_self": "我自己",
"plan.announcement.assignee_user": "请你",
diff --git a/src/main/model/core-agent/chat-history-tools.ts b/src/main/model/core-agent/chat-history-tools.ts
new file mode 100644
index 00000000..d0db2e6d
--- /dev/null
+++ b/src/main/model/core-agent/chat-history-tools.ts
@@ -0,0 +1,224 @@
+/**
+ * Conversation-history tools injected into main-conversation runners.
+ *
+ * These tools are intentionally lower-priority than the knowledge base:
+ * chat logs are useful for "what did we discuss before" recall, but KB files
+ * remain the authoritative source for durable facts and documents.
+ */
+
+import type { AgentTool } from '#core-agent';
+import { safeId } from '../../storage';
+import * as chats from '../../features/chats';
+import * as search from '../../features/search';
+
+export interface ChatHistoryToolsOpts {
+ userId: string;
+ currentCid?: string;
+}
+
+const MAX_SEARCH_K = 15;
+const DEFAULT_SEARCH_K = 5;
+const MAX_READ_WINDOW = 10;
+const DEFAULT_READ_WINDOW = 3;
+const MAX_LATEST_MESSAGES = 30;
+const DEFAULT_LATEST_MESSAGES = 20;
+const SCORE_EPSILON = 0.1;
+
+function previewOf(text: unknown): string {
+ return String(text || '').trim().replace(/\s+/g, ' ');
+}
+
+function attrOf(text: unknown): string {
+ return String(text || '')
+ .replace(/&/g, '&amp;')
+ .replace(/"/g, '&quot;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;');
+}
+
+function boundedInt(value: unknown, fallback: number, min: number, max: number): number {
+ const n = Math.floor(Number(value ?? fallback));
+ if (!Number.isFinite(n)) return fallback;
+ return Math.min(max, Math.max(min, n));
+}
+
+function messageText(msg: chats.MessageRecord): string {
+ const m = msg as chats.MessageRecord & { content?: unknown };
+ if (typeof m.text === 'string') return m.text;
+ if (typeof m.content === 'string') return m.content;
+ return '';
+}
+
+function messageActor(msg: chats.MessageRecord): string {
+ const m = msg as chats.MessageRecord & { role?: string };
+ return m.from || m.role || '';
+}
+
+function messageTime(msg: chats.MessageRecord): string {
+ const m = msg as chats.MessageRecord & { time?: string };
+ return m.ts || m.time || '';
+}
+
+function formatMessage(index: number, msg: chats.MessageRecord): string {
+ const actor = messageActor(msg) || 'unknown';
+ const time = messageTime(msg);
+ const body = messageText(msg).trim();
+ return `<msg index="${index}" from="${actor}"${time ? ` time="${time}"` : ''}>\n${body}\n</msg>`;
+}
+
+function timeMs(value: unknown): number {
+ const ms = Date.parse(String(value || ''));
+ return Number.isFinite(ms) ? ms : 0;
+}
+
+export function rankChatHitsForTest(hits: search.SearchResult[], currentCid?: string): search.SearchResult[] {
+ return [...hits].sort((a, b) => {
+ const scoreDelta = (Number(b.score) || 0) - (Number(a.score) || 0);
+ if (Math.abs(scoreDelta) > SCORE_EPSILON) return scoreDelta;
+
+ const aCurrent = currentCid && String(a.cid || '') === currentCid ? 1 : 0;
+ const bCurrent = currentCid && String(b.cid || '') === currentCid ? 1 : 0;
+ if (aCurrent !== bCurrent) return bCurrent - aCurrent;
+
+ return timeMs(b.time) - timeMs(a.time);
+ });
+}
+
+function createChatSearchTool(opts: ChatHistoryToolsOpts): AgentTool {
+ return {
+ name: 'chat_search',
+ description:
+ 'Search across the current user\'s conversation history. Use this only after\n'
+ + '`kb_search` / `kb_read` when the user asks about prior chats, previous\n'
+ + 'decisions, or historical working context that may not have been saved to\n'
+ + 'the knowledge base. Chat history is informal and may be stale; treat it as\n'
+ + 'supporting context, not as an authoritative source.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: {
+ type: 'string',
+ description: 'Free-text query over conversation messages. Natural language or keywords both work.',
+ },
+ k: {
+ type: 'number',
+ description: 'Top-k result count. Default 5, max 15.',
+ },
+ },
+ required: ['query'],
+ },
+ async execute(input) {
+ const query = String(input.query ?? '').trim();
+ if (!query) return { content: 'chat_search: `query` is required', isError: true };
+ const k = boundedInt(input.k, DEFAULT_SEARCH_K, 1, MAX_SEARCH_K);
+
+ const hits = rankChatHitsForTest(await search.searchChats(opts.userId, query), opts.currentCid).slice(0, k);
+ if (!hits.length) return { content: `No conversation-history results for "${query}".` };
+
+ const lines: string[] = [`${hits.length} hit(s) for "${query}" in conversation history:`];
+ for (const h of hits) {
+ const cid = String(h.cid || '');
+ const msgIndex = Number(h.msg_index);
+ const title = String(h.conv_title || '');
+ const role = String(h.role || '');
+ const time = String(h.time || '');
+ const score = typeof h.score === 'number' ? h.score.toFixed(3) : '0.000';
+ const project = h.project_name ? ` project="${attrOf(h.project_name)}"` : '';
+ const current = opts.currentCid && cid === opts.currentCid ? ' current=true' : '';
+ lines.push(
+ `- cid=${cid} msg=${Number.isFinite(msgIndex) ? msgIndex : '?'}`
+ + (role ? ` role=${role}` : '')
+ + (time ? ` time=${time}` : '')
+ + ` score=${score}`
+ + current
+ + (title ? ` title="${attrOf(title)}"` : '')
+ + project,
+ );
+ lines.push(` ${previewOf(h.snippet)}`);
+ }
+ lines.push('Use chat_read({ cid, msg_index, window }) to inspect surrounding messages.');
+ return { content: lines.join('\n') };
+ },
+ };
+}
+
+function createChatReadTool(opts: ChatHistoryToolsOpts): AgentTool {
+ return {
+ name: 'chat_read',
+ description:
+ 'Read messages from one conversation. Pair with `chat_search`: pass a hit\'s\n'
+ + '`cid` and `msg_index` to fetch nearby context. If `msg_index` is omitted,\n'
+ + 'returns the latest messages from that conversation. Prefer KB tools for\n'
+ + 'durable facts; use chat_read for informal prior-chat context.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ cid: {
+ type: 'string',
+ description: 'Conversation id, usually the `cid` returned by chat_search.',
+ },
+ msg_index: {
+ type: 'number',
+ description: 'Zero-based message index returned by chat_search. Omit to read latest messages.',
+ },
+ window: {
+ type: 'number',
+ description: 'When msg_index is set, include ±window nearby messages. Default 3, max 10.',
+ },
+ limit: {
+ type: 'number',
+ description: 'When msg_index is omitted, latest message count. Default 20, max 30.',
+ },
+ },
+ required: ['cid'],
+ },
+ async execute(input) {
+ const cid = String(input.cid ?? '').trim();
+ if (!safeId(cid)) return { content: 'chat_read: valid `cid` is required', isError: true };
+
+ const conv = await chats.getConversation(opts.userId, cid);
+ if (!conv) return { content: `chat_read: conversation not found — ${cid}`, isError: true };
+
+ const allMessages = await chats.getMessages(opts.userId, cid, Number.MAX_SAFE_INTEGER);
+ if (!allMessages.length) return { content: `chat_read: conversation has no messages — ${cid}` };
+
+ let lo: number;
+ let hi: number;
+ let note: string;
+
+ if (input.msg_index != null) {
+ const msgIndex = Math.floor(Number(input.msg_index));
+ if (!Number.isFinite(msgIndex) || msgIndex < 0 || msgIndex >= allMessages.length) {
+ return {
+ content: `chat_read: msg_index ${msgIndex} out of range; total=${allMessages.length}`,
+ isError: true,
+ };
+ }
+ const window = boundedInt(input.window, DEFAULT_READ_WINDOW, 0, MAX_READ_WINDOW);
+ lo = Math.max(0, msgIndex - window);
+ hi = Math.min(allMessages.length - 1, msgIndex + window);
+ note = lo === hi ? `msg ${msgIndex}` : `msgs ${lo}..${hi} (hit=${msgIndex})`;
+ } else {
+ const limit = boundedInt(input.limit, DEFAULT_LATEST_MESSAGES, 1, MAX_LATEST_MESSAGES);
+ lo = Math.max(0, allMessages.length - limit);
+ hi = allMessages.length - 1;
+ note = `latest ${hi - lo + 1} message(s)`;
+ }
+
+ const body = allMessages.slice(lo, hi + 1)
+ .map((msg, offset) => formatMessage(lo + offset, msg))
+ .join('\n\n');
+ return {
+ content:
+ `<chat-history cid="${cid}" title="${attrOf(conv.title)}" total="${allMessages.length}" range="${lo}..${hi}">\n`
+ + `<!-- ${note} -->\n`
+ + `${body}\n`
+ + '</chat-history>',
+ };
+ },
+ };
+}
+
+export function createChatHistoryTools(opts: ChatHistoryToolsOpts): AgentTool[] {
+ return [createChatSearchTool(opts), createChatReadTool(opts)];
+}
diff --git a/src/main/model/core-agent/connector-meta-tools.ts b/src/main/model/core-agent/connector-meta-tools.ts
index 5c331682..e4b4e5c7 100644
--- a/src/main/model/core-agent/connector-meta-tools.ts
+++ b/src/main/model/core-agent/connector-meta-tools.ts
@@ -36,7 +36,7 @@ import {
stringifyMcpResult,
} from '../../features/connectors/tools-adapter';
import { findCatalogEntry } from '../../features/connectors/catalog';
-import { getCurrentLang } from '../../i18n';
+import { descriptionLang, getCurrentLang } from '../../i18n';
import { createLogger } from '../../logger';
import type { ConnectorInstance, ToolSchema } from '../../features/connectors/types';
@@ -64,10 +64,9 @@ function _renderConnectorLine(instance: ConnectorInstance): string {
// every line is implicitly healthy. Disconnected / errored / connecting instances are hidden
// from the LLM entirely — see tools-adapter.ts for the filter + rationale.
const catalog = findCatalogEntry(instance.id);
- const lang = getCurrentLang();
- const desc = catalog
- ? (lang === 'zh' ? catalog.description_zh : catalog.description_en)
- : '';
+ const lang = descriptionLang(getCurrentLang());
+ const descKey = `description_${lang}` as 'description_zh' | 'description_en';
+ const desc = catalog ? (catalog[descKey] || '') : '';
const acct = instance.oauth_grant?.account_label ? ` (account: ${instance.oauth_grant.account_label})` : '';
return desc
? `- **${instance.id}** — ${instance.display_name}: ${desc}${acct}`
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index 82414f24..6633e8d9 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -32,6 +32,7 @@ import { appendAgentSkill } from '../../features/agents';
const log = createLogger('model/runner');
import { createLocalTools, createFileTools } from './local-tools';
import { createKbTools } from './kb-tools';
+import { createChatHistoryTools } from './chat-history-tools';
import { createImageGenTool } from './image-gen-tool';
import { createWebSearchOverrideTool } from './search-tools';
import { sessionToolResultsDir, agentEvolvedSkillsDir } from '../../paths';
@@ -271,6 +272,14 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// (matches file-tools).
const kbTools = uid ? createKbTools({ userId: uid }) : [];
+ // Conversation-history tools (chat_search + chat_read). Read-only and
+ // lower-priority than KB: useful for "what did we discuss before" recall,
+ // not an authoritative facts source.
+ const chatHistoryTools = uid ? createChatHistoryTools({
+ userId: uid,
+ ...(params.cid ? { currentCid: params.cid } : {}),
+ }) : [];
+
// Image generation. Permission-gated like local-tools; reuses
// localExec.granted (writing image bytes is the same blast radius as
// write_file). Skipped when uid is unknown — generateImage needs the
@@ -340,6 +349,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
...localTools,
...fileTools,
...kbTools,
+ ...chatHistoryTools,
...imageGenTools,
...searchOverrideTools,
...(params.extraTools || []),
diff --git a/src/main/model/core-agent/skill-registry.ts b/src/main/model/core-agent/skill-registry.ts
index 54b4cc46..4907fa4f 100644
--- a/src/main/model/core-agent/skill-registry.ts
+++ b/src/main/model/core-agent/skill-registry.ts
@@ -22,12 +22,12 @@ import * as path from 'node:path';
import { userMarketplaceSkillsDir, userSkillsDir } from '../../paths';
import { getActiveUserId } from '../../features/users';
-import { getCurrentLang } from '../../i18n';
+import { descriptionLang, getCurrentLang } from '../../i18n';
// `pickDescription` is loaded lazily — see CLAUDE.md §3: any static import
// from `#core-agent` at module load would pull in pi-ai before
// `sdk-timeout-patch` has had a chance to monkey-patch it. The cached fn is
// hydrated on first render call, after the loader is already initialized.
-type PickDescription = (s: { description_zh?: string; description_en?: string }, lang: 'zh' | 'en') => string;
+type PickDescription = (s: { description_zh?: string; description_en?: string }, lang: string) => string;
let _pickDescription: PickDescription | null = null;
async function getPickDescription(): Promise<PickDescription> {
if (_pickDescription) return _pickDescription;
@@ -78,7 +78,7 @@ async function renderSkillLines(
builtinRoot: string,
): Promise<string> {
if (!specs.length) return '';
- const lang = getCurrentLang();
+ const lang = descriptionLang(getCurrentLang());
const pick = await getPickDescription();
// Each entry shows the human `name` (what the model uses to decide *whether* to reach
// for the skill) plus the raw `id` (what goes into the read_file path). They DIVERGE for
@@ -189,7 +189,7 @@ export async function invalidateSkills(): Promise<void> {
/** For diagnostics: return the skill list. Picks a description per the active UI language. */
export async function listSkills(): Promise<Array<{ id: string; name: string; description: string }>> {
const loader = await getLoader();
- const lang = getCurrentLang();
+ const lang = descriptionLang(getCurrentLang());
const pick = await getPickDescription();
return loader.list().map((s) => ({ id: s.id, name: s.name, description: pick(s, lang) }));
}
diff --git a/src/main/model/core-agent/tool-catalog.ts b/src/main/model/core-agent/tool-catalog.ts
index 013017ff..c533416d 100644
--- a/src/main/model/core-agent/tool-catalog.ts
+++ b/src/main/model/core-agent/tool-catalog.ts
@@ -35,6 +35,7 @@ export type ToolGroup =
| 'shell' // command line
| 'pdf' // PDF rendering
| 'kb' // knowledge base
+ | 'chat' // conversation history
| 'image' // image generation
| 'web' // web access
| 'connector' // third-party services via MCP umbrella tools
@@ -82,6 +83,10 @@ export const TOOL_CATALOG: ToolCatalogEntry[] = [
{ name: 'kb_search', group: 'kb', summary: 'Semantic search over the user\'s knowledge base.' },
{ name: 'kb_read', group: 'kb', summary: 'Read source-text chunks from a KB file that kb_search has hit.' },
+ // Conversation history
+ { name: 'chat_search', group: 'chat', summary: 'Search prior conversation messages after KB is insufficient or the user asks about previous chats.' },
+ { name: 'chat_read', group: 'chat', summary: 'Read nearby messages from a chat_search hit, or the latest messages from one conversation.' },
+
// Image
{ name: 'generate_image', group: 'image', permission: 'localExec', summary: 'Call the configured image-generation API and save the result into the workspace.' },
@@ -110,6 +115,7 @@ const GROUP_ORDER: ReadonlyArray<{ group: ToolGroup; title: string }> = [
{ group: 'shell', title: 'Shell' },
{ group: 'pdf', title: 'PDF' },
{ group: 'kb', title: 'Knowledge base' },
+ { group: 'chat', title: 'Conversation history' },
{ group: 'image', title: 'Image' },
{ group: 'web', title: 'Web' },
{ group: 'connector', title: 'Connectors (third-party services)' },
diff --git a/src/main/paths.ts b/src/main/paths.ts
index 6ba76740..53387a0e 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -27,6 +27,24 @@
* local/ ← Machine-private domain (never synced)
* config/ ← auth-profiles.json + web-search-cache.json
* search/ ← contexts / chats inverted idx (agent / skill bodies queried in-memory at request time)
+ * <container>/ ← ~/.orkas (mac/linux) or <drive>:\.orkas (Windows, pinned)
+ * data/ ← WS_ROOT
+ * users.json ← Local uid registry + current_user_id
+ * window-state.json ← Last desktop window bounds (machine-local)
+ * logs/ ← Local logs (rolled daily, global)
+ * builtin/ ← Local public builtin runtime copy (hash-synced from src/builtin/ at startup)
+ * agents/<agent_id>/
+ * skills/<skill_id>/
+ * <user_id>/
+ * cloud/ ← Cloud-sync domain (synced per uid / org / team once accounts are integrated)
+ * chats/ chat_attachments/ sessions/ contexts/ memory/
+ * agents/<agent_id>/ skills/<skill_id>/ meta/<agent_id>/
+ * config/preferences.json
+ * local/ ← Machine-private domain (never synced)
+ * config/ ← auth-profiles.json + web-search-cache.json
+ * search/ ← contexts / chats inverted idx (agent / skill bodies queried in-memory at request time)
+ * test/ ← dev-only LLM archive
+ * userWorkSpace/ ← DEFAULT_USER_WORKSPACE (sibling of data/)
*
* Runtime overrides:
* ORKAS_WORKSPACE_ROOT point data root elsewhere; tests pre-set this in setup-env.ts.
@@ -75,6 +93,7 @@ export const WS_ROOT = path.resolve(process.env.ORKAS_WORKSPACE_ROOT);
// ── Top-level (machine-global, shared across uids) ───────────────────────
// Machine-local uid registry: { current_user_id, users: [{user_id, created_at}, ...] }
export const USERS_FILE = path.join(WS_ROOT, 'users.json');
+export const WINDOW_STATE_FILE = path.join(WS_ROOT, 'window-state.json');
// Machine-local logs (daily rolling, single global file shared across uids).
export const LOGS_DIR = path.join(WS_ROOT, 'logs');
// (The legacy globally-shared `data/builtin/{agents,skills}/` tree is gone. Marketplace
@@ -369,22 +388,6 @@ 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
@@ -493,7 +496,6 @@ 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/preload.js b/src/main/preload.js
index ffea7c7b..64ef97c8 100644
--- a/src/main/preload.js
+++ b/src/main/preload.js
@@ -32,7 +32,7 @@ const { contextBridge, ipcRenderer } = require('electron');
let _i18nBoot = null;
try {
const res = ipcRenderer.sendSync('orkas:bootI18n');
- if (res && res.ok && (res.lang === 'zh' || res.lang === 'en') && res.tables) {
+ if (res && res.ok && res.lang && res.tables && Object.prototype.hasOwnProperty.call(res.tables, res.lang)) {
_i18nBoot = { lang: res.lang, tables: res.tables };
}
} catch (_) { /* main not ready / handler missing → renderer falls back to async */ }
@@ -66,7 +66,8 @@ function logRecord(record) {
// Push-event subscription — for main-initiated broadcasts where the renderer doesn't drive
// the lifecycle (unlike `stream` which the renderer starts). Channel names are restricted to
// a known prefix list so the renderer can't tap into arbitrary internal IPC traffic.
-const PUSH_EVENT_PREFIXES = ['marketplace:', 'sync:', 'conversations:'];
+// Sync + auto-updater push channels are stripped from this build along with their producers.
+const PUSH_EVENT_PREFIXES = ['marketplace:', 'conversations:'];
function isAllowedPushChannel(channel) {
if (typeof channel !== 'string') return false;
return PUSH_EVENT_PREFIXES.some((p) => channel.startsWith(p));
diff --git a/src/main/prompts/chat_agent_in_group.md b/src/main/prompts/chat_agent_in_group.md
index af1f1667..42e8c3e7 100644
--- a/src/main/prompts/chat_agent_in_group.md
+++ b/src/main/prompts/chat_agent_in_group.md
@@ -142,5 +142,3 @@ $inputs_schema
### Working directory
$working_dir
-
-$output_format_hint
diff --git a/src/main/prompts/chat_agent_setup.md b/src/main/prompts/chat_agent_setup.md
index f1dd6e76..5f4eb4af 100644
--- a/src/main/prompts/chat_agent_setup.md
+++ b/src/main/prompts/chat_agent_setup.md
@@ -27,7 +27,7 @@ This is the per-agent inline edit chat — the agent you're refining is identifi
1. **Understand the user's intent**: what does the user want this agent to do? Whose problem does it solve? Is it one-shot or repeated runs? When info is insufficient, list questions in one batch and have the user fill them — don't guess or spin in place.
2. **Iterate gradually**: chat about one thing at a time; don't dump every detail up front.
3. **Tool / skill priority** when authoring workflow actions (per agent-creator rules):
- - **Built-in tools** (file IO, `bash`, `kb_search`, `kb_read`, `markdown_to_pdf`, `html_to_pdf`, `generate_image`, `web_search`, `web_fetch`) — write the tool name directly. **No skill wrapper needed** for single-step actions.
+ - **Built-in tools** (file IO, `bash`, `kb_search`, `kb_read`, `chat_search`, `chat_read`, `markdown_to_pdf`, `html_to_pdf`, `generate_image`, `web_search`, `web_fetch`) — write the tool name directly. **No skill wrapper needed** for single-step actions.
- **Then check the "Available skills" section** — skills are most useful for: multi-step logic encapsulation, third-party paid APIs (with credential management), recurrent compound flows. If one fits, use it; don't reinvent the wheel.
- **Connectors**: when the system prompt has a `## Connectors` block, you may reference any listed connector by id in the workflow. Use `list_connector_tools({connector_id})` to see the connector's available actions + JSON input schemas — then write **specific** workflow steps naming the action (e.g. "use `gmail`'s `send_email` action with subject/body from step 2") rather than vague references ("use gmail to send email"). The block lists every connector the user has installed regardless of this agent's current allowed-list; if you reference one not yet allowed for this agent, they'll need to enable it in the agent-edit UI's "Allowed connectors" section before the agent can call it. You do NOT author the allowed-list yourself (UI-only field). `call_connector_tool` is NOT available in this editing session by design — you discover schemas but never execute, so authoring produces no external side effects.
- **Only when none of the above has it**, tell the user "we need a skill called X to do Y" — this is a fallback, not the default. An agent that uses no skills at all is a perfectly common, legal shape.
diff --git a/src/main/prompts/chat_commander.md b/src/main/prompts/chat_commander.md
index 5cbaff08..2f5dba6f 100644
--- a/src/main/prompts/chat_commander.md
+++ b/src/main/prompts/chat_commander.md
@@ -50,6 +50,7 @@ You are NOT woken up in scenarios outside the table (e.g. agent X replies to the
**Rule 2 — Q&A handling**:
- First do `kb_search(query)` semantic retrieval; judge hits by `score` / `preview`.
- If info is enough, answer directly; if not, `kb_read(path, chunk?, window: 1~2)` to fetch adjacent chunks and stitch the answer.
+- If the user asks what was discussed before, or KB is insufficient for prior working context, use `chat_search` then `chat_read`; treat chat history as lower-priority than KB and possibly stale.
- For time-sensitive questions (latest / now / price / status), follow the web-search rules (search before answering).
- Combine facts and call out the source ("according to《X》").
- If the `kb_search` response includes `processing=N` = N documents are being vectorized; you can suggest the user retry shortly.
@@ -84,6 +85,10 @@ The task is a **single-step / one-shot concrete operation** AND can be fully cov
When dispatching to an agent, **don't pre-clarify at the commander level** — the agent has its own `inputs_schema` form and will ask itself.
+#### Marketplace expansion
+
+If installed agents/skills and built-in tools do not adequately cover the task, you may call `marketplace_search`; if one best candidate would materially help, call `marketplace_request_install` (asks the user, does not install), then stop and wait. On the next wake-up, use it if installed; if skipped/failed, continue with the best built-in/installed fallback unless truly blocked.
+
#### Reverse checks
- A skill / built-in tool **is not an actor** — it cannot be a plan step or a dispatch target. "Use the X skill to do Y" = THIS turn you `cat SKILL.md` + invoke the tool.
@@ -231,6 +236,10 @@ Read the matching SKILL.md **before** emitting any `<agent>` / `<skill>` contain
`kb_search(query, k?, dir?, kind?)` + `kb_read(path, chunk?, window?)`: search first, read on demand. After a hit, use `window: 1~2` to bring back adjacent chunks — small embedding unit (precise recall) + larger context unit (enough to answer) — both matter.
+### Conversation history
+
+`chat_search(query, k?)` + `chat_read(cid, msg_index?, window?, limit?)`: use only for prior-chat recall ("what did we discuss before", previous decisions, unsaved working context), after KB or when the user explicitly asks about history.
+
### Connectors (third-party services)
When the system prompt has a `## Connectors` block, those services are reachable via `list_connector_tools({connector_id})` (to see an action's JSON input schema) then `call_connector_tool({connector_id, tool_name, args})`. List before calling — don't guess action names. If the user asks for a service the block doesn't list, tell them to add it via the Connectors panel; don't fake it with `web_search` / `bash`.
diff --git a/src/main/prompts/chat_shared_rules.md b/src/main/prompts/chat_shared_rules.md
index 2eec08a9..04e9d2ca 100644
--- a/src/main/prompts/chat_shared_rules.md
+++ b/src/main/prompts/chat_shared_rules.md
@@ -7,7 +7,7 @@ Switch automatically by availability (paid API / model native / built-in `web_se
- Native model search (Anthropic web_search / OpenAI web_search_preview / Google google_search, etc.) has already grabbed the body and citations server-side — **don't `web_fetch` again**, that wastes tokens.
- Built-in `web_search` returns only summaries → pick 3–5 URLs and use `web_fetch` to grab the full bodies before drawing conclusions.
- Regardless of source, **do not** stitch together a "trend summary" purely from search snippets.
-3. **Failures keep going**: skip to the next URL on a fetch failure; on empty search results or `isError`, **try at least two different strategies** (zh ↔ en switch / different keywords / `site:`) before giving up — a single empty result is not a reason to give up. When everything fails, state the actual cause (empty results / preview text), not vague "API error" wording.
+3. **Failures keep going**: skip to the next URL on a fetch failure; on empty search results or `isError`, **try at least two different strategies** (current UI language ↔ English / different keywords / `site:`) before giving up — a single empty result is not a reason to give up. When everything fails, state the actual cause (empty results / preview text), not vague "API error" wording.
## PDF toolchain rules
@@ -23,35 +23,3 @@ To generate a PDF you **must** use `markdown_to_pdf` (pure markdown) or `html_to
- 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`.
- `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`. Unknown `type` renders empty — stick to the list. 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/quality/rules/schema.ts b/src/main/quality/rules/schema.ts
index d63d77a5..9c21c956 100644
--- a/src/main/quality/rules/schema.ts
+++ b/src/main/quality/rules/schema.ts
@@ -124,17 +124,12 @@ 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: 'MEDIUM',
+ level: 'EXTREME',
rule: 'agent_description_missing',
field: 'agent.json:description',
snippet: '',
- suggested_fix: 'Add `description_zh` and `description_en` so the commander can dispatch this agent in either UI language.',
+ suggested_fix: 'Agent spec must include `description_zh` and `description_en` so the commander can dispatch correctly in either UI language.',
});
} else {
for (const [field, value] of [
diff --git a/src/main/util/tool-result-cap.ts b/src/main/util/tool-result-cap.ts
index fc25143b..948244d1 100644
--- a/src/main/util/tool-result-cap.ts
+++ b/src/main/util/tool-result-cap.ts
@@ -44,6 +44,7 @@ export const MAX_RESULT_CHARS_BY_TOOL: Record<string, number> = {
bash: 30_000,
search_file: 20_000,
kb_search: 20_000,
+ chat_search: 20_000,
web_fetch: 100_000,
web_search: 100_000,
markdown_to_pdf: 4_000,
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 56cf76bf..435ccf47 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -17,13 +17,12 @@
<img class="logo-icon" src="../resources/icons/logo.png" alt="" draggable="false" />
<div class="logo-text">Orkas</div>
</div>
- <button class="sidebar-search-btn" id="sidebar-search-btn" data-i18n-title="sidebar.search_title" title="Global search (⌘K)">
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
- <circle cx="11" cy="11" r="7"></circle>
- <path d="m21 21-4.3-4.3"></path>
- </svg>
+ <button class="sidebar-search-btn" id="sidebar-search-btn" data-i18n-title="sidebar.search_title" title="Global search (Cmd/Ctrl+K)">
+ <span data-ui-icon="search" data-ui-icon-class="sidebar-search-icon"></span>
<span class="sidebar-search-label" data-i18n="sidebar.search">Search</span>
- <span class="sidebar-search-kbd">⌘K</span>
+ <span class="sidebar-search-kbd">
+ <span data-ui-icon="command" data-ui-icon-class="ui-icon sidebar-search-command-icon"></span><span>K</span>
+ </span>
</button>
<div class="sidebar-actions">
<button class="sidebar-btn primary" id="new-chat-btn" data-i18n="sidebar.new_chat">Commander</button>
@@ -33,30 +32,33 @@
<button class="sidebar-btn" id="contexts-btn" data-i18n="sidebar.contexts">Knowledge</button>
<button class="sidebar-btn" id="apps-btn" data-i18n="sidebar.apps">My Apps</button>
</div>
- <div class="sidebar-section sidebar-projects-section">
- <div class="sidebar-section-title-row">
- <span class="sidebar-section-title" data-i18n="sidebar.projects">Projects</span>
- <button class="sidebar-section-add" id="projects-add-btn"
- data-i18n-title="sidebar.project_create_title"
- data-i18n-aria-label="sidebar.project_create_title"
- title="New project" aria-label="New project">+</button>
+ <div class="sidebar-conversation-nav">
+ <div class="sidebar-section sidebar-projects-section">
+ <div class="sidebar-section-title-row">
+ <span class="sidebar-section-title" data-i18n="sidebar.projects">Projects</span>
+ <button class="sidebar-section-add" id="projects-add-btn"
+ data-i18n-title="sidebar.project_create_title"
+ data-i18n-aria-label="sidebar.project_create_title"
+ title="New project" aria-label="New project">+</button>
+ </div>
+ <div class="projects-list" id="projects-list"></div>
</div>
- <div class="projects-list" id="projects-list"></div>
- </div>
- <div class="sidebar-section sidebar-conversations-section">
- <div class="sidebar-section-title" data-i18n="sidebar.conversations">Conversations</div>
- <div class="conversation-list" id="conversation-list">
- <div class="conv-empty" data-i18n="sidebar.conv_empty">No conversations yet</div>
+ <div class="sidebar-section sidebar-conversations-section">
+ <div class="sidebar-section-title" data-i18n="sidebar.conversations">Conversations</div>
+ <div class="conversation-list" id="conversation-list">
+ <div class="conv-empty" data-i18n="sidebar.conv_empty">No conversations yet</div>
+ </div>
</div>
</div>
<div class="sidebar-footer-actions">
<button class="sidebar-footer-btn" id="settings-btn" data-i18n-title="sidebar.settings_title" title="Settings">
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
- <circle cx="12" cy="12" r="3"></circle>
- <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.01a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h.01a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.01a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
- </svg>
+ <span data-ui-icon="settings" data-ui-icon-class="sidebar-footer-icon"></span>
<span data-i18n="sidebar.settings">Settings</span>
</button>
+ <button class="sidebar-footer-btn dev-only-btn" id="devtools-btn" style="display:none" data-i18n-title="sidebar.devtools_title" title="Visible in dev mode only">
+ <span data-ui-icon="terminal" data-ui-icon-class="sidebar-footer-icon"></span>
+ <span data-i18n="sidebar.devtools">Devtools</span>
+ </button>
</div>
</aside>
@@ -78,6 +80,10 @@
<textarea id="new-chat-input" data-i18n-placeholder="new_chat.input_placeholder" placeholder="Type a message..." rows="2"></textarea>
<div class="chat-bottom-bar">
<button type="button" class="chat-attach-btn" id="new-chat-attach-btn" data-i18n-title="new_chat.attach_title" title="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)">
<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>
@@ -89,14 +95,12 @@
<button type="button" class="chat-project-chip" id="new-chat-project-chip" data-i18n-title="chat.project_picker_title" title="Pick project">
<span class="chat-project-prefix" data-i18n="chat.project_label">Project: </span>
<span class="chat-project-name" id="new-chat-project-name" data-i18n="chat.project_none">None</span>
- <svg class="chat-project-chevron" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.5">
- <polyline points="6 9 12 15 18 9"/>
- </svg>
+ <span data-ui-icon="chevron-down" data-ui-icon-class="chat-project-chevron"></span>
</button>
<input type="file" id="new-chat-attach-input" multiple style="display:none"
accept=".md,.markdown,.txt,.csv,.tsv,.json,.yaml,.yml,.log,.pdf,.docx,.png,.jpg,.jpeg,.webp,.gif,text/plain,text/markdown,text/csv,application/json,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/png,image/jpeg,image/webp,image/gif" />
<button id="new-chat-send-btn" class="chat-send-btn" data-i18n-title="new_chat.send_title" title="Send">
- <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"></path></svg>
+ <span data-ui-icon="send" data-ui-icon-class="send-icon"></span>
</button>
</div>
</div>
@@ -107,39 +111,27 @@
<!-- Conversation Detail -->
<section class="panel" id="panel-conversation">
<div class="chat-container">
- <div id="conv-project-empty-banner" class="conv-project-empty-banner" style="display:none">
- <span class="muted" data-i18n="project.bindings.empty_in_chat">This project has no agents or skills bound. Open the project page to add some.</span>
- <button type="button" class="btn btn-sm" id="conv-project-empty-banner-open" data-i18n="project.bindings.open_settings">Open project page</button>
- </div>
- <div id="chat-history" class="chat-history">
- <div class="empty" data-i18n="chat.empty">No messages yet...</div>
- </div>
- <div class="chat-input-wrapper">
- <div class="chat-queue" id="chat-queue" style="display:none">
- <div class="chat-queue-header">
- <span class="chat-queue-label"><span data-i18n="chat.queue_label">Queued</span> <span class="chat-queue-count" id="chat-queue-count">0</span></span>
- <span class="chat-queue-hint" data-i18n="chat.queue_hint">Drag to reorder · Edit · Delete</span>
- </div>
- <div class="chat-queue-list" id="chat-queue-list"></div>
+ <div class="chat-main-pane">
+ <button type="button" class="conversation-info-toggle" id="conversation-info-toggle"
+ data-i18n-title="conversation_info.toggle_title"
+ data-i18n-aria-label="conversation_info.toggle_title"
+ title="Conversation info" aria-label="Conversation info" aria-expanded="false">
+ <span data-ui-icon="panel-list" data-ui-icon-class="conversation-info-toggle-icon"></span>
+ </button>
+ <div id="conv-project-empty-banner" class="conv-project-empty-banner" style="display:none">
+ <span class="muted" data-i18n="project.bindings.empty_in_chat">This project has no agents or skills bound. Open the project page to add some.</span>
+ <button type="button" class="btn btn-sm" id="conv-project-empty-banner-open" data-i18n="project.bindings.open_settings">Open project page</button>
</div>
- <div class="chat-input-area">
- <!-- Floats above the input box. Plan rail anchors left, attachments
- wrap to its right. The workspace chip moved into
- .chat-bottom-bar below (next to the recipient chip) so
- the overlay no longer holds it. -->
- <div class="chat-input-overlay">
- <!-- Plan rail floats at left. Self-hides when current cid has
- no plan. Expanded body opens UPWARD (bottom: 100%) over
- the chat-history. See modules/plan-rail.js. -->
- <div id="plan-rail" class="plan-rail" style="display:none">
- <div class="plan-rail-header" data-i18n-title="plan.toggle_title" title="Collapse / Expand">
- <span class="plan-rail-title">📋 <span data-i18n="plan.title">Execution Plan</span></span>
- <span class="plan-rail-progress" id="plan-rail-progress"></span>
- <span class="plan-rail-toggle" id="plan-rail-toggle">▴</span>
- </div>
- <div class="plan-rail-body" id="plan-rail-body"></div>
+ <div id="chat-history" class="chat-history">
+ <div class="empty" data-i18n="chat.empty">No messages yet...</div>
+ </div>
+ <div class="chat-input-wrapper">
+ <div class="chat-queue" id="chat-queue" style="display:none">
+ <div class="chat-queue-header">
+ <span class="chat-queue-label"><span data-i18n="chat.queue_label">Queued</span> <span class="chat-queue-count" id="chat-queue-count">0</span></span>
+ <span class="chat-queue-hint" data-i18n="chat.queue_hint">Drag to reorder · Edit · Delete</span>
</div>
- <div class="chat-attachments" id="chat-attachments" style="display:none"></div>
+ <div class="chat-queue-list" id="chat-queue-list"></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>
@@ -152,16 +144,68 @@
<div class="chat-skill-chip" id="chat-skill-chip" data-target="conversation" style="display:none">
<span class="chip-label"></span>
<span class="chip-close" data-i18n-title="chat.chip_remove_title" title="Remove">×</span>
+ <div class="chat-input-area">
+ <!-- Floats above the input box. Plan rail anchors left, attachments
+ wrap to its right. The workspace chip moved into
+ .chat-bottom-bar below (next to the recipient chip) so
+ the overlay no longer holds it. -->
+ <div class="chat-input-overlay">
+ <!-- Plan rail floats at left. Self-hides when current cid has
+ no plan. Expanded body opens UPWARD (bottom: 100%) over
+ the chat-history. See modules/plan-rail.js. -->
+ <div id="plan-rail" class="plan-rail" style="display:none">
+ <div class="plan-rail-header" data-i18n-title="plan.toggle_title" title="Collapse / Expand">
+ <span class="plan-rail-title">
+ <span data-ui-icon="clipboard-list" data-ui-icon-class="ui-icon plan-rail-title-icon"></span>
+ <span data-i18n="plan.title">Execution Plan</span>
+ </span>
+ <span class="plan-rail-progress" id="plan-rail-progress"></span>
+ <span class="plan-rail-toggle" id="plan-rail-toggle">▴</span>
+ </div>
+ <div class="plan-rail-body" id="plan-rail-body"></div>
+ </div>
+ <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>
+ <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)">
+ <span class="chat-recipient-prefix" data-i18n="chat.recipient_label">To: </span>
+ <span class="chat-recipient-name" id="chat-recipient-name" data-i18n="chat.recipient_commander">Commander</span>
+ </button>
+ <div class="chat-skill-chip" id="chat-skill-chip" data-target="conversation" style="display:none">
+ <span class="chip-label"></span>
+ <span class="chip-close" data-i18n-title="chat.chip_remove_title" title="Remove">×</span>
+ </div>
+ <input type="file" id="chat-attach-input" multiple style="display:none"
+ accept=".md,.markdown,.txt,.csv,.tsv,.json,.yaml,.yml,.log,.pdf,.docx,.png,.jpg,.jpeg,.webp,.gif,text/plain,text/markdown,text/csv,application/json,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/png,image/jpeg,image/webp,image/gif" />
+ <button id="chat-send-btn" class="chat-send-btn" data-i18n-title="chat.send_title" title="Send">
+ <span data-ui-icon="send" data-ui-icon-class="send-icon"></span>
+ <span data-ui-icon="stop" data-ui-icon-class="stop-icon"></span>
+ </button>
</div>
- <input type="file" id="chat-attach-input" multiple style="display:none"
- accept=".md,.markdown,.txt,.csv,.tsv,.json,.yaml,.yml,.log,.pdf,.docx,.png,.jpg,.jpeg,.webp,.gif,text/plain,text/markdown,text/csv,application/json,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/png,image/jpeg,image/webp,image/gif" />
- <button id="chat-send-btn" class="chat-send-btn" data-i18n-title="chat.send_title" title="Send">
- <svg class="send-icon" viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"></path></svg>
- <svg class="stop-icon" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"></rect></svg>
- </button>
</div>
</div>
</div>
+ <aside class="conversation-info-panel" id="conversation-info-panel" hidden>
+ <div class="conversation-info-header">
+ <div class="conversation-info-title" data-i18n="conversation_info.title">Conversation info</div>
+ <button type="button" class="conversation-info-close" id="conversation-info-close"
+ data-i18n-title="common.close" data-i18n-aria-label="common.close"
+ title="Close" aria-label="Close">×</button>
+ </div>
+ <div class="conversation-info-tabs" role="tablist">
+ <button type="button" class="conversation-info-tab is-active" data-info-tab="tasks" data-i18n="conversation_info.tab_tasks">Tasks</button>
+ <button type="button" class="conversation-info-tab" data-info-tab="files" data-i18n="conversation_info.tab_files">Files</button>
+ <button type="button" class="conversation-info-tab" data-info-tab="attachments" data-i18n="conversation_info.tab_attachments">Attachments</button>
+ </div>
+ <div class="conversation-info-body" id="conversation-info-body"></div>
+ </aside>
</div>
</section>
@@ -200,7 +244,7 @@
<span class="skills-doc-source" id="skills-detail-source"></span>
<div class="skills-doc-actions" id="skills-detail-actions">
<button class="btn-icon-use" id="skill-use-btn" data-i18n-title="skills.use_tooltip" data-i18n-aria-label="skills.use_tooltip" aria-label="Use this skill">
- <svg class="icon-play" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><polygon points="5,3 5,13 13,8" fill="currentColor"/></svg>
+ <span data-ui-icon="play-triangle" data-ui-icon-class="icon-play"></span>
</button>
<button class="btn btn-sm" id="skill-edit-btn" data-i18n="skills.edit">Edit</button>
<button class="btn btn-sm" id="skill-enabled-btn" data-i18n="component.disable">Disable</button>
@@ -252,8 +296,8 @@
<div class="skills-chat-input-area">
<textarea id="skills-chat-input" data-i18n-placeholder="skills.chat_input_placeholder" placeholder="Describe what to change..." rows="1"></textarea>
<button id="skills-chat-send-btn" class="chat-send-btn" data-i18n-title="chat.send_title" title="Send">
- <svg class="send-icon" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"></path></svg>
- <svg class="stop-icon" viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"></rect></svg>
+ <span data-ui-icon="send" data-ui-icon-class="send-icon"></span>
+ <span data-ui-icon="stop" data-ui-icon-class="stop-icon"></span>
</button>
</div>
</div>
@@ -297,7 +341,7 @@
<span class="agents-detail-source" id="agents-detail-source"></span>
<div class="detail-actions" id="agents-detail-actions">
<button class="btn-icon-use" id="agent-use-btn" data-i18n-title="agents.use_tooltip" data-i18n-aria-label="agents.use_tooltip" aria-label="Use this agent">
- <svg class="icon-play" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><polygon points="5,3 5,13 13,8" fill="currentColor"/></svg>
+ <span data-ui-icon="play-triangle" data-ui-icon-class="icon-play"></span>
</button>
<button class="btn btn-sm" id="agent-edit-btn" data-i18n="agents.edit_btn_edit">Edit</button>
<button class="btn btn-sm" id="agent-enabled-btn" data-i18n="component.disable">Disable</button>
@@ -321,15 +365,6 @@
<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-connectors-section">
- <div class="agents-detail-label" data-i18n="agents.label_connectors">Connectors</div>
- <div class="agents-detail-connectors" id="agents-detail-connectors"></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>
@@ -349,8 +384,8 @@
<div class="agents-chat-input-area">
<textarea id="agents-chat-input" data-i18n-placeholder="agents.chat_input_placeholder" placeholder="Describe what to adjust..." rows="1"></textarea>
<button id="agents-chat-send-btn" class="chat-send-btn" data-i18n-title="chat.send_title" title="Send">
- <svg class="send-icon" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"></path></svg>
- <svg class="stop-icon" viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"></rect></svg>
+ <span data-ui-icon="send" data-ui-icon-class="send-icon"></span>
+ <span data-ui-icon="stop" data-ui-icon-class="stop-icon"></span>
</button>
</div>
</div>
@@ -559,6 +594,13 @@
</div>
</div>
<!-- Past-due / grace warning row, populated only when status warrants. -->
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="account.subscription_title">会员</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <!-- Past-due / grace warning row, populated only when status warrants. -->
</div>
</div>
</div>
@@ -588,9 +630,17 @@
<span class="settings-status" data-i18n="settings.sync.pro_required">云端同步是 Pro 会员功能。开通后多台设备的对话、智能体、技能、知识库自动保持一致。</span>
</div>
<div class="settings-group-title" data-i18n="settings.sync.title">云端同步</div>
+ </div>
<div class="settings-group-sub" data-i18n="settings.sync.privacy_note">数据通过 HTTPS 加密上传到私有云存储,仅你的账号可访问。</div>
</div>
- <div class="settings-row">
+ <!-- Pro-required row: shown when current user is not Pro.
+ Replaces the toggle row in that state so the user gets a
+ clear "this is a Pro feature, subscribe" affordance instead
+ of a toggle that just bounces them to a dialog. The
+ existing toggle row + controls row still exist and stay
+ functional for Pro users. -->
+ <span class="settings-status" data-i18n="settings.sync.pro_required">云端同步是 Pro 会员功能。开通后多台设备的对话、智能体、技能、知识库自动保持一致。</span>
+ </div>
<label class="settings-toggle settings-toggle-tight">
<span data-i18n="settings.sync.toggle_enable">启用云端同步</span>
</label>
@@ -703,6 +753,17 @@
<span class="settings-status muted" id="settings-metacognition-status"></span>
</div>
</div>
+
+ <div class="settings-group">
+ <div class="settings-group-head">
+ </div>
+ <div class="settings-row">
+ <label class="settings-toggle">
+ </label>
+ </div>
+ <div class="settings-row">
+ </div>
+ </div>
</div>
<!-- ───────────────────────── 配置 ───────────────────────── -->
@@ -814,10 +875,6 @@
<label data-i18n="agent_modal.category">Category</label>
<div class="ai-select" id="agent-category-select"></div>
</div>
- <div class="form-row">
- <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>
<textarea id="agent-desc-input" rows="4" data-i18n-placeholder="agent_modal.desc_placeholder" placeholder="e.g. Review my code before commit, focus on logic bugs and security issues..."></textarea>
@@ -1002,15 +1059,10 @@
<div class="search-overlay" id="search-overlay" style="display:none">
<div class="search-modal">
<div class="search-input-row">
- <svg class="search-input-icon" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
- <circle cx="11" cy="11" r="7"></circle>
- <path d="m21 21-4.3-4.3"></path>
- </svg>
+ <span data-ui-icon="search" data-ui-icon-class="search-input-icon"></span>
<input type="text" id="search-input" data-i18n-placeholder="search.input_placeholder" placeholder="Search chats and knowledge base…" autocomplete="off" spellcheck="false" />
<button class="search-close-btn" id="search-close-btn" data-i18n-title="search.close_title" title="Close (Esc)">
- <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
- <path d="M18 6 6 18M6 6l12 12"></path>
- </svg>
+ <span data-ui-icon="x" data-ui-icon-class="search-close-icon"></span>
</button>
</div>
<div class="search-tabs" id="search-tabs" role="tablist">
@@ -1045,10 +1097,14 @@
after boot.js (it calls bootApp); account_settings.js is invoked from settings.js::loadSettings. -->
<script src="./views/login/login_panel.js"></script>
<script src="./views/login/account_settings.js"></script>
+ <!-- Pro entitlement gate (renderer-side). Loads before voice / sync so window.proGate
+ exists when those modules attach button handlers. Stripped in OrkasOpen. -->
+ <script src="./modules/pro_gate.js"></script>
<script src="./modules/avatar.js"></script>
<script src="./modules/avatar-picker.js"></script>
<script src="./modules/chat-input-form.js"></script>
<script src="./modules/chat-lightbox.js"></script>
+ <script src="./modules/icons.js"></script>
<script src="./modules/chat-file-viewer.js"></script>
<script src="./modules/strip-structural-blocks.js"></script>
<script src="./modules/projects.js"></script>
@@ -1056,6 +1112,7 @@
<script src="./modules/conversation.js"></script>
<script src="./modules/chat-artifact.js"></script>
<script src="./modules/plan-rail.js"></script>
+ <script src="./modules/conversation-info.js"></script>
<script src="./modules/queue-draft.js"></script>
<script src="./modules/skills.js"></script>
<script src="./modules/connectors.js"></script>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index 0b1e2c49..965d8789 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -16,6 +16,34 @@
"account.settings_title": "Account",
"account.settings_logout": "Sign out",
"account.settings_signed_in": "Signed in",
+ "account.subscription_title": "Subscription",
+ "account.subscription_status_active": "Renews",
+ "account.subscription_status_will_cancel": "Cancels",
+ "account.subscription_status_past_due": "Payment issue",
+ "account.subscription_status_expired": "Subscription ended",
+ "account.subscription_status_free": "Free plan",
+ "account.subscription_status_coming_soon": "Pro coming soon",
+ "account.subscription_detail_active": "Cloud sync and voice input are unlocked.",
+ "account.subscription_detail_will_cancel": "You keep Pro until the end of the period; then revert to Free.",
+ "account.subscription_detail_past_due": "Update your payment method to avoid losing Pro.",
+ "account.subscription_detail_grace": "Cloud data will be deleted at the end of the grace window; resubscribe to keep it.",
+ "account.subscription_detail_free": "Upgrade to Pro for cloud sync and voice input.",
+ "account.subscription_detail_coming_soon": "We're opening the billing channel — stay tuned.",
+ "account.subscription_action_subscribe": "Subscribe",
+ "account.subscription_action_manage": "Manage subscription",
+ "account.subscription_action_resume": "Resume subscription",
+ "account.subscription_action_update_card": "Update payment method",
+ "account.subscription_action_resubscribe": "Resubscribe",
+ "account.subscription_action_coming_soon": "Coming soon",
+ "account.subscription_warning_past_due": "Payment failed. Update your card on the management page.",
+ "account.subscription_warning_grace": "Cloud data will be deleted on {date}. Resubscribe to keep it.",
+ "account.subscription_open_failed": "Couldn't open the management page; check your network and retry.",
+ "account.pro_required_title": "Pro feature",
+ "account.pro_required_voice": "Voice input is a Pro feature. Subscribe to dictate directly into the composer with auto-transcription.",
+ "account.pro_required_sync": "Cloud sync is a Pro feature. Subscribe to keep conversations, agents, skills and knowledge in sync across devices.",
+ "account.pro_required_generic": "This is a Pro feature. Subscribe to unlock cloud sync and voice input.",
+ "account.pro_required_action": "Subscribe now",
+ "account.pro_required_cancel": "Later",
"common.ok": "OK",
"common.confirm": "Confirm",
"common.cancel": "Cancel",
@@ -38,7 +66,7 @@
"component.send_blocked_disabled": "This agent is disabled — re-enable it or switch conversation.",
"component.conv_agent_disabled_banner": "The agent bound to this conversation is disabled. Send is locked. Re-enable it on the Agents page to continue.",
"sidebar.search": "Search",
- "sidebar.search_title": "Global search (⌘K)",
+ "sidebar.search_title": "Global search (Cmd/Ctrl+K)",
"sidebar.new_chat": "Commander",
"sidebar.agents": "Agents",
"sidebar.skills": "Skills",
@@ -61,14 +89,7 @@
"common.save": "Save",
"common.more": "More",
"common.loading": "Loading…",
- "agents.label_connectors": "Allowed connectors",
- "agents.connectors_empty": "No connectors installed. Add one in the Connectors tab.",
- "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": "Conversations",
+ "sidebar.conversations": "Chats",
"sidebar.conv_empty": "No conversations yet",
"sidebar.projects": "Projects",
"sidebar.project_create_title": "New project",
@@ -139,6 +160,25 @@
"chat.preview_unsupported_reveal": "Open Folder",
"chat.preview_cancel": "Close",
"chat.process_info": "Process info",
+ "conversation_info.toggle_title": "Conversation info",
+ "conversation_info.title": "Conversation info",
+ "conversation_info.tab_tasks": "Tasks",
+ "conversation_info.tab_files": "Files",
+ "conversation_info.tab_attachments": "Attachments",
+ "conversation_info.no_conversation": "Open a conversation to see details",
+ "conversation_info.load_failed": "Could not load conversation info: {reason}",
+ "conversation_info.empty_tasks": "No tasks yet",
+ "conversation_info.empty_steps": "No steps",
+ "conversation_info.empty_files": "No generated files yet",
+ "conversation_info.empty_attachments": "No attachments",
+ "conversation_info.task_plan_fallback": "Execution plan",
+ "conversation_info.step_files": "Files",
+ "conversation_info.status.pending": "Pending",
+ "conversation_info.status.in_progress": "Running",
+ "conversation_info.status.done": "Done",
+ "conversation_info.status.failed": "Failed",
+ "conversation_info.status.skipped": "Skipped",
+ "conversation_info.status.blocked": "Blocked",
"artifact.title": "Interactive app",
"artifact.reload": "Reload",
"artifact.more": "More",
@@ -166,12 +206,12 @@
"apps.save_failed": "Could not save the app",
"chat.archive_btn_title": "Save to knowledge base",
"chat.archive_btn": "Knowledge",
- "chat.archive_done": "Archived ✓",
+ "chat.archive_done": "Archived",
"chat.archive_failed": "Archive failed",
"chat.archive_failed_with_reason": "Archive failed: {reason}",
"chat.copy_btn_title": "Copy final reply to clipboard",
"chat.copy_btn": "Copy",
- "chat.copy_done": "Copied ✓",
+ "chat.copy_done": "Copied",
"chat.copy_failed": "Copy failed",
"chat.quote_btn_title": "Quote this message and send to a target agent",
"chat.quote_btn": "Quote",
@@ -230,19 +270,19 @@
"ai_select.empty": "(no options)",
"chat.stream.phase_start": "start",
"chat.stream.phase_end": "done",
- "chat.stream.reasoning_start": "▶ Reasoning started",
- "chat.stream.reasoning_done": "● Reasoning complete",
- "chat.stream.reasoning_error": "◯ Reasoning error",
- "chat.stream.reasoning_error_with": "◯ Reasoning error — {msg}",
+ "chat.stream.reasoning_start": "Reasoning started",
+ "chat.stream.reasoning_done": "Reasoning complete",
+ "chat.stream.reasoning_error": "Reasoning error",
+ "chat.stream.reasoning_error_with": "Reasoning error — {msg}",
"chat.stream.lifecycle": "▪ Lifecycle {p}",
- "chat.stream.thinking": "◆ Thinking",
- "chat.stream.plan_with_steps": "▣ Plan ({n} steps): {titles}",
- "chat.stream.plan": "▣ Plan {p}",
- "chat.stream.command_empty": "▷ (no output)",
- "chat.stream.patch": "◉ File change",
- "chat.stream.approval": "○ Awaiting approval",
- "chat.stream.approval_with": "○ Awaiting approval: {p}",
- "chat.stream.error": "◯ Error: {msg}",
+ "chat.stream.thinking": "Thinking",
+ "chat.stream.plan_with_steps": "Plan ({n} steps): {titles}",
+ "chat.stream.plan": "Plan {p}",
+ "chat.stream.command_empty": "(no output)",
+ "chat.stream.patch": "File change",
+ "chat.stream.approval": "Awaiting approval",
+ "chat.stream.approval_with": "Awaiting approval: {p}",
+ "chat.stream.error": "Error: {msg}",
"chat.stream.attachment_skipped": "◯ Attachment skipped: {items}",
"chat.create_agent_btn": "Create agent",
"chat.create_agent_inline": "Distill the above into an agent",
@@ -383,7 +423,7 @@
"agents.schedule.default_input_label": "Default input",
"agents.schedule.default_input_placeholder": "Sent to the agent on each run (optional)",
"agents.schedule.title_label": "Task title (optional)",
- "agents.schedule.title_placeholder": "Used as the new conversation title; defaults to ⏱ {name}",
+ "agents.schedule.title_placeholder": "Used as the new conversation title; defaults to {name}",
"agents.schedule.enabled_label": "Enabled",
"agents.schedule.save_btn": "Save",
"agents.schedule.cancel_btn": "Cancel",
@@ -503,6 +543,9 @@
"settings.section.cloud": "Cloud",
"settings.section.local": "Local",
"settings.sync.title": "Cloud sync",
+ "settings.sync.pro_badge": "Pro",
+ "settings.sync.pro_required": "Cloud sync is a Pro feature. Subscribe to keep conversations, agents, skills and knowledge in sync across devices.",
+ "settings.sync.grace_warning": "Cloud sync paused. Cloud data will be deleted on {date}. Resubscribe to keep it.",
"settings.sync.storage_title": "Storage",
"settings.sync.conflicts_title": "Conflict log",
"settings.sync.conflicts_sub": "When two devices edit the same file at once, the overwritten version is kept here.",
@@ -657,7 +700,7 @@
"settings.entries.testing": "Testing…",
"settings.entries.conn_ok": "Connected {ms}",
"settings.entries.conn_failed": "Connection failed",
- "settings.entries.delete_confirm": "Delete authorization \"{title}\"?\n\n(Only removes it from the priority list; the credential is kept for future reuse.)",
+ "settings.entries.delete_confirm": "Delete authorization \"{title}\"?\n\nThis also clears the local credential linked to this authorization. You will need to authorize it again before using it.",
"settings.entries.switch_model_failed": "Failed to switch model",
"settings.entries.reorder_failed": "Failed to reorder",
"settings.entries.delete_failed": "Delete failed",
@@ -806,7 +849,7 @@
"agent.external_badge.openclaw": "External · OpenClaw",
"agent.external_badge.opencode": "External · OpenCode",
"agent.external_badge.hermes": "External · Hermes",
- "agent.cli_missing": "⚠ External agent not installed",
+ "agent.cli_missing": "External agent not installed",
"input.dir.none": "(not set)",
"input.dir.pick": "Pick directory…",
"input.dir.change": "Change…",
@@ -961,5 +1004,13 @@
"marketplace.author_platform": "Official",
"marketplace.author_user": "by {uid}",
"marketplace.reconcile_running": "Syncing marketplace resources {pulled}/{total}…",
- "marketplace.reconcile_partial": "Marketplace sync done; {failed} failed, will retry on next launch"
+ "marketplace.reconcile_partial": "Marketplace sync done; {failed} failed, will retry on next launch",
+ "marketplace_request.kind_agent": "Agent",
+ "marketplace_request.kind_skill": "Skill",
+ "marketplace_request.status_pending": "Needs approval",
+ "marketplace_request.status_installed": "Installed",
+ "marketplace_request.status_skipped": "Skipped",
+ "marketplace_request.status_failed": "Failed",
+ "marketplace_request.install": "Install",
+ "marketplace_request.skip": "Skip"
}
diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.json
new file mode 100644
index 00000000..ad0c2c85
--- /dev/null
+++ b/src/renderer/locales/ja.json
@@ -0,0 +1,1010 @@
+{
+ "account.gate_title": "Orkas にサインイン",
+ "account.gate_signin": "サインイン",
+ "account.gate_signin_pending": "サインインページを開いています…",
+ "account.gate_signin_again": "サインインページをもう一度開く",
+ "account.gate_signing_in": "サインイン中…",
+ "account.gate_browser_hint": "ブラウザでサインインページを開きました。完了すると自動的に戻ります。",
+ "account.gate_sub": "続行するにはアカウントにサインインしてください",
+ "account.gate_hint": "開いたブラウザで認証してください。完了すると自動的に戻ります。",
+ "account.provider_google": "Google で続行",
+ "account.provider_apple": "Apple で続行",
+ "account.provider_generic": "{provider} で続行",
+ "account.error_start": "サインインを開始できませんでした。もう一度お試しください。",
+ "account.error_cancelled": "サインインがキャンセルされました。",
+ "account.error_generic": "サインインに失敗しました。",
+ "account.settings_title": "アカウント",
+ "account.settings_logout": "サインアウト",
+ "account.settings_signed_in": "サインイン済み",
+ "account.subscription_title": "サブスクリプション",
+ "account.subscription_status_active": "更新予定日",
+ "account.subscription_status_will_cancel": "解約予定日",
+ "account.subscription_status_past_due": "支払いに問題があります",
+ "account.subscription_status_expired": "サブスクリプション終了",
+ "account.subscription_status_free": "無料プラン",
+ "account.subscription_status_coming_soon": "Pro は近日公開",
+ "account.subscription_detail_active": "クラウド同期と音声入力が利用できます。",
+ "account.subscription_detail_will_cancel": "期間終了までは Pro を利用できます。その後は無料プランに戻ります。",
+ "account.subscription_detail_past_due": "Pro を継続するには支払い方法を更新してください。",
+ "account.subscription_detail_grace": "猶予期間の終了時にクラウドデータが削除されます。保持するには再登録してください。",
+ "account.subscription_detail_free": "クラウド同期と音声入力を使うには Pro にアップグレードしてください。",
+ "account.subscription_detail_coming_soon": "課金チャネルを準備中です。しばらくお待ちください。",
+ "account.subscription_action_subscribe": "登録する",
+ "account.subscription_action_manage": "サブスクリプションを管理",
+ "account.subscription_action_resume": "サブスクリプションを再開",
+ "account.subscription_action_update_card": "支払い方法を更新",
+ "account.subscription_action_resubscribe": "再登録",
+ "account.subscription_action_coming_soon": "近日公開",
+ "account.subscription_warning_past_due": "支払いに失敗しました。管理ページでカードを更新してください。",
+ "account.subscription_warning_grace": "{date} にクラウドデータが削除されます。保持するには再登録してください。",
+ "account.subscription_open_failed": "管理ページを開けませんでした。ネットワークを確認して再試行してください。",
+ "account.pro_required_title": "Pro 機能",
+ "account.pro_required_voice": "音声入力は Pro 機能です。登録するとコンポーザーへ直接音声入力し、自動文字起こしできます。",
+ "account.pro_required_sync": "クラウド同期は Pro 機能です。登録すると会話、エージェント、スキル、ナレッジを複数デバイスで同期できます。",
+ "account.pro_required_generic": "これは Pro 機能です。クラウド同期と音声入力を利用するには登録してください。",
+ "account.pro_required_action": "今すぐ登録",
+ "account.pro_required_cancel": "あとで",
+ "common.ok": "OK",
+ "common.confirm": "確認",
+ "common.cancel": "キャンセル",
+ "common.delete": "削除",
+ "common.edit": "編集",
+ "common.use": "使用",
+ "common.refresh": "更新",
+ "common.clear": "クリア",
+ "common.close": "閉じる",
+ "common.copy": "コピー",
+ "common.remove": "削除",
+ "common.dev_suffix": "(開発)",
+ "component.enabled": "有効",
+ "component.disabled": "無効",
+ "component.enable": "有効にする",
+ "component.disable": "無効にする",
+ "component.toggle_disable_hint": "クリックして無効化",
+ "component.toggle_enable_hint": "クリックして有効化",
+ "component.toggle_failed": "切り替えに失敗しました",
+ "component.send_blocked_disabled": "このエージェントは無効です。再度有効にするか、会話を切り替えてください。",
+ "component.conv_agent_disabled_banner": "この会話に紐づくエージェントは無効です。送信はロックされています。続行するには Agents ページで再度有効にしてください。",
+ "sidebar.search": "検索",
+ "sidebar.search_title": "グローバル検索 (Cmd/Ctrl+K)",
+ "sidebar.new_chat": "コマンダー",
+ "sidebar.agents": "エージェント",
+ "sidebar.skills": "スキル",
+ "sidebar.connectors": "コネクター",
+ "sidebar.apps": "マイアプリ",
+ "sidebar.contexts": "ナレッジ",
+ "connectors.title": "コネクター",
+ "connectors.group.connected": "接続済み",
+ "connectors.group.available": "利用可能",
+ "connectors.empty": "利用可能なコネクターはありません。",
+ "connectors.action.connect": "接続",
+ "connectors.action.connecting": "接続中…",
+ "connectors.action.disconnect": "切断",
+ "connectors.action.unavailable": "近日公開",
+ "connectors.confirm_disconnect_title": "「{name}」を切断",
+ "connectors.confirm_disconnect_msg": "このコネクターが提供するツールは利用できなくなります。",
+ "connectors.status.error": "エラー",
+ "connectors.errors.connect_failed": "認証に失敗しました",
+ "connectors.errors.remove_failed": "アンインストールに失敗しました",
+ "common.save": "保存",
+ "common.more": "その他",
+ "common.loading": "読み込み中…",
+ "sidebar.conversations": "チャット",
+ "sidebar.conv_empty": "会話はまだありません",
+ "sidebar.projects": "プロジェクト",
+ "sidebar.project_create_title": "新規プロジェクト",
+ "sidebar.project_create_placeholder": "プロジェクト名を入力",
+ "sidebar.project_conv_empty": "(会話なし)",
+ "sidebar.settings": "設定",
+ "sidebar.settings_title": "設定",
+ "sidebar.devtools": "開発ツール",
+ "sidebar.devtools_title": "開発モードでのみ表示",
+ "new_chat.title": "エージェントに指示して作業を進める",
+ "new_chat.subtitle": "質問やタスクを入力",
+ "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.recipient_label": "宛先: ",
+ "chat.recipient_commander": "コマンダー",
+ "chat.recipient_commander_hint": "デフォルトの宛先です。@ は不要です",
+ "chat.recipient_picker_title": "宛先を切り替え(コマンダー / エージェント)",
+ "chat.project_label": "プロジェクト: ",
+ "chat.project_none": "なし",
+ "chat.project_picker_title": "プロジェクトを選択",
+ "chat.attach_title": "添付ファイルをアップロード(テキスト / PDF / Word / 画像 / 動画)",
+ "chat.mic_title": "音声入力",
+ "chat.mic_stop_title": "録音を停止",
+ "chat.mic_error_permission": "マイクへのアクセスがブロックされています。音声入力を使うにはシステム設定で許可してください。",
+ "chat.mic_error_unavailable": "現在、音声入力は利用できません。",
+ "chat.mic_login_required": "音声入力を使うにはサインインしてください。",
+ "chat.chip_remove_title": "削除",
+ "chat.send_title": "送信",
+ "chat.attach_uploading": "アップロード中",
+ "chat.lightbox_close_title": "閉じる",
+ "chat.attach_remove_title": "削除",
+ "chat.attach_unsupported": "{name}(未対応の形式)",
+ "chat.attach_upload_fail": "{name}({reason})",
+ "chat.attach_upload_generic_fail": "アップロードに失敗しました",
+ "chat.attach_rejected_prefix": "次のファイルはアップロードできませんでした:\n\n{list}",
+ "chat.new_conv_title": "新規会話",
+ "chat.conv_del_title": "削除",
+ "chat.conv_del_confirm": "この会話を削除しますか?",
+ "chat.loading": "読み込み中...",
+ "chat.load_failed": "読み込みに失敗しました: {msg}",
+ "chat.thinking": "考え中...",
+ "chat.thinking_short": "考え中",
+ "chat.plan_announce": "実行計画",
+ "plan.title": "実行計画",
+ "plan.toggle_title": "折りたたみ / 展開",
+ "plan.action.retry": "再試行",
+ "plan.action.skip": "スキップ",
+ "plan.action.abort": "計画を中止",
+ "plan.confirm.skip": "このステップをスキップしますか?後続はブロックされなくなりますが、このステップ自体は実行されません。",
+ "plan.confirm.abort": "計画全体を中止しますか?未完了のステップはすべて中止されます。",
+ "plan.error.retry_failed": "再試行に失敗しました: {reason}",
+ "plan.error.skip_failed": "スキップに失敗しました: {reason}",
+ "plan.error.abort_failed": "中止に失敗しました: {reason}",
+ "chat.from_commander": "コマンダー",
+ "chat.from_user": "ユーザー",
+ "chat.from_agent_unknown": "エージェント",
+ "chat.produced_reveal_title": "フォルダで表示",
+ "chat.produced_preview_title": "プレビュー",
+ "chat.preview_close_title": "閉じる",
+ "chat.preview_reveal_title": "フォルダで開く",
+ "chat.preview_unsupported_message": "アプリ内では {ext} ファイルをプレビューできません。保存先フォルダを開きますか?",
+ "chat.preview_unsupported_no_ext": "(拡張子なし)",
+ "chat.preview_too_large_message": "「{name}」は {size} MB で、プレビュー上限の {cap} MB を超えています。保存先フォルダを開きますか?",
+ "chat.preview_read_failed_message": "「{name}」を読み取れませんでした。保存先フォルダを開きますか?",
+ "chat.preview_unsupported_reveal": "フォルダを開く",
+ "chat.preview_cancel": "閉じる",
+ "chat.process_info": "プロセス情報",
+ "conversation_info.toggle_title": "会話情報",
+ "conversation_info.title": "会話情報",
+ "conversation_info.tab_tasks": "タスク",
+ "conversation_info.tab_files": "ファイル",
+ "conversation_info.tab_attachments": "添付ファイル",
+ "conversation_info.no_conversation": "会話を開くと詳細が表示されます",
+ "conversation_info.load_failed": "会話情報を読み込めませんでした: {reason}",
+ "conversation_info.empty_tasks": "タスクはまだありません",
+ "conversation_info.empty_steps": "ステップはありません",
+ "conversation_info.empty_files": "生成されたファイルはまだありません",
+ "conversation_info.empty_attachments": "添付ファイルはありません",
+ "conversation_info.task_plan_fallback": "実行計画",
+ "conversation_info.step_files": "ファイル",
+ "conversation_info.status.pending": "待機中",
+ "conversation_info.status.in_progress": "実行中",
+ "conversation_info.status.done": "完了",
+ "conversation_info.status.failed": "失敗",
+ "conversation_info.status.skipped": "スキップ済み",
+ "conversation_info.status.blocked": "入力待ち",
+ "artifact.title": "インタラクティブアプリ",
+ "artifact.reload": "再読み込み",
+ "artifact.more": "その他",
+ "artifact.menu_save": "保存",
+ "artifact.open_external": "ブラウザで開く",
+ "artifact.open_failed": "ブラウザで開けませんでした",
+ "artifact.result_prefix": "結果:",
+ "apps.title": "作成したアプリ",
+ "apps.empty": "保存済みアプリはまだありません。会話でインタラクティブアプリを作成し、カードの ⋯ → 保存 から追加できます。",
+ "apps.open_hint": "既定のブラウザで開く",
+ "apps.open_failed": "ブラウザで開けませんでした",
+ "apps.edit": "編集",
+ "apps.edit_conv_title": "「{name}」を編集",
+ "apps.edit_seed": "インタラクティブアプリ「{name}」を変更したいです。完全なソースは添付ファイル「{file}」にあります。次の変更を行ってください:\n\n",
+ "apps.edit_failed": "編集用の会話を開けませんでした",
+ "apps.rename": "名前を変更",
+ "apps.rename_prompt": "新しい名前:",
+ "apps.rename_failed": "アプリ名を変更できませんでした",
+ "apps.delete": "削除",
+ "apps.delete_confirm": "「{name}」を削除しますか?この操作は元に戻せません。",
+ "apps.delete_failed": "アプリを削除できませんでした",
+ "apps.more": "その他",
+ "apps.source_hint": "会話から作成",
+ "apps.saved_toast": "マイアプリに保存しました",
+ "apps.save_failed": "アプリを保存できませんでした",
+ "chat.archive_btn_title": "ナレッジベースに保存",
+ "chat.archive_btn": "ナレッジ",
+ "chat.archive_done": "保存しました",
+ "chat.archive_failed": "保存に失敗しました",
+ "chat.archive_failed_with_reason": "保存に失敗しました: {reason}",
+ "chat.copy_btn_title": "最終回答をクリップボードにコピー",
+ "chat.copy_btn": "コピー",
+ "chat.copy_done": "コピーしました",
+ "chat.copy_failed": "コピーに失敗しました",
+ "chat.quote_btn_title": "このメッセージを引用して対象エージェントへ送信",
+ "chat.quote_btn": "引用",
+ "chat.quote_from": "@{name} からの引用:",
+ "chat.quote_remove_title": "引用を削除",
+ "chat.quote_files_label": "添付ファイル(read_file で直接読み取り可能):",
+ "chat.attach_still_uploading": "添付ファイルのアップロード中です。送信前に完了をお待ちください。",
+ "chat.create_conv_failed": "会話の作成に失敗しました",
+ "chat.create_conv_failed_with_reason": "会話の作成に失敗しました: {reason}",
+ "chat.attach_adopt_failed": "添付ファイルの取り込みに失敗しました: {reason}",
+ "chat.attach_queue_blocked": "返信が進行中のため、添付ファイルはキューに入れられません。返信完了を待つか、添付ファイルを削除してからキューに入れてください。",
+ "chat.send_failed": "送信に失敗しました: {msg}",
+ "chat.interrupted": "中断されました",
+ "chat.stream_done": "● 生成完了",
+ "chat.tool_result_expand_hint": "クリックして出力全体を表示",
+ "chat.form.title": "パラメーターを確認",
+ "chat.form.submit": "確認",
+ "chat.form.reset": "リセット",
+ "chat.form.required_text": "この項目は空にできません",
+ "chat.form.required_select": "選択してください",
+ "chat.form.required_multiselect": "少なくとも 1 つ選択してください",
+ "chat.form.required_file": "ファイルを選択してください",
+ "chat.form.required_directory": "ディレクトリを選択してください",
+ "chat.form.file_pick": "ファイルを選択",
+ "chat.form.file_pick_multi": "ファイルを選択(複数)",
+ "chat.form.file_uploading": "アップロード中…",
+ "chat.form.file_failed": "失敗",
+ "chat.form.file_uploading_wait": "ファイルのアップロード完了を待ってください",
+ "chat.form.num_min": "{min} 以上である必要があります",
+ "chat.form.num_max": "{max} 以下である必要があります",
+ "chat.form.errors_prefix": "「{label}」{msg}",
+ "chat.form.boolean_on": "オン",
+ "chat.form.empty_value": "(空)",
+ "chat.form.submitted_no_time": "送信済み",
+ "chat.form.submitted_at": "送信済み · {time}",
+ "chat.form.readonly_title": "パラメーター確認済み",
+ "chat.form.streaming_placeholder": "パラメーターフォームを準備中…",
+ "chat.form.unknown_type": "(不明なフィールドタイプ: {type})",
+ "chat.form.submit_failed": "送信に失敗しました",
+ "chat.stream_generating": "◐ 生成中: ",
+ "chat.stream_interrupted_line": "◯ 中断されました",
+ "chat.queue_drag_title": "ドラッグで並べ替え",
+ "chat.queue_edit": "編集",
+ "chat.queue_save": "保存",
+ "chat.queue_cancel": "キャンセル",
+ "chat.stop_reply": "返信を停止",
+ "chat.replying": "返信中...",
+ "chat.input_placeholder_queue": "返信中です。Enter でメッセージをキューに追加…",
+ "chat.status.replying_short": "返信中",
+ "chat.status.pending_short": "キュー済み",
+ "chat.unknown_error": "不明なエラー",
+ "chat.upload_failed": "アップロードに失敗しました",
+ "chat.reply_interrupted": "モデルの応答が中断されました。メッセージを再送してください。",
+ "chat.reply_timeout": "モデルの応答がタイムアウトしました(サービスが再起動した可能性があります)。メッセージを再送してください。",
+ "ai_select.placeholder": "— 選択 —",
+ "ai_select.empty": "(選択肢なし)",
+ "chat.stream.phase_start": "開始",
+ "chat.stream.phase_end": "完了",
+ "chat.stream.reasoning_start": "推論を開始しました",
+ "chat.stream.reasoning_done": "推論が完了しました",
+ "chat.stream.reasoning_error": "推論エラー",
+ "chat.stream.reasoning_error_with": "推論エラー — {msg}",
+ "chat.stream.lifecycle": "▪ ライフサイクル {p}",
+ "chat.stream.thinking": "考え中",
+ "chat.stream.plan_with_steps": "計画({n} ステップ): {titles}",
+ "chat.stream.plan": "計画 {p}",
+ "chat.stream.command_empty": "(出力なし)",
+ "chat.stream.patch": "ファイル変更",
+ "chat.stream.approval": "承認待ち",
+ "chat.stream.approval_with": "承認待ち: {p}",
+ "chat.stream.error": "エラー: {msg}",
+ "chat.stream.attachment_skipped": "◯ 添付ファイルをスキップ: {items}",
+ "chat.create_agent_btn": "エージェントを作成",
+ "chat.create_agent_inline": "上記をエージェントにまとめる",
+ "chat.create_agent_message": "上記の会話を新しいエージェントにまとめてください。",
+ "chat.created_agent_chip": "エージェントを開く: {name}",
+ "chat.created_skill_chip": "スキルを開く: {name}",
+ "chat.create_agent_failed": "エージェントの作成に失敗しました: {reason}",
+ "chat.create_agent_streaming_placeholder": "エージェント設定を組み立てています…",
+ "chat.create_skill_streaming_placeholder": "スキルファイルを組み立てています…",
+ "chat.skill_file_streaming_placeholder": "{path} を書き込み中…",
+ "chat.skill_file_streaming_placeholder_unknown": "ファイルを書き込み中…",
+ "skills.title": "スキル",
+ "skills.add": "+ 追加",
+ "skills.more_btn": "その他",
+ "skills.custom_group": "カスタム",
+ "skills.builtin_group": "プラットフォーム",
+ "skills.empty": "スキルはまだありません",
+ "skills.use": "使用",
+ "skills.edit": "編集",
+ "skills.delete": "アンインストール",
+ "skills.use_tooltip": "このスキルを使用",
+ "skills.more_actions": "その他の操作",
+ "skills.back": "スキルに戻る",
+ "common.back": "戻る",
+ "skills.label_summary": "概要",
+ "skills.label_extra": "その他の属性",
+ "skills.label_usage": "使い方",
+ "skills.label_source": "ソースを表示",
+ "skills.no_desc": "(説明なし)",
+ "skills.clear_chat": "クリア",
+ "skills.clear_chat_title": "このスキルの編集チャットをクリア",
+ "skills.chat_input_placeholder": "変更内容を説明...",
+ "skills.use_prefix": "{skill} スキルを使用: {content}",
+ "skills.rename_title": "クリックして名前を変更",
+ "skills.source_custom": "カスタム",
+ "skills.source_builtin": "組み込み",
+ "skills.name_invalid": "名前は英字で始めてください。使用可能: 英数字、アンダースコア、ハイフン、単一の内部スペース",
+ "skills.desc_unset": "(説明なし)",
+ "skills.loading": "読み込み中...",
+ "skills.load_failed": "読み込みに失敗しました",
+ "skills.saving": "保存中…",
+ "skills.unknown_error": "不明なエラー",
+ "skills.saved": "保存しました",
+ "skills.save_failed_with": "保存に失敗しました: {reason}",
+ "skills.editing": "編集中…",
+ "skills.rename_prompt": "新しいスキル名(英字で始め、数字、-、_、単一スペースを使用可)",
+ "skills.rename_failed": "名前の変更に失敗しました: {reason}",
+ "skills.network_error": "ネットワークエラー: {reason}",
+ "skills.network_error_plain": "ネットワークエラー",
+ "skills.edit_btn_done": "完了",
+ "skills.edit_btn_edit": "編集",
+ "skills.help_finish_seed": "このスキルを完成させるのを手伝って",
+ "skills.clear_confirm": "このスキルの編集チャットをクリアしますか?ファイルは変更されません。",
+ "skills.modal_edit_title": "スキルを編集",
+ "skills.modal_new_title": "新規スキル",
+ "skills.input_name_needed": "名前を入力してください",
+ "skills.input_desc_needed": "説明を入力してください",
+ "skills.save_failed": "保存に失敗しました",
+ "skills.delete_confirm": "スキル「{name}」とその全ファイルをアンインストールしますか?",
+ "skills.delete_failed_with": "アンインストールに失敗しました: {reason}",
+ "skills.promote_to_builtin": "組み込みにする(開発)",
+ "skills.promote_confirm": "カスタムスキル「{name}」を組み込みに昇格しますか?src/builtin と data/builtin の両方に書き込み、カスタムコピーは削除されます。",
+ "skills.promote_failed_with": "組み込み化に失敗しました: {reason}",
+ "agents.title": "エージェント",
+ "agents.create_btn": "+ 作成",
+ "agents.more_btn": "その他",
+ "agents.empty": "エージェントはまだありません",
+ "agents.custom_group": "カスタム",
+ "agents.builtin_group": "プラットフォーム",
+ "agents.back": "エージェントに戻る",
+ "agents.use": "使用",
+ "agents.use_tooltip": "このエージェントを使用",
+ "agents.more_actions": "その他の操作",
+ "agents.edit": "編集",
+ "agents.delete": "アンインストール",
+ "agents.label_desc": "概要",
+ "agents.label_runtime": "外部エージェント",
+ "agents.label_workflow": "ワークフロー",
+ "agents.clear_chat": "クリア",
+ "agents.clear_chat_title": "このエージェントの編集チャットをクリア",
+ "agents.chat_input_placeholder": "調整内容を説明...",
+ "agents.unnamed": "無題",
+ "agents.source_builtin": "組み込み",
+ "agents.source_custom": "カスタム",
+ "agents.placeholder_unset": "(未設定)",
+ "agents.edit_btn_done": "完了",
+ "agents.edit_btn_edit": "編集",
+ "agents.input_name_needed": "名前を入力してください",
+ "agents.input_desc_needed": "概要を入力してください",
+ "agents.name_reserved": "その名前はシステムで予約されています(コマンダー)。別の名前を選んでください。",
+ "agents.name_taken": "その名前は別のエージェントで使用されています。別の名前を選んでください。",
+ "agents.name_invalid": "名前に使用できるのは英数字、アンダースコア、ハイフン、CJK 文字、単一の内部スペースのみです",
+ "agents.name_too_long": "名前が長すぎます(最大 50 文字)",
+ "agents.ext_cli_needed": "先に外部エージェントを選択してください",
+ "agents.create_failed": "作成に失敗しました",
+ "agents.seed_workflow": "このエージェントを改善するのを手伝って",
+ "agents.network_error": "ネットワークエラー: {reason}",
+ "agents.delete_confirm": "このエージェントをアンインストールしますか?関連する会話も削除されます。",
+ "agents.delete_failed": "アンインストールに失敗しました",
+ "agents.delete_failed_with": "アンインストールに失敗しました: {reason}",
+ "agents.promote_to_builtin": "組み込みにする(開発)",
+ "agents.promote_confirm": "カスタムエージェント「{name}」を組み込みに昇格しますか?agent.json のみが src/builtin と data/builtin にコピーされます(meta/ と自己進化スキルは除外)。カスタムコピーは削除されます。",
+ "agents.promote_failed_with": "組み込み化に失敗しました: {reason}",
+ "agents.edit_chat_empty": "このエージェントをどう調整したいか教えてください",
+ "agents.clear_confirm": "このエージェントの編集チャットをクリアしますか?",
+ "agents.agent_not_found": "エージェントが見つかりません",
+ "agents.create_conv_failed": "会話の作成に失敗しました",
+ "agents.run_prefix": "@{name} 実行",
+ "agents.launch_failed": "起動に失敗しました: {reason}",
+ "agents.no_match": "一致するエージェントはありません",
+ "agents.schedule.menu": "スケジュール済みタスク",
+ "agents.schedule.dialog_title": "{name} · スケジュール済みタスク",
+ "agents.schedule.empty": "スケジュール済みタスクはまだありません",
+ "agents.schedule.add_btn": "+ 新規スケジュールタスク",
+ "agents.schedule.edit_btn": "編集",
+ "agents.schedule.delete_btn": "削除",
+ "agents.schedule.delete_confirm": "このスケジュール済みタスクを削除しますか?",
+ "agents.schedule.type_label": "繰り返し",
+ "agents.schedule.type_interval": "間隔",
+ "agents.schedule.type_daily": "毎日",
+ "agents.schedule.type_weekly": "毎週",
+ "agents.schedule.interval_label": "毎",
+ "agents.schedule.interval_unit": "分",
+ "agents.schedule.time_label": "時刻",
+ "agents.schedule.weekdays_label": "曜日",
+ "agents.schedule.weekday.0": "日",
+ "agents.schedule.weekday.1": "月",
+ "agents.schedule.weekday.2": "火",
+ "agents.schedule.weekday.3": "水",
+ "agents.schedule.weekday.4": "木",
+ "agents.schedule.weekday.5": "金",
+ "agents.schedule.weekday.6": "土",
+ "agents.schedule.default_input_label": "デフォルト入力",
+ "agents.schedule.default_input_placeholder": "各実行時にエージェントへ送信されます(任意)",
+ "agents.schedule.title_label": "タスクタイトル(任意)",
+ "agents.schedule.title_placeholder": "新しい会話タイトルとして使用されます。既定は {name}",
+ "agents.schedule.enabled_label": "有効",
+ "agents.schedule.save_btn": "保存",
+ "agents.schedule.cancel_btn": "キャンセル",
+ "agents.schedule.close_btn": "閉じる",
+ "agents.schedule.summary_interval": "{minutes} 分ごと",
+ "agents.schedule.summary_daily": "毎日 {time}",
+ "agents.schedule.summary_weekly": "{days} {time}",
+ "agents.schedule.last_run": "前回: {when}",
+ "agents.schedule.never_run": "未実行",
+ "agents.schedule.invalid_interval": "間隔は 1 から 43200 分の間で指定してください",
+ "agents.schedule.invalid_time": "有効な時刻を入力してください(HH:MM)",
+ "agents.schedule.invalid_weekdays": "少なくとも 1 つの曜日を選択してください",
+ "agents.schedule.save_failed": "保存に失敗しました: {reason}",
+ "agents.schedule.delete_failed": "削除に失敗しました: {reason}",
+ "agents.schedule.load_failed": "読み込みに失敗しました: {reason}",
+ "contexts.editor_empty": "左側でファイルを選択してください",
+ "contexts.kb.pending": "キュー済み",
+ "contexts.kb.processing": "ベクトル化中…",
+ "contexts.kb.failed": "ベクトル化に失敗しました。クリックして再試行",
+ "contexts.kb.reprocess_failed": "再処理に失敗しました",
+ "contexts.kb.reprocess_failed_with": "再処理に失敗しました: {reason}",
+ "contexts.title": "ナレッジベース",
+ "contexts.empty": "ナレッジベースは空です",
+ "contexts.root_label": "ルート",
+ "contexts.menu.more_actions": "その他の操作",
+ "contexts.menu.new_text": "新規テキストファイル",
+ "contexts.menu.new_todo": "新規 Todo リスト",
+ "contexts.menu.new_folder": "新規フォルダ",
+ "contexts.menu.upload": "ファイルをアップロード",
+ "contexts.menu.rename": "名前を変更",
+ "contexts.menu.delete": "削除",
+ "contexts.menu.edit": "編集",
+ "contexts.menu.open_in_system": "システムで開く",
+ "contexts.dnd.invalid_self": "自分自身または配下のフォルダへは移動できません",
+ "contexts.dir.del_confirm": "フォルダ「{rel}」とその中身をすべて削除しますか?この操作は元に戻せません。",
+ "contexts.dir.create_failed": "フォルダの作成に失敗しました",
+ "contexts.file.del_confirm": "ファイル「{rel}」を削除しますか?",
+ "contexts.file.create_failed": "ファイルの作成に失敗しました",
+ "contexts.entry.rename_bad_name": "無効な名前です(/ または .. は使用できません)",
+ "contexts.entry.rename_failed": "名前の変更に失敗しました",
+ "contexts.entry.rename_failed_with": "名前の変更に失敗しました: {reason}",
+ "contexts.new.modal_title_dir": "新規フォルダ",
+ "contexts.new.target": "場所: {rel}",
+ "contexts.new.dir_name": "フォルダ名",
+ "contexts.new.name_needed": "名前は必須です",
+ "contexts.new.bad_chars": "名前に / \\ または .. は使用できません",
+ "contexts.new.untitled_stem": "無題",
+ "contexts.new.todo_stem": "Todo リスト",
+ "contexts.new.todo_template_heading": "Todo",
+ "contexts.read_failed": "読み込みに失敗しました",
+ "contexts.read_failed_with": "読み込みに失敗しました: {reason}",
+ "contexts.save_failed": "保存に失敗しました",
+ "contexts.save_failed_with": "保存に失敗しました: {reason}",
+ "contexts.delete_failed": "削除に失敗しました",
+ "contexts.delete_failed_with": "削除に失敗しました: {reason}",
+ "contexts.network_error": "ネットワークエラー: {reason}",
+ "contexts.upload_failed": "アップロードに失敗しました: {name}",
+ "contexts.upload_rejected": "次のファイルは未対応の形式です({exts}):\n{list}",
+ "contexts.upload.in_progress": "{count} 個のファイルをアップロード中…",
+ "contexts.viewer.edit": "編集",
+ "contexts.viewer.delete": "削除",
+ "contexts.viewer.save": "保存",
+ "contexts.viewer.cancel": "キャンセル",
+ "contexts.viewer.open_system": "システムで開く",
+ "contexts.viewer.kind_pdf": "PDF",
+ "contexts.viewer.kind_docx": "Word 文書",
+ "contexts.viewer.kind_other": "ファイル",
+ "contexts.viewer.binary_hint": "{kind} はここではプレビューできません。システム既定のアプリで開きました。",
+ "contexts.viewer.docx_empty": "文書は空です。",
+ "contexts.editor.tb.h1": "見出し 1",
+ "contexts.editor.tb.h2": "見出し 2",
+ "contexts.editor.tb.h3": "見出し 3",
+ "contexts.editor.tb.bold": "太字 (Ctrl/Cmd+B)",
+ "contexts.editor.tb.italic": "斜体 (Ctrl/Cmd+I)",
+ "contexts.editor.tb.strike": "取り消し線",
+ "contexts.editor.tb.ul": "箇条書き",
+ "contexts.editor.tb.ol": "番号付きリスト",
+ "contexts.editor.tb.quote": "引用",
+ "contexts.editor.tb.code": "インラインコード",
+ "contexts.editor.tb.codeblock": "コードブロック",
+ "contexts.editor.tb.link": "リンク (Ctrl/Cmd+K)",
+ "contexts.editor.tb.image": "画像",
+ "contexts.editor.tb.todo": "Todo",
+ "contexts.editor.tb.preview": "プレビュー",
+ "contexts.editor.tb.edit_back": "編集に戻る",
+ "contexts.editor.placeholder.bold": "太字テキスト",
+ "contexts.editor.placeholder.italic": "斜体テキスト",
+ "contexts.editor.placeholder.strike": "取り消し線",
+ "contexts.editor.placeholder.heading": "見出し",
+ "contexts.editor.placeholder.list_item": "リスト項目",
+ "contexts.editor.placeholder.quote": "引用テキスト",
+ "contexts.editor.placeholder.code": "コード",
+ "contexts.editor.placeholder.link_text": "リンクテキスト",
+ "contexts.editor.placeholder.link_url": "https://",
+ "contexts.editor.placeholder.image_alt": "画像の代替テキスト",
+ "contexts.editor.placeholder.image_url": "https://",
+ "contexts.editor.placeholder.todo": "タスク",
+ "contexts.editor.preview_empty": "(空です。入力してからプレビューに切り替えると表示を確認できます)",
+ "contexts.todo.save_failed": "チェック状態を保存できませんでした: {reason}",
+ "contexts.reveal_failed": "ファイルを開けませんでした",
+ "contexts.reveal_failed_with": "ファイルを開けませんでした: {reason}",
+ "kb_picker.title": "ナレッジへ保存",
+ "kb_picker.name": "名前",
+ "kb_picker.name_hint": "ファイル名を入力してください",
+ "kb_picker.name_needed": "名前は必須です",
+ "kb_picker.name_bad_chars": "名前に / \\ または .. は使用できません",
+ "kb_picker.name_too_long": "ファイル名が長すぎます: 「{name}」。約 100 ASCII 文字または約 50 CJK 文字以内にしてください。",
+ "kb_picker.folder": "フォルダ",
+ "kb_picker.target": "保存先: {rel}",
+ "chat.archive_picker_title": "メッセージをナレッジベースに保存",
+ "settings.title": "設定",
+ "settings.tab.account": "アカウント",
+ "settings.tab.data": "データ",
+ "settings.tab.general": "一般",
+ "settings.tab.credentials": "認証情報",
+ "settings.account.signed_out_hint": "サインインしていません。複数デバイス同期とリモートバックアップにはログインが必要です。",
+ "settings.section.cloud": "クラウド",
+ "settings.section.local": "ローカル",
+ "settings.sync.title": "クラウド同期",
+ "settings.sync.pro_badge": "Pro",
+ "settings.sync.pro_required": "クラウド同期は Pro 機能です。登録すると会話、エージェント、スキル、ナレッジを複数デバイスで同期できます。",
+ "settings.sync.grace_warning": "クラウド同期が一時停止しています。{date} にクラウドデータが削除されます。保持するには再登録してください。",
+ "settings.sync.storage_title": "ストレージ",
+ "settings.sync.conflicts_title": "競合ログ",
+ "settings.sync.conflicts_sub": "2 台のデバイスが同じファイルを同時に編集した場合、上書きされた版をここに保持します。",
+ "settings.sync.toggle_enable": "クラウド同期を有効にする",
+ "settings.sync.disable_title": "クラウド同期をオフにする",
+ "settings.sync.disable_message": "このデバイスは同期を停止します。\n別のデバイスでもクラウド同期が有効な場合、クラウドデータの削除はそのローカルコピーにも影響します。慎重に選択してください。",
+ "settings.sync.disable_keep_cloud": "クラウドデータを保持",
+ "settings.sync.disable_purge_cloud": "クラウドデータを削除",
+ "settings.sync.disabling": "クラウドデータを削除して無効化中…",
+ "settings.sync.disable_failed": "無効化に失敗しました: {error}",
+ "settings.sync.retry": "再試行",
+ "settings.sync.state_paused_disabled": "無効",
+ "settings.sync.state_paused_other_device_syncing": "別のデバイスが同期中",
+ "settings.sync.state_paused_mass_delete_pending": "削除の確認",
+ "settings.sync.mass_delete_title": "多数のローカル削除を検出しました",
+ "settings.sync.mass_delete_summary": "クラウドから ",
+ "settings.sync.mass_delete_summary_tail": " 個のファイルを削除しようとしています。意図した操作か確認してください。",
+ "settings.sync.mass_delete_confirm": "削除を確認",
+ "settings.sync.mass_delete_cancel": "キャンセルして復元",
+ "settings.sync.btn_sync_now": "今すぐ同期",
+ "settings.sync.state_idle": "最新です",
+ "settings.sync.state_syncing": "同期中…",
+ "settings.sync.state_error": "同期に失敗しました",
+ "settings.sync.state_paused_login_required": "有効にするにはサインイン",
+ "settings.sync.state_paused_quota_full": "容量上限に達しました",
+ "settings.sync.state_paused_offline": "オフライン",
+ "settings.sync.state_paused_version_outdated": "アプリの更新が必要です",
+ "settings.sync.version_outdated_hint": "同期を再開するにはアプリを最新バージョンに更新してください。",
+ "settings.sync.last_sync": "最終同期: ",
+ "settings.sync.just_now": "たった今",
+ "settings.sync.uploading": "アップロード",
+ "settings.sync.downloading": "ダウンロード",
+ "settings.sync.conflicts_summary": "競合ログ",
+ "settings.sync.conflicts_empty": "競合はありません",
+ "settings.sync.group_conversations": "会話",
+ "settings.sync.group_kb": "ナレッジベース",
+ "settings.sync.group_agents": "エージェント",
+ "settings.sync.group_skills": "スキル",
+ "settings.sync.group_apps": "アプリ",
+ "settings.sync.group_other": "その他",
+ "settings.sync.privacy_note": "HTTPS で暗号化され、プライベートクラウドストレージに保存されます。アクセスできるのはあなたのアカウントだけです。",
+ "settings.sync.error_generic": "同期に失敗しました",
+ "settings.sync.error_network": "ネットワークエラーです。接続を確認して再試行してください",
+ "settings.sync.error_quota_full": "クラウドストレージがいっぱいです",
+ "settings.section.general": "一般",
+ "settings.section.models": "モデルと認証情報",
+ "settings.section.models_note": "API キーと OAuth トークンはローカルにのみ保存され、同期や外部送信はされません。",
+ "settings.section.tools": "ツール機能",
+ "settings.section.tools_note": "検索と画像生成の API キーはローカルにのみ保存され、同期や外部送信はされません。",
+ "settings.delete": "削除",
+ "settings.search.title": "検索 API キー",
+ "settings.search.sub": "優先順位: 有料 API > モデルネイティブ検索 > 組み込みのキー不要スクレイパー。",
+ "settings.search.provider": "プロバイダー",
+ "settings.search.api_key": "API キー",
+ "settings.search.add": "+ 検索キーを追加",
+ "settings.search.pick_provider": "— 検索プロバイダーを選択 —",
+ "settings.search.error_provider_needed": "先に検索プロバイダーを選択してください",
+ "settings.search.error_key_needed": "先に API キーを貼り付けてください",
+ "settings.search.adding": "追加中…",
+ "settings.search.add_ok": "追加しました",
+ "settings.search.add_failed": "追加に失敗しました",
+ "settings.search.empty": "検索 API キーはまだ設定されていません(組み込みのキー不要スクレイパーを使用します)。",
+ "settings.search.active_tag": "有効",
+ "settings.search.confirm_delete": "{provider} の検索 API キーを削除しますか?",
+ "settings.image.title": "画像生成 API キー",
+ "settings.image.sub": "generate_image ツール用の API です。OpenAI または Google 向けのチャットキーがある場合はそれを再利用します。",
+ "settings.image.provider": "プロバイダー",
+ "settings.image.api_key": "API キー",
+ "settings.image.add": "+ 画像キーを追加",
+ "settings.image.pick_provider": "— 画像プロバイダーを選択 —",
+ "settings.image.error_provider_needed": "先に画像プロバイダーを選択してください",
+ "settings.image.error_key_needed": "先に API キーを貼り付けてください",
+ "settings.image.adding": "追加中…",
+ "settings.image.add_ok": "追加しました",
+ "settings.image.add_failed": "追加に失敗しました",
+ "settings.image.empty": "画像生成 API キーはまだありません(チャット側の OpenAI / Google キーがあれば再利用します)。",
+ "settings.image.active_tag": "有効",
+ "settings.image.confirm_delete": "{provider} の画像 API キーを削除しますか?",
+ "settings.section.data": "データ",
+ "settings.section.data_note": "ローカルデータのメンテナンス操作です。元に戻せません。",
+ "settings.clear_all_convs.title": "すべての会話を削除",
+ "settings.clear_all_convs.sub": "すべての会話を削除します。スキルとエージェントは変更されません。",
+ "settings.clear_all_convs.btn": "すべての会話を削除",
+ "settings.clear_all_convs.confirm": "{count} 件の会話を完全に削除しますか?この操作は元に戻せません。",
+ "settings.clear_all_convs.empty": "削除する会話はありません。",
+ "settings.clear_all_convs.in_progress": "削除中…",
+ "settings.clear_all_convs.success": "{count} 件の会話を削除しました。",
+ "settings.clear_all_convs.failed": "一括削除に失敗しました: {message}",
+ "settings.language.title": "言語 / Language",
+ "settings.add_auth_title": "モデル認証を追加",
+ "settings.add_auth_sub": "プロバイダーとモデルを選択し、API キーまたは OAuth アカウントを追加します。",
+ "settings.provider": "プロバイダー",
+ "settings.model": "モデル",
+ "settings.add_account": "+ アカウントを追加",
+ "settings.configured_title": "設定済み(優先順)",
+ "settings.configured_sub": "先頭の項目がデフォルトモデルです。後続はフォールバック順です。ドラッグで並べ替えできます。",
+ "settings.loading": "読み込み中…",
+ "settings.picker.recommended_suffix": "(推奨)",
+ "provider.moonshot.note_paygo": "Moonshot Open Platform の従量課金アカウント",
+ "provider.kimi_coding.note_subscription": "Moonshot Coding Plan の月額サブスクリプションが必要です",
+ "settings.picker.select_provider": "— プロバイダーを選択 —",
+ "settings.picker.select_model": "— モデルを選択 —",
+ "settings.picker.pick_provider_first": "(先にプロバイダーを選択)",
+ "settings.picker.error_provider_needed": "プロバイダーを選択してください",
+ "settings.picker.error_model_needed": "モデルを選択してください",
+ "settings.picker.error_provider_missing": "プロバイダーが見つかりません",
+ "settings.oauth.support_api_and_oauth": "API キーと OAuth",
+ "settings.oauth.support_api_only": "API キーのみ",
+ "settings.oauth.support_oauth_only": "OAuth のみ",
+ "settings.modal.add_account_title": "アカウントを追加",
+ "settings.modal.add_account_title_with_provider": "アカウントを追加 · {provider}",
+ "settings.modal.method_api_title": "API キー",
+ "settings.modal.method_api_hint": "プロバイダーのコンソールで作成したキーを貼り付けます",
+ "settings.modal.method_oauth_title": "OAuth サインイン",
+ "settings.modal.method_oauth_hint": "ブラウザで既存アカウントにサインインします(例: Claude Pro / ChatGPT)",
+ "settings.modal.api_key_form_title": "API キーを追加 · {provider}",
+ "settings.modal.label": "ラベル",
+ "settings.modal.label_placeholder": "任意。例: default / work / personal",
+ "settings.modal.docs_prefix": "{url} で作成",
+ "settings.save": "保存",
+ "settings.save_loading": "保存中…",
+ "settings.paste_key_first": "先に API キーを貼り付けてください",
+ "settings.save_failed": "保存に失敗しました",
+ "settings.add_entry_failed": "認証情報の追加に失敗しました",
+ "settings.oauth.title_prefix": "OAuth サインイン · {provider}",
+ "settings.oauth.alias_tip": "注意: サインインは {provider} 経由で行われます。",
+ "settings.oauth.starting": "認証フローを開始中…",
+ "settings.oauth.processing": "処理中…",
+ "settings.oauth.start_failed": "OAuth フローの開始に失敗しました",
+ "settings.oauth.top_hint_browser": "システムブラウザを開きました。そちらで認証を完了してください。",
+ "settings.oauth.top_hint_page": "認証ページを開きました。ブラウザで下のコードを入力してサインインを完了してください。",
+ "settings.oauth.sub_hint_callback": "成功すると Orkas が認証情報を自動で受け取ります。ブラウザから戻らない場合は、アドレスバーのコールバック URL 全体をコピーしてここに貼り付けてください。",
+ "settings.oauth.sub_hint_devicecode": "Orkas が認証情報を自動でポーリングします。この画面に戻る必要はありません。",
+ "settings.oauth.reopen": "もう一度開く",
+ "settings.oauth.copy_link": "リンクをコピー",
+ "settings.oauth.manual_placeholder": "コールバック URL または認証コードを貼り付け(任意、自動復帰に失敗した場合)",
+ "settings.oauth.submit": "送信",
+ "settings.oauth.submitting": "送信済み、処理中…",
+ "settings.oauth.enter_prompt_fallback": "値を入力してください",
+ "settings.oauth.success_writing": "認証済み。項目を書き込み中…",
+ "settings.oauth.auth_failed": "認証に失敗しました",
+ "settings.entries.empty": "モデル認証はまだ設定されていません。上のセレクターから最初の認証を追加してください。",
+ "settings.entries.drag_title": "ドラッグで並べ替え",
+ "settings.entries.default_tag": "デフォルト",
+ "settings.entries.account_title": "アカウントラベル",
+ "settings.entries.oauth_badge": "OAuth",
+ "settings.entries.oauth_expired": "OAuth · 期限切れ",
+ "settings.entries.test": "テスト",
+ "settings.entries.testing": "テスト中…",
+ "settings.entries.conn_ok": "接続済み {ms}",
+ "settings.entries.conn_failed": "接続に失敗しました",
+ "settings.entries.delete_confirm": "認証「{title}」を削除しますか?\n\nこの認証に紐づくローカル認証情報も削除されます。使用するには再認証が必要です。",
+ "settings.entries.switch_model_failed": "モデルの切り替えに失敗しました",
+ "settings.entries.reorder_failed": "並べ替えに失敗しました",
+ "settings.entries.delete_failed": "削除に失敗しました",
+ "settings.commander_avatar.title": "コマンダーのアバター",
+ "settings.commander_avatar.sub": "アバターをクリックして新しいアイコンと色を選択します。",
+ "settings.commander_avatar.hint": "左のアバターをクリックして変更",
+ "avatar.icon_label": "アイコン",
+ "avatar.color_label": "色",
+ "avatar.change": "アバターを変更",
+ "avatar.icon.crown": "王冠",
+ "avatar.icon.sparkle": "きらめき",
+ "avatar.icon.rocket": "ロケット",
+ "avatar.icon.brain": "脳",
+ "avatar.icon.bulb": "電球",
+ "avatar.icon.bot": "ロボット",
+ "avatar.icon.atom": "原子",
+ "avatar.icon.compass": "コンパス",
+ "avatar.icon.leaf": "葉",
+ "avatar.icon.flame": "炎",
+ "avatar.icon.star": "星",
+ "avatar.icon.bolt": "稲妻",
+ "avatar.icon.target": "ターゲット",
+ "avatar.icon.music": "音符",
+ "avatar.icon.code": "コード",
+ "avatar.icon.palette": "パレット",
+ "avatar.color.gold": "ゴールド",
+ "avatar.color.coral": "コーラル",
+ "avatar.color.mint": "ミント",
+ "avatar.color.lavender": "ラベンダー",
+ "avatar.color.peach": "ピーチ",
+ "avatar.color.sky": "スカイ",
+ "avatar.color.sunshine": "サンシャイン",
+ "avatar.color.rose": "ローズ",
+ "avatar.color.sage": "セージ",
+ "avatar.color.periwinkle": "ペリウィンクル",
+ "avatar.color.butter": "バター",
+ "avatar.color.blush": "ブラッシュ",
+ "avatar.color.cyan": "シアン",
+ "avatar.color.violet": "バイオレット",
+ "avatar.color.lime": "ライム",
+ "avatar.color.salmon": "サーモン",
+ "settings.localexec.title": "ローカル実行",
+ "settings.localexec.sub": "許可すると、エージェントはシェルコマンドの実行、ワークスペースファイルの読み書き、PDF 生成を行えます。許可がない場合、これらのツールは拒否されます。",
+ "settings.localexec.status_loading": "読み込み中…",
+ "settings.localexec.status_granted": "許可済み",
+ "settings.localexec.status_granted_with_date": "許可済み({date})",
+ "settings.localexec.status_revoked": "未許可",
+ "settings.localexec.status_revoked_with_date": "未許可(前回の取り消し {date})",
+ "settings.localexec.btn_grant": "ローカル実行を許可",
+ "settings.localexec.btn_revoke": "取り消す",
+ "settings.metacognition.title": "メタ認知レベルのエージェント自己進化",
+ "settings.metacognition.sub": "有効にすると、各エージェントは最近の実行結果を定期的に振り返り、学びを抽出して、次回より良く動けるように自身の振る舞いを調整します。タスクをこなすだけでなく「自分はうまくできているか、次はどう改善できるか」を考えるため、これをメタ認知と呼んでいます。自己レビューを止めるにはオフにしてください。",
+ "settings.metacognition.toggle": "有効にする",
+ "settings.metacognition.env_forced_off": "環境変数 ORKAS_METACOGNITION=0 により強制的にオフ",
+ "settings.data_root.title": "データディレクトリ",
+ "settings.data_root.sub": "すべてのデータはこのディレクトリ内に保存されます。クリックするとファイルマネージャーで開きます。",
+ "settings.data_root.open_tooltip": "ファイルマネージャーで開く",
+ "devtools.title": "開発ツール",
+ "devtools.subtitle": "開発モードのみ",
+ "devtools.sysinfo_title": "システム情報",
+ "devtools.copy_title": "テキストとしてコピー",
+ "devtools.copy": "コピー",
+ "devtools.relaunch_title": "再起動",
+ "devtools.relaunch_sub": "ローカルコードの変更を反映するため Orkas プロセスを再起動します",
+ "devtools.relaunch_btn": "再起動 (Cmd/Ctrl + Shift + R)",
+ "devtools.native_search_title": "モデルネイティブ Web 検索",
+ "devtools.native_search_sub": "有効にすると、対応モデルにサーバー側検索ツールを注入します。メモリ上のみで、再起動後は既定でオンになります。",
+ "devtools.native_search_toggle": "モデルネイティブ Web 検索を有効化(OpenAI / Anthropic / Google)",
+ "devtools.archives_title": "LLM 呼び出しアーカイブ",
+ "devtools.archives_sub": "直近 30 件の streamChatWithModel 呼び出し(入力 / 出力 / イベントを含む)",
+ "devtools.refresh": "更新",
+ "devtools.clear": "クリア",
+ "devtools.archives_empty": "(記録された呼び出しはありません)",
+ "devtools.archives_detail_empty": "左側で呼び出しを選択すると詳細を表示します",
+ "devtools.input_title": "ユーザー入力",
+ "devtools.events_title": "ストリームイベント",
+ "devtools.output_title": "モデル出力",
+ "devtools.context_title": "コンテキスト",
+ "devtools.tools_title": "利用可能なツール",
+ "devtools.copied": "コピーしました",
+ "devtools.copy_failed": "コピーに失敗しました: {reason}",
+ "devtools.relaunching": "再起動中…",
+ "devtools.relaunch_confirm": "Orkas を再起動しますか?",
+ "devtools.relaunch_failed": "再起動に失敗しました: {reason}",
+ "devtools.archives.empty": "(記録された呼び出しはありません)",
+ "devtools.archives.aborted": "中断",
+ "devtools.archives.error": "エラー",
+ "devtools.archives.ok": "OK",
+ "devtools.archives.duration": "{ms}ms",
+ "devtools.archives.clear_confirm": "すべての呼び出しアーカイブをクリアしますか?",
+ "devtools.archives.clear_failed": "クリアに失敗しました: {reason}",
+ "devtools.archives.refresh_failed": "更新に失敗しました: {reason}",
+ "devtools.archives.read_failed": "読み込みに失敗しました: {reason}",
+ "devtools.archives.clear_confirm2": "すべてのデバッグアーカイブをクリアしますか?この操作は元に戻せません。",
+ "devtools.archives.badge_kind_agent": "エージェント",
+ "devtools.archives.badge_kind_agent_title": "エージェント編集チャット",
+ "devtools.archives.badge_kind_skill": "スキル",
+ "devtools.archives.badge_kind_skill_title": "スキル編集チャット",
+ "devtools.archives.badge_kind_extract_img": "画像認識",
+ "devtools.archives.badge_kind_extract_img_title": "KB 画像認識",
+ "devtools.archives.badge_kind_cli": "CLI",
+ "devtools.archives.badge_kind_cli_title": "ローカル CLI エージェント実行",
+ "devtools.archives.status_error": "エラー",
+ "devtools.archives.status_aborted": "中断",
+ "devtools.archives.status_ok": "OK",
+ "devtools.archives.meta_start": "開始: {time}",
+ "devtools.archives.meta_duration": "所要時間: {s}秒",
+ "devtools.archives.meta_tokens": "トークン: 入力 {input} · 出力 {output}{cache}",
+ "devtools.archives.meta_cache_hit": " · キャッシュヒット {read}({pct}%)",
+ "devtools.archives.meta_cache_write": " · キャッシュ書き込み {write}",
+ "devtools.archives.meta_tokens_missing": "トークン: プロバイダーから報告されませんでした(pi-ai アダプターは 0 固定または usage 不明)",
+ "devtools.archives.prompt_empty": "(空)",
+ "devtools.archives.no_events": "(イベントなし)",
+ "devtools.archives.aborted_tag": "[中断]",
+ "devtools.archives.error_tag": "[エラー] {msg}",
+ "devtools.archives.context_empty": "(なし)",
+ "devtools.archives.context_skill_all": "すべてのスキル(許可リストなし)",
+ "devtools.archives.context_skill_none": "(空のセット、スキル 0 件)",
+ "devtools.archives.tools_empty": "(ツールなし、またはアップグレード前のアーカイブ)",
+ "devtools.archives.tools_source_extra": "呼び出し元注入(例: group_chat commander の plan_set / agent 管理ツール)",
+ "devtools.archives.tools_source_orkas": "Orkas 注入(上書き / 拡張)",
+ "devtools.archives.tools_source_core_agent": "core-agent 組み込み",
+ "agent_modal.title": "新規エージェント",
+ "agent_modal.tab_create": "作成",
+ "agent_modal.tab_external": "外部",
+ "agent_modal.name": "名前",
+ "agent_modal.category": "カテゴリ",
+ "agent_modal.name_placeholder": "例: コードレビューアシスタント",
+ "agent_modal.desc": "概要",
+ "agent_modal.desc_hint": "何をするかを 1 行で入力します。AI がワークフローを生成します",
+ "agent_modal.desc_placeholder": "例: コミット前にコードをレビューし、ロジックバグとセキュリティ問題に注目する...",
+ "agent_modal.ext_cli_label": "エージェント",
+ "agent_modal.ext_cli_none": "未選択",
+ "agent_modal.ext_name": "名前",
+ "agent_modal.ext_name_placeholder": "例: Claude Code",
+ "agent_modal.ext_desc": "概要",
+ "agent_modal.ext_desc_placeholder": "(CLI 選択時に自動入力。上書き可能)",
+ "agent_modal.runtime_cli_claude": "Claude Code",
+ "agent_modal.runtime_cli_codex": "Codex",
+ "agent_modal.runtime_cli_openclaw": "OpenClaw",
+ "agent_modal.runtime_cli_opencode": "OpenCode",
+ "agent_modal.runtime_cli_hermes": "Hermes",
+ "agent.external_word": "外部",
+ "agent.external_badge.claude": "外部 · Claude Code",
+ "agent.external_badge.codex": "外部 · Codex",
+ "agent.external_badge.openclaw": "外部 · OpenClaw",
+ "agent.external_badge.opencode": "外部 · OpenCode",
+ "agent.external_badge.hermes": "外部 · Hermes",
+ "agent.cli_missing": "外部エージェントがインストールされていません",
+ "input.dir.none": "(未設定)",
+ "input.dir.pick": "ディレクトリを選択…",
+ "input.dir.change": "変更…",
+ "input.dir.clear": "クリア",
+ "skill_modal.title_create": "新規スキル",
+ "skill_modal.title_edit": "スキルを編集",
+ "skill_modal.name": "名前(英語)",
+ "skill_modal.category": "カテゴリ",
+ "skill_modal.name_hint": "英字で始めてください。数字、-、_、単一スペースを使用できます",
+ "skill_modal.name_placeholder": "例: web-summary",
+ "skill_modal.description": "概要",
+ "skill_modal.desc_placeholder": "このスキルが何をし、いつ使うかを 1 行で...",
+ "skill_modal.tab_manual": "手動",
+ "skill_modal.tab_url": "URL から",
+ "skill_modal.tab_dir": "フォルダから",
+ "skill_modal.url": "URL",
+ "skill_modal.url_hint": "clawhub / GitHub / スキル紹介ページなど",
+ "skill_modal.url_placeholder": "https://...",
+ "skill_modal.dir": "ソースフォルダ",
+ "skill_modal.dir_hint": "最大 100 ファイル / 合計 50 MiB",
+ "skill_modal.dir_pick_btn": "フォルダを選択",
+ "skill_modal.dir_pick_failed": "フォルダの選択に失敗しました",
+ "skill_modal.dir_none": "(未選択)",
+ "skill_modal.err_url_invalid": "URL は http(s):// で始まる必要があります",
+ "skill_modal.err_dir_missing": "先にソースフォルダを選択してください",
+ "agent_picker.search_placeholder": "エージェントを検索...",
+ "add_account.title": "アカウントを追加",
+ "oauth_flow.title": "OAuth サインイン",
+ "oauth_flow.preparing": "認証を準備中…",
+ "search.input_placeholder": "チャットとナレッジベースを検索…",
+ "search.close_title": "閉じる (Esc)",
+ "search.empty_hint": "キーワードを入力して検索を開始",
+ "workspace.unselected": "未設定",
+ "workspace.chip_label": "ワークスペース: ",
+ "workspace.chip_title": "クリックしてワークスペースを選択",
+ "workspace.default_header": "デフォルト",
+ "workspace.recent_header": "最近使用",
+ "workspace.pick_folder": "フォルダを選択...",
+ "workspace.open_folder": "フォルダを開く...",
+ "workspace.scope_project": "プロジェクト「{name}」のワークスペース",
+ "workspace.scope_project_generic": "プロジェクトワークスペース",
+ "project.menu.more_actions": "その他の操作",
+ "project.menu.new_conv": "新規会話",
+ "project.menu.rename": "名前を変更",
+ "project.menu.delete": "削除",
+ "project.name_dup_inline": "同じ名前のプロジェクトがすでにあります",
+ "project.name_empty": "プロジェクト名は空にできません",
+ "project.error.generic": "操作に失敗しました。もう一度お試しください",
+ "project.delete_confirm_title": "プロジェクト「{name}」を削除しますか?",
+ "project.delete_confirm_body": "このプロジェクト内の {count} 件の会話も削除されます。この操作は元に戻せません。",
+ "project.delete_confirm_body_empty": "プロジェクト「{name}」を削除しますか?",
+ "project.delete_danger_label": "プロジェクト + {count} 件の会話を削除",
+ "project.delete_danger_label_empty": "プロジェクトを削除",
+ "project.has_running_conv": "このプロジェクト内の会話がまだ実行中です。削除する前に停止してください。",
+ "project.delete_failed_generic": "プロジェクトの削除に失敗しました。もう一度お試しください",
+ "project.back": "戻る",
+ "project.detail_load_failed": "プロジェクトを読み込めませんでした。削除された可能性があります。",
+ "project.action.new_conv": "新規チャット",
+ "project.action.rename": "名前を変更",
+ "project.action.delete": "削除",
+ "project.bindings.picker_search_placeholder": "名前または説明で検索",
+ "project.bindings.picker_no_match": "一致するものがありません。",
+ "agents.no_project_agents": "このプロジェクトに紐づくエージェントはありません。プロジェクトページを開いて追加してください。",
+ "project.bindings.agents_title": "エージェント",
+ "project.bindings.skills_title": "スキル",
+ "project.bindings.agents_desc": "プロジェクト内で使えるエージェントを追加します。",
+ "project.bindings.skills_desc": "プロジェクトの機能を拡張するスキルを追加します。",
+ "project.bindings.add_agent": "追加",
+ "project.bindings.add_skill": "追加",
+ "project.bindings.picker_title_agents": "プロジェクトにエージェントを追加",
+ "project.bindings.picker_title_skills": "プロジェクトにスキルを追加",
+ "project.bindings.picker_close": "閉じる",
+ "project.bindings.remove": "削除",
+ "project.bindings.empty_agents": "紐づくエージェントはありません。プロジェクト内で使うには追加してください。",
+ "project.bindings.empty_skills": "紐づくスキルはありません。プロジェクト内で使うには追加してください。",
+ "project.bindings.candidates_empty_agents": "追加できるエージェントはありません。",
+ "project.bindings.candidates_empty_skills": "追加できるスキルはありません。",
+ "project.bindings.stale": "削除済み",
+ "project.bindings.empty_in_chat": "このプロジェクトに紐づくエージェントはありません。プロジェクトページを開いて追加してください。",
+ "project.bindings.open_settings": "プロジェクトページを開く",
+ "search.history_title": "最近の検索",
+ "search.history_clear": "クリア",
+ "search.failed": "検索に失敗しました: {msg}",
+ "search.tab.all": "すべて",
+ "search.tab.chat": "チャット",
+ "search.tab.agent": "エージェント",
+ "search.tab.skill": "スキル",
+ "search.tab.context": "ナレッジ",
+ "search.section.chat": "チャット",
+ "search.section.agent": "エージェント",
+ "search.section.skill": "スキル",
+ "search.section.context": "ナレッジ",
+ "search.show_more": "さらに表示",
+ "search.scope.context": "ナレッジ",
+ "search.scope.chat": "会話",
+ "search.scope.agent": "エージェント",
+ "search.scope.skill": "スキル",
+ "search.source.custom": "カスタム",
+ "search.source.builtin": "組み込み",
+ "search.no_results": "「{query}」の結果はありません",
+ "search.role.user": "自分",
+ "search.role.ai": "AI",
+ "model_guard.banner": "モデルが設定されていないため、すべての機能が無効です。先に設定で API キーを追加するかサインインしてください。",
+ "model_guard.cta": "設定を開く",
+ "model_guard.modal": "モデルが設定されていないため、この機能は利用できません。\n\n先に設定で API キーを追加するかサインインしてください。",
+ "marketplace.title": "マーケットプレイス",
+ "marketplace.tab_agent": "エージェント",
+ "marketplace.tab_skill": "スキル",
+ "marketplace.all": "すべて",
+ "marketplace.install": "インストール",
+ "marketplace.installed": "インストール済み",
+ "marketplace.installing": "インストール中…",
+ "marketplace.uninstall": "アンインストール",
+ "marketplace.uninstalling": "アンインストール中…",
+ "marketplace.uninstall_ok": "アンインストールしました",
+ "marketplace.uninstall_failed": "アンインストールに失敗しました: {reason}",
+ "marketplace.search_ph": "検索",
+ "marketplace.search": "検索",
+ "marketplace.empty": "結果がありません",
+ "marketplace.load_failed": "マーケットプレイスの読み込みに失敗しました",
+ "marketplace.install_ok": "インストールしました",
+ "marketplace.install_failed": "インストールに失敗しました: {reason}",
+ "quality.install_rejected_title": "品質検証によりインストールが拒否されました: {name}",
+ "quality.level.EXTREME": "EXTREME",
+ "quality.level.MEDIUM": "MEDIUM",
+ "quality.level.LOW": "LOW",
+ "quality.empty": "指摘事項はありません。",
+ "marketplace.close": "閉じる",
+ "marketplace.back": "戻る",
+ "marketplace.version": "v{version}",
+ "marketplace.upload": "マーケットプレイスへアップロード(開発)",
+ "marketplace.upload_title": "マーケットプレイスへアップロード",
+ "marketplace.upload_category": "カテゴリ",
+ "marketplace.upload_version": "バージョン",
+ "marketplace.upload_submit": "アップロード",
+ "marketplace.upload_ok": "アップロードしました",
+ "marketplace.upload_failed": "アップロードに失敗しました: {reason}",
+ "marketplace.err_not_dev": "アップロードは開発ビルドでのみ利用できます。",
+ "marketplace.err_no_permission": "アップロード権限がありません(サーバー側の電話番号ホワイトリスト)。",
+ "marketplace.err_no_category": "先に作成ダイアログでカテゴリを設定してください。",
+ "marketplace.delete": "削除(開発)",
+ "marketplace.delete_confirm_title": "マーケットプレイス項目を削除",
+ "marketplace.delete_confirm_msg": "{kind}「{name}」を削除しますか?\nサーバー DB 行と COS blob が消去されます。この操作は元に戻せません。",
+ "marketplace.delete_ok": "削除しました",
+ "marketplace.delete_failed": "削除に失敗しました: {reason}",
+ "marketplace.deleting": "削除中…",
+ "marketplace.upload_version_prompt": "バージョンを入力",
+ "marketplace.upload_default_install": "既定でインストール(慎重に使用)",
+ "marketplace.upload_loading": "{kind} をプラットフォームへアップロード中…",
+ "marketplace.detail_loading": "詳細を読み込み中…",
+ "marketplace.list_loading": "マーケットプレイスを読み込み中…",
+ "marketplace.author_platform": "公式",
+ "marketplace.author_user": "{uid} 作成",
+ "marketplace.reconcile_running": "マーケットプレイスリソースを同期中 {pulled}/{total}…",
+ "marketplace.reconcile_partial": "マーケットプレイス同期が完了しました。{failed} 件が失敗し、次回起動時に再試行します",
+ "marketplace_request.kind_agent": "エージェント",
+ "marketplace_request.kind_skill": "スキル",
+ "marketplace_request.status_pending": "承認待ち",
+ "marketplace_request.status_installed": "インストール済み",
+ "marketplace_request.status_skipped": "スキップ済み",
+ "marketplace_request.status_failed": "失敗",
+ "marketplace_request.install": "インストール",
+ "marketplace_request.skip": "スキップ"
+}
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index b80abfee..60e9c553 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -16,6 +16,34 @@
"account.settings_title": "账号",
"account.settings_logout": "退出登录",
"account.settings_signed_in": "已登录",
+ "account.subscription_title": "会员",
+ "account.subscription_status_active": "续订时间",
+ "account.subscription_status_will_cancel": "到期时间",
+ "account.subscription_status_past_due": "扣款失败",
+ "account.subscription_status_expired": "会员已结束",
+ "account.subscription_status_free": "免费用户",
+ "account.subscription_status_coming_soon": "Pro 即将上线",
+ "account.subscription_detail_active": "云端同步与语音输入已解锁。",
+ "account.subscription_detail_will_cancel": "本期内仍可使用全部 Pro 功能;到期后切回免费。",
+ "account.subscription_detail_past_due": "请尽快更新支付方式以避免会员中断。",
+ "account.subscription_detail_grace": "云端数据将在保留期满后清理。续订即可恢复。",
+ "account.subscription_detail_free": "升级到 Pro 即可使用云端同步与语音输入。",
+ "account.subscription_detail_coming_soon": "我们正在开放支付通道,敬请期待。",
+ "account.subscription_action_subscribe": "开通会员",
+ "account.subscription_action_manage": "管理订阅",
+ "account.subscription_action_resume": "恢复订阅",
+ "account.subscription_action_update_card": "更新支付方式",
+ "account.subscription_action_resubscribe": "续订会员",
+ "account.subscription_action_coming_soon": "敬请期待",
+ "account.subscription_warning_past_due": "扣款失败,请到管理页更新支付方式。",
+ "account.subscription_warning_grace": "云端数据将于 {date} 清理,续订即可保留。",
+ "account.subscription_open_failed": "无法打开管理页,请检查网络后重试。",
+ "account.pro_required_title": "Pro 会员功能",
+ "account.pro_required_voice": "语音输入是 Pro 会员功能。开通后即可在对话框直接说话,自动转写为文字。",
+ "account.pro_required_sync": "云端同步是 Pro 会员功能。开通后多台设备的对话、智能体、技能、知识库自动保持一致。",
+ "account.pro_required_generic": "该功能是 Pro 会员专属。开通后即可使用云端同步与语音输入。",
+ "account.pro_required_action": "立即开通",
+ "account.pro_required_cancel": "稍后再说",
"common.ok": "确定",
"common.confirm": "确认",
"common.cancel": "取消",
@@ -38,7 +66,7 @@
"component.send_blocked_disabled": "该智能体已被停用,请重新启用或换一个对话",
"component.conv_agent_disabled_banner": "本对话绑定的智能体已被停用,发送已锁定。在「智能体」页重新启用即可继续。",
"sidebar.search": "搜索",
- "sidebar.search_title": "全局搜索 (⌘K)",
+ "sidebar.search_title": "全局搜索 (Cmd/Ctrl+K)",
"sidebar.new_chat": "指挥官",
"sidebar.agents": "智能体",
"sidebar.skills": "技能库",
@@ -61,14 +89,7 @@
"common.save": "保存",
"common.more": "更多",
"common.loading": "加载中…",
- "agents.label_connectors": "可用连接器",
- "agents.connectors_empty": "尚未安装任何连接器。请在「连接器」tab 添加。",
- "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.conversations": "对话",
"sidebar.conv_empty": "暂无对话",
"sidebar.projects": "项目",
"sidebar.project_create_title": "新建项目",
@@ -139,6 +160,25 @@
"chat.preview_unsupported_reveal": "打开所在文件夹",
"chat.preview_cancel": "关闭",
"chat.process_info": "过程信息",
+ "conversation_info.toggle_title": "对话信息",
+ "conversation_info.title": "对话信息",
+ "conversation_info.tab_tasks": "任务",
+ "conversation_info.tab_files": "文件",
+ "conversation_info.tab_attachments": "附件",
+ "conversation_info.no_conversation": "打开一个对话后查看详情",
+ "conversation_info.load_failed": "对话信息加载失败:{reason}",
+ "conversation_info.empty_tasks": "暂无任务",
+ "conversation_info.empty_steps": "暂无步骤",
+ "conversation_info.empty_files": "暂无生成文件",
+ "conversation_info.empty_attachments": "暂无附件",
+ "conversation_info.task_plan_fallback": "执行计划",
+ "conversation_info.step_files": "文件",
+ "conversation_info.status.pending": "待开始",
+ "conversation_info.status.in_progress": "进行中",
+ "conversation_info.status.done": "已完成",
+ "conversation_info.status.failed": "失败",
+ "conversation_info.status.skipped": "已跳过",
+ "conversation_info.status.blocked": "待输入",
"artifact.title": "互动应用",
"artifact.reload": "重新加载",
"artifact.more": "更多操作",
@@ -166,12 +206,12 @@
"apps.save_failed": "保存失败",
"chat.archive_btn_title": "保存到知识库",
"chat.archive_btn": "知识库",
- "chat.archive_done": "已存档 ✓",
+ "chat.archive_done": "已存档",
"chat.archive_failed": "存档失败",
"chat.archive_failed_with_reason": "存档失败:{reason}",
"chat.copy_btn_title": "复制最终回复到剪贴板",
"chat.copy_btn": "复制",
- "chat.copy_done": "已复制 ✓",
+ "chat.copy_done": "已复制",
"chat.copy_failed": "复制失败",
"chat.quote_btn_title": "引用此消息发送给目标智能体",
"chat.quote_btn": "引用",
@@ -230,19 +270,19 @@
"ai_select.empty": "(无可选项)",
"chat.stream.phase_start": "开始",
"chat.stream.phase_end": "完成",
- "chat.stream.reasoning_start": "▶ 开始推理",
- "chat.stream.reasoning_done": "● 推理完成",
- "chat.stream.reasoning_error": "◯ 推理出错",
- "chat.stream.reasoning_error_with": "◯ 推理出错 — {msg}",
+ "chat.stream.reasoning_start": "开始推理",
+ "chat.stream.reasoning_done": "推理完成",
+ "chat.stream.reasoning_error": "推理出错",
+ "chat.stream.reasoning_error_with": "推理出错 — {msg}",
"chat.stream.lifecycle": "▪ 生命周期 {p}",
- "chat.stream.thinking": "◆ 思考",
- "chat.stream.plan_with_steps": "▣ 计划({n} 步): {titles}",
- "chat.stream.plan": "▣ 计划 {p}",
- "chat.stream.command_empty": "▷ (空输出)",
- "chat.stream.patch": "◉ 文件改动",
- "chat.stream.approval": "○ 等待确认",
- "chat.stream.approval_with": "○ 等待确认: {p}",
- "chat.stream.error": "◯ 错误: {msg}",
+ "chat.stream.thinking": "思考",
+ "chat.stream.plan_with_steps": "计划({n} 步): {titles}",
+ "chat.stream.plan": "计划 {p}",
+ "chat.stream.command_empty": "(空输出)",
+ "chat.stream.patch": "文件改动",
+ "chat.stream.approval": "等待确认",
+ "chat.stream.approval_with": "等待确认: {p}",
+ "chat.stream.error": "错误: {msg}",
"chat.stream.attachment_skipped": "◯ 附件跳过: {items}",
"chat.create_agent_btn": "创建智能体",
"chat.create_agent_inline": "把以上对话沉淀为智能体",
@@ -383,7 +423,7 @@
"agents.schedule.default_input_label": "默认输入",
"agents.schedule.default_input_placeholder": "运行时发送给智能体的内容(可留空)",
"agents.schedule.title_label": "任务标题(可选)",
- "agents.schedule.title_placeholder": "用于新会话的标题;留空则使用 ⏱ {name}",
+ "agents.schedule.title_placeholder": "用于新会话的标题;留空则使用 {name}",
"agents.schedule.enabled_label": "启用",
"agents.schedule.save_btn": "保存",
"agents.schedule.cancel_btn": "取消",
@@ -503,6 +543,9 @@
"settings.section.cloud": "云端",
"settings.section.local": "本地",
"settings.sync.title": "云端同步",
+ "settings.sync.pro_badge": "Pro",
+ "settings.sync.pro_required": "云端同步是 Pro 会员功能。开通后多台设备的对话、智能体、技能、知识库自动保持一致。",
+ "settings.sync.grace_warning": "云端同步已暂停。云端数据将于 {date} 清理,续订即可保留。",
"settings.sync.storage_title": "存储空间",
"settings.sync.conflicts_title": "冲突记录",
"settings.sync.conflicts_sub": "多设备并发修改同一文件时,被覆盖的版本会保留在此。",
@@ -657,7 +700,7 @@
"settings.entries.testing": "测试中…",
"settings.entries.conn_ok": "连接正常 {ms}",
"settings.entries.conn_failed": "连接失败",
- "settings.entries.delete_confirm": "确定删除授权「{title}」?\n\n(仅从优先级列表移除,凭证仍保留,下次可复用。)",
+ "settings.entries.delete_confirm": "确定删除授权「{title}」?\n\n会同时清理该授权关联的本地凭证,删除后需要重新授权才能继续使用。",
"settings.entries.switch_model_failed": "切换模型失败",
"settings.entries.reorder_failed": "排序失败",
"settings.entries.delete_failed": "删除失败",
@@ -806,7 +849,7 @@
"agent.external_badge.openclaw": "外接 · OpenClaw",
"agent.external_badge.opencode": "外接 · OpenCode",
"agent.external_badge.hermes": "外接 · Hermes",
- "agent.cli_missing": "⚠ 外接智能体未安装",
+ "agent.cli_missing": "外接智能体未安装",
"input.dir.none": "(未选择)",
"input.dir.pick": "选择目录…",
"input.dir.change": "更换…",
@@ -961,5 +1004,13 @@
"marketplace.author_platform": "官方",
"marketplace.author_user": "作者 {uid}",
"marketplace.reconcile_running": "正在同步市场资源 {pulled}/{total}…",
- "marketplace.reconcile_partial": "市场同步完成,{failed} 项失败,下次启动会自动重试"
+ "marketplace.reconcile_partial": "市场同步完成,{failed} 项失败,下次启动会自动重试",
+ "marketplace_request.kind_agent": "智能体",
+ "marketplace_request.kind_skill": "技能",
+ "marketplace_request.status_pending": "等待确认",
+ "marketplace_request.status_installed": "已安装",
+ "marketplace_request.status_skipped": "已跳过",
+ "marketplace_request.status_failed": "失败",
+ "marketplace_request.install": "安装",
+ "marketplace_request.skip": "跳过"
}
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 90943134..8b9a7685 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -6,9 +6,16 @@ let _selectedAgent = null; // { id, name, source }
let _agentEditing = false;
let _agentFieldSaveTimer = null;
+function _agentUiIconHtml(name, className) {
+ if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {
+ return window.uiIconHtml(name, className);
+ }
+ return '';
+}
+
// 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 _RESERVED_AGENT_NAMES = new Set(['指挥官', '总指挥', 'コマンダー', '司令官', 'commander']);
/** 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
@@ -61,7 +68,7 @@ function _resolveCategoryLabel(code, lang) {
const list = (typeof _mpCategoriesCache !== 'undefined' && _mpCategoriesCache) || [];
const c = list.find((x) => x.code === code);
if (!c) return code;
- return lang === 'zh' ? (c.name_zh || c.name_en || code) : (c.name_en || c.name_zh || code);
+ return pickLocalizedName(c, lang) || code;
}
// Mirror of `agents.ts::NAME_TOKEN_RE` so the form rejects junk before
@@ -204,7 +211,7 @@ function renderAgentsGrid(agents) {
<div class="agent-card-actions">
${cliChip}${platformChips}
<button type="button" class="agent-card-use" data-agent-use title="${useTitle}" aria-label="${useTitle}">
- <svg class="icon-play" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><polygon points="5,3 5,13 13,8" fill="currentColor"/></svg>
+ ${_agentUiIconHtml('play-triangle', 'icon-play')}
</button>
</div>
</div>
@@ -490,7 +497,7 @@ function _renderSourceMetaHtml(item) {
if (catCode) {
const lang = (typeof getLang === 'function') ? getLang() : 'zh';
const cat = Array.isArray(_mpCategoriesCache) ? _mpCategoriesCache.find((c) => c.code === catCode) : null;
- const label = cat ? (lang === 'zh' ? (cat.name_zh || cat.name_en || catCode) : (cat.name_en || cat.name_zh || catCode)) : catCode;
+ const label = cat ? (pickLocalizedName(cat, lang) || catCode) : catCode;
parts.push(`<span class="agents-detail-source is-category">${escapeHtml(label)}</span>`);
}
const uid = String(item.create_uid || '').trim();
@@ -573,9 +580,6 @@ function _renderAgentDetail(agent, editing) {
}
_renderAgentEnabledButton({ id: agent.agent_id, enabled: agent.enabled !== false });
- _renderAgentConnectorsSection(agent, editing);
- _renderAgentOutputFormatSection(agent);
-
_toggleAgentFieldEditable(editing);
}
@@ -760,7 +764,9 @@ async function _renderAgentDetailRuntime(agent) {
? baseLabel : currentType;
options.push({
value: `cli:${currentType}`,
- label: `${labelText} ${t('agent.cli_missing')}`,
+ label: labelText,
+ hint: t('agent.cli_missing'),
+ iconName: 'warning',
});
}
if (options.length === 0) {
@@ -787,7 +793,7 @@ async function _renderAgentDetailRuntime(agent) {
const lang = (typeof getLang === 'function') ? getLang() : 'zh';
const prev = (typeof getCliDefaults === 'function') ? getCliDefaults(currentType) : null;
const next2 = (typeof getCliDefaults === 'function') ? getCliDefaults(newCli) : null;
- const prevDescLocal = prev ? (lang === 'en' ? prev.description_en : prev.description_zh) : '';
+ const prevDescLocal = prev ? pickDesc(prev, lang) : '';
const curName = (agent.name || '').trim();
const curDescLocal = pickDesc(agent, lang).trim();
// Same default-like detection as the create modal: bare default OR
@@ -1101,9 +1107,7 @@ function _applyExternalCliDefaults(cliType, { force = false } = {}) {
if (!nameEl || !descEl) return;
const lang = (typeof getLang === 'function') ? getLang() : 'zh';
- const localizedDesc = defaults
- ? (lang === 'en' ? defaults.description_en : defaults.description_zh)
- : '';
+ const localizedDesc = defaults ? pickDesc(defaults, lang) : '';
const targetName = defaults ? defaults.name : '';
const targetDesc = localizedDesc;
@@ -1112,7 +1116,7 @@ function _applyExternalCliDefaults(cliType, { force = false } = {}) {
// name and gets a refreshed description. "Default-like name" also covers
// dedup suffixes like "Claude Code 2" (added to dodge name-taken errors).
const prev = (typeof getCliDefaults === 'function') ? getCliDefaults(_extActiveCli) : null;
- const prevDescLocalized = prev ? (lang === 'en' ? prev.description_en : prev.description_zh) : '';
+ const prevDescLocalized = prev ? pickDesc(prev, lang) : '';
const nameUntouched = force || _isDefaultlikeName(nameEl.value, prev?.name);
const descUntouched = force
@@ -1171,33 +1175,9 @@ function openAgentModal() {
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;
- slot.innerHTML = '';
- const mount = document.createElement('div');
- mount.className = 'ai-select';
- slot.appendChild(mount);
- const options = [
- { 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)' },
- ];
- _aiSelectMount(mount, {
- options,
- value: 'markdown_only',
- onChange: () => { /* dataset.value is the source of truth for save */ },
- });
-}
window.openAgentModal = openAgentModal;
function closeAgentModal() {
@@ -1243,13 +1223,10 @@ async function _saveCreateAgent({ msgEl }) {
}
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, output_format: outputFormat };
+ const body = { name, description, icon: avatar.icon, color: avatar.color, category };
const res = await apiFetch('/api/agents/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -1315,8 +1292,9 @@ async function _saveExternalAgent({ msgEl }) {
// both fully-translated can edit each side later.
const defaults = (typeof getCliDefaults === 'function') ? getCliDefaults(cli) : null;
const lang = (typeof getLang === 'function') ? getLang() : 'zh';
- const description_zh = lang === 'zh' ? desc : (defaults ? defaults.description_zh : desc);
- const description_en = lang === 'en' ? desc : (defaults ? defaults.description_en : desc);
+ const editingZh = descriptionLocale(lang) === 'zh';
+ 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 || '';
@@ -1942,4 +1920,3 @@ function bindAgentPickers() {
}
}
-
diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.js
index ca8ae0b6..9c30be58 100644
--- a/src/renderer/modules/boot.js
+++ b/src/renderer/modules/boot.js
@@ -180,7 +180,7 @@ function setView(view, cid, opts = {}) {
if (isConvPending(cid) && !opts.skipLoad && !streamBubbleAlive) {
const state = pendingConvs.get(cid);
// Will be (re)appended after history loads — handled in loadConversationHistory
- state.needsIndicator = true;
+ if (state) state.needsIndicator = true;
}
// Restore input draft + queue panel for this conversation
if (!opts.skipLoad) _restoreDraft(cid);
@@ -256,4 +256,3 @@ function setView(view, cid, opts = {}) {
currentCid = null;
}
}
-
diff --git a/src/renderer/modules/chat-file-viewer.js b/src/renderer/modules/chat-file-viewer.js
index 2348077b..20e2871a 100644
--- a/src/renderer/modules/chat-file-viewer.js
+++ b/src/renderer/modules/chat-file-viewer.js
@@ -7,6 +7,7 @@
//
// Render strategies:
// image (.png/.jpg/.jpeg/.webp/.gif) → delegate to openChatImageLightbox
+// video (.mp4/.webm/.mov/.m4v/.ogv) → <video controls>
// pdf (.pdf) → <iframe> + Chromium PDFium
// html (.html/.htm) → sandbox="allow-scripts" iframe
// md (.md/.markdown) → renderMarkdown(text) in a <div>
@@ -51,6 +52,7 @@ const _viewerLog = (typeof createLogger === 'function')
// adding a new ext here is fine, but the renderer should actually have
// something useful to do with it; otherwise the fallback is the better UX.
const _IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif']);
+const _VIDEO_EXTS = new Set(['.mp4', '.webm', '.mov', '.m4v', '.ogv']);
const _MARKDOWN_EXTS = new Set(['.md', '.markdown']);
// Text exts: the source-as-text bucket. Keep code-ish exts here too so the
// user can peek at a generated script without leaving the app. No syntax
@@ -80,6 +82,7 @@ function _extOf(name) {
function _kindOf(name) {
const ext = _extOf(name);
if (_IMAGE_EXTS.has(ext)) return 'image';
+ if (_VIDEO_EXTS.has(ext)) return 'video';
if (ext === '.pdf') return 'pdf';
if (ext === '.html' || ext === '.htm') return 'html';
if (_MARKDOWN_EXTS.has(ext)) return 'markdown';
@@ -120,17 +123,16 @@ function _ensureViewer() {
root.setAttribute('aria-hidden', 'true');
const closeLabel = _viewerLabel('chat.preview_close_title', 'Close');
const revealLabel = _viewerLabel('chat.preview_reveal_title', 'Open in folder');
- // Folder SVG uses currentColor so it picks up the same gray as the close
- // `×` — keeps the header monochrome. Colored emoji 📁 was tried first but
- // it looked out of place against `×` (different rendering pipeline + size).
- const folderSvg = '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
+ const folderIcon = (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function')
+ ? window.uiIconHtml('folder', 'chat-file-viewer-folder-icon')
+ : '';
root.innerHTML = `
<div class="chat-file-viewer-backdrop"></div>
<div class="chat-file-viewer-stage">
<div class="chat-file-viewer-header">
<span class="chat-file-viewer-title"></span>
<div class="chat-file-viewer-actions">
- <button type="button" class="chat-file-viewer-reveal" aria-label="${revealLabel}" title="${revealLabel}">${folderSvg}</button>
+ <button type="button" class="chat-file-viewer-reveal" aria-label="${revealLabel}" title="${revealLabel}">${folderIcon}</button>
<button type="button" class="chat-file-viewer-close" aria-label="${closeLabel}" title="${closeLabel}">×</button>
</div>
</div>
@@ -236,6 +238,12 @@ function _renderHtmlBody(absPath, displayName) {
_viewerBody.innerHTML = `<iframe class="chat-file-viewer-html" sandbox="${sandbox}" src="${url}" title="${escapeHtml(displayName || '')}"></iframe>`;
}
+function _renderVideoBody(absPath, displayName) {
+ _openViewerShell(displayName);
+ const url = _chatMediaLocalUrl(absPath);
+ _viewerBody.innerHTML = `<div class="chat-file-viewer-video-wrap"><video class="chat-file-viewer-video" controls preload="metadata" src="${url}"></video></div>`;
+}
+
async function _renderMarkdownBody(absPath, displayName, cid) {
_openViewerShell(displayName);
_viewerBody.innerHTML = `<div class="chat-file-viewer-loading">…</div>`;
@@ -362,6 +370,7 @@ function openChatFileViewer(absPath, displayName, opts) {
return;
}
if (kind === 'pdf') return _renderPdfBody(absPath, name);
+ if (kind === 'video') return _renderVideoBody(absPath, name);
if (kind === 'html') return _renderHtmlBody(absPath, name);
if (kind === 'markdown') return _renderMarkdownBody(absPath, name, cid);
if (kind === 'text') return _renderTextBody(absPath, name, cid);
diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.js
index fba19402..011c4d4f 100644
--- a/src/renderer/modules/connectors.js
+++ b/src/renderer/modules/connectors.js
@@ -159,7 +159,7 @@ function _renderCatalogCard(entry, instance) {
const iconHtml = e.icon_svg
? `<div class="connector-card-icon is-svg">${e.icon_svg}</div>`
: `<div class="connector-card-icon is-fallback">${escapeHtml((e.display_name || '?').slice(0, 2).toUpperCase())}</div>`;
- const desc = (getLang && getLang() === 'zh' ? e.description_zh : e.description_en) || e.description_en || e.description_zh || '';
+ const desc = pickDesc(e, (typeof getLang === 'function') ? getLang() : 'en');
const accountLabel = (instance && instance.oauth_grant && instance.oauth_grant.account_label) || '';
const errorMsg = errored && instance && instance.status && instance.status.message;
diff --git a/src/renderer/modules/contexts.js b/src/renderer/modules/contexts.js
index aab8035d..90442fde 100644
--- a/src/renderer/modules/contexts.js
+++ b/src/renderer/modules/contexts.js
@@ -17,6 +17,13 @@ let _ctxPendingRename = null; // {path} — flagged for inline-rename on t
let _kbStatusByPath = {}; // {[path]: {status, chunks?, error?, kind?}}
let _kbEventsAbort = null;
+function _ctxUiIconHtml(name, className) {
+ if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {
+ return window.uiIconHtml(name, className);
+ }
+ return '';
+}
+
async function loadContexts() {
try {
const [treeRes, kbRes] = await Promise.all([
@@ -178,7 +185,9 @@ function _renderCtxNodes(nodes, depth = 0) {
if (n.type === 'dir') {
const open = _ctxExpanded.has(n.path);
const caretCls = open ? 'skill-tree-caret' : 'skill-tree-caret collapsed';
- const icon = open ? ICON_FOLDER_OPEN : ICON_FOLDER_CLOSED;
+ const icon = open
+ ? _ctxUiIconHtml('folder-open', 'skill-tree-node-svg')
+ : _ctxUiIconHtml('folder', 'skill-tree-node-svg');
const childrenHtml = open
? `<div class="skill-tree-children">${_renderCtxNodes(n.children || [], depth + 1)}</div>`
: '';
@@ -211,7 +220,7 @@ function _renderCtxNodes(nodes, depth = 0) {
<div class="ctx-tree-wrap" data-path="${escapeHtml(n.path)}" data-type="file" draggable="true">
<div class="skill-tree-node skill-tree-file${active}" data-ext="${escapeHtml(ext)}" style="padding-left:${indent}px">
<span class="skill-tree-caret skill-tree-caret-empty"></span>
- <span class="skill-tree-icon icon-file" data-ext="${escapeHtml(ext)}">${ICON_FILE}</span>
+ <span class="skill-tree-icon icon-file" data-ext="${escapeHtml(ext)}">${_ctxUiIconHtml('file', 'skill-tree-node-svg')}</span>
${labelHtml}
${chip}
<button type="button" class="ctx-row-menu-btn" data-menu title="${moreTitle}" aria-label="${moreTitle}">⋯</button>
@@ -999,9 +1008,12 @@ function _showCtxBinaryViewer(rel, kind) {
const els = _prepCtxViewerShell(rel);
if (!els) return;
const kindLabel = t(`contexts.viewer.kind_${kind}`) || kind.toUpperCase();
+ const icon = (typeof window !== 'undefined' && typeof window.fileKindIconHtml === 'function')
+ ? window.fileKindIconHtml(rel, kind)
+ : '';
els.bodyEl.innerHTML = `
<div class="ctx-viewer-binary">
- <div class="ctx-viewer-binary-icon">${kind === 'pdf' ? '📄' : kind === 'docx' ? '📘' : '📎'}</div>
+ <div class="ctx-viewer-binary-icon">${icon}</div>
<div class="ctx-viewer-binary-name">${escapeHtml(rel)}</div>
<div class="ctx-viewer-binary-hint">${escapeHtml(t('contexts.viewer.binary_hint', { kind: kindLabel }))}</div>
<button class="btn btn-primary" id="ctx-viewer-reveal-big">${escapeHtml(t('contexts.viewer.open_system'))}</button>
@@ -1122,9 +1134,8 @@ function _ctxClearDraft(path) {
if (key) _ctxDrafts.delete(key);
}
-// Toolbar definition. `kind` keys map to `_ctxApplyMd()` cases; `icon` uses
-// Unicode glyphs only (CLAUDE.md §8 — no colored emoji on process-info-style
-// rails); `label` is the i18n key for the title tooltip.
+// 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' },
@@ -1134,17 +1145,17 @@ const _CTX_EDITOR_TOOLBAR = [
{ 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', icon: '•', label: 'contexts.editor.tb.ul' },
- { kind: 'ol', icon: '1.', label: 'contexts.editor.tb.ol' },
- { kind: 'quote', icon: '“', label: 'contexts.editor.tb.quote' },
+ { 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', icon: '<>', label: 'contexts.editor.tb.code' },
- { kind: 'codeblock', icon: '{ }', label: 'contexts.editor.tb.codeblock' },
+ { kind: 'code', iconName: 'code', label: 'contexts.editor.tb.code' },
+ { kind: 'codeblock', iconName: 'code-block', label: 'contexts.editor.tb.codeblock' },
{ kind: 'sep' },
- { kind: 'link', icon: '↗', label: 'contexts.editor.tb.link' },
- { kind: 'image', icon: '▣', label: 'contexts.editor.tb.image' },
+ { kind: 'link', iconName: 'link', label: 'contexts.editor.tb.link' },
+ { kind: 'image', iconName: 'image', label: 'contexts.editor.tb.image' },
{ kind: 'sep' },
- { kind: 'todo', icon: '☐', label: 'contexts.editor.tb.todo' },
+ { kind: 'todo', iconName: 'square', label: 'contexts.editor.tb.todo' },
];
function _enterCtxEdit() {
@@ -1174,10 +1185,15 @@ function _ctxRenderEditor() {
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}` : '';
- 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}>${escapeHtml(item.icon)}</button>`;
+ 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 = _ctxEditPreview ? '✎' : '◐';
+ 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>`
@@ -1186,7 +1202,7 @@ function _ctxRenderEditor() {
<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} ${escapeHtml(t(toggleKey))}</button>
+ <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>
`;
diff --git a/src/renderer/modules/conversation-info.js b/src/renderer/modules/conversation-info.js
new file mode 100644
index 00000000..b8eb0050
--- /dev/null
+++ b/src/renderer/modules/conversation-info.js
@@ -0,0 +1,569 @@
+// ─── Conversation info side panel ───────────────────────────────────────
+// Right-side companion panel for the active conversation. It summarizes the
+// structured plan, produced files, and attachments without adding new backend
+// state: everything is derived from the same history / plan / attachment
+// endpoints already used by the chat view.
+
+const ConversationInfo = (() => {
+ const _infoLog = (typeof createLogger === 'function')
+ ? createLogger('conversation-info')
+ : { warn: () => {}, info: () => {}, error: () => {} };
+
+ let _cid = null;
+ let _open = false;
+ let _activeTab = 'tasks';
+ let _seq = 0;
+ let _loading = false;
+ let _error = '';
+ let _snapshot = {
+ conversation: null,
+ history: [],
+ plan: null,
+ attachments: [],
+ };
+
+ function _label(key, fallback, vars) {
+ try {
+ const v = typeof t === 'function' ? t(key, vars || undefined) : key;
+ return v && v !== key ? v : fallback;
+ } catch (_) {
+ return fallback;
+ }
+ }
+
+ function _compactText(text, max = 82) {
+ const s = String(text || '').replace(/\s+/g, ' ').trim();
+ if (!s) return '';
+ return s.length > max ? s.slice(0, max - 1) + '…' : s;
+ }
+
+ function _baseName(p) {
+ const parts = String(p || '').split(/[\\/]/).filter(Boolean);
+ return parts.length ? parts[parts.length - 1] : String(p || '');
+ }
+
+ function _dirName(p) {
+ const s = String(p || '').replace(/\\/g, '/');
+ const idx = s.lastIndexOf('/');
+ return idx >= 0 ? s.slice(0, idx) : '';
+ }
+
+ function _splitPath(p) {
+ return String(p || '')
+ .replace(/\\/g, '/')
+ .split('/')
+ .filter(Boolean);
+ }
+
+ function _samePrefix(a, b) {
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length > b.length) return false;
+ for (let i = 0; i < a.length; i++) {
+ if (a[i] !== b[i]) return false;
+ }
+ return true;
+ }
+
+ function _commonDirSegments(paths) {
+ const dirs = paths.map((p) => _splitPath(_dirName(p)));
+ if (!dirs.length) return [];
+ let common = dirs[0].slice();
+ for (let i = 1; i < dirs.length; i++) {
+ const next = dirs[i];
+ let j = 0;
+ while (j < common.length && j < next.length && common[j] === next[j]) j++;
+ common = common.slice(0, j);
+ }
+ return common;
+ }
+
+ function _iconForName(name, kind) {
+ if (typeof window !== 'undefined' && typeof window.fileKindIconHtml === 'function') return window.fileKindIconHtml(name, kind);
+ return '';
+ }
+
+ function _uiIcon(name, className) {
+ if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {
+ return window.uiIconHtml(name, className);
+ }
+ return '';
+ }
+
+ function _kindForName(name) {
+ const ext = (String(name || '').split('.').pop() || '').toLowerCase();
+ if (['png', 'jpg', 'jpeg', 'webp', 'gif'].includes(ext)) return 'image';
+ if (['mp4', 'webm', 'mov', 'm4v', 'ogv'].includes(ext)) return 'video';
+ if (ext === 'pdf') return 'pdf';
+ if (ext === 'docx') return 'docx';
+ return 'text';
+ }
+
+ function _formatBytes(bytes) {
+ const n = Number(bytes);
+ if (!Number.isFinite(n) || n <= 0) return '';
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(n < 10 * 1024 ? 1 : 0)} KB`;
+ return `${(n / 1024 / 1024).toFixed(n < 10 * 1024 * 1024 ? 1 : 0)} MB`;
+ }
+
+ async function _fetchJson(url) {
+ const res = await apiFetch(url);
+ const data = await res.json();
+ if (!data || data.ok === false) throw new Error((data && data.error) || 'load failed');
+ return data;
+ }
+
+ async function _load(cid) {
+ const enc = encodeURIComponent(cid);
+ const [historyData, planData, attachmentData] = await Promise.all([
+ _fetchJson(`/api/conversations/${enc}/history?limit=500`),
+ _fetchJson(`/api/conversations/${enc}/plan`).catch((err) => {
+ _infoLog.warn('plan load failed', { cid, error: err && err.message });
+ return { plan: null };
+ }),
+ _fetchJson(`/api/conversations/${enc}/attachments`).catch((err) => {
+ _infoLog.warn('attachment load failed', { cid, error: err && err.message });
+ return { items: [] };
+ }),
+ ]);
+ return {
+ conversation: historyData.conversation || null,
+ history: Array.isArray(historyData.history) ? historyData.history : [],
+ plan: planData.plan || null,
+ attachments: Array.isArray(attachmentData.items) ? attachmentData.items : [],
+ };
+ }
+
+ function _currentConversationTitle() {
+ const c = _snapshot.conversation
+ || (Array.isArray(conversations) ? conversations.find((x) => x && x.conversation_id === _cid) : null);
+ return c && c.title ? c.title : _label('chat.new_conv_title', 'New conversation');
+ }
+
+ function _nearestPriorUserText(history, index) {
+ for (let i = index; i >= 0; i--) {
+ const m = history[i];
+ if (m && (m.from === 'user' || m.role === 'user')) {
+ return _compactText(m.text || m.content || '', 96);
+ }
+ }
+ return '';
+ }
+
+ function _parseAnnouncementSteps(text) {
+ const lines = String(text || '').split(/\r?\n/);
+ const steps = [];
+ for (const line of lines) {
+ const m = line.match(/^\s*(\d+)[\.\)、)]\s+(.+?)\s*$/u);
+ if (!m) continue;
+ const idx = Number(m[1]);
+ const body = String(m[2] || '').replace(/[((][^))]*[))]\s*$/u, '').trim();
+ if (!body) continue;
+ steps.push({ index: idx, title: body, status: 'pending' });
+ }
+ return steps;
+ }
+
+ function _buildTasks() {
+ const history = _snapshot.history || [];
+ const plan = _snapshot.plan;
+ const tasks = [];
+ for (let i = 0; i < history.length; i++) {
+ const m = history[i];
+ if (!m || !m.plan_announcement) continue;
+ const fallbackTitle = _nearestPriorUserText(history, i - 1)
+ || _currentConversationTitle()
+ || _label('conversation_info.task_plan_fallback', 'Execution plan');
+ tasks.push({
+ id: `plan-${m.id || i}`,
+ title: fallbackTitle,
+ time: m.ts || m.time || '',
+ steps: _parseAnnouncementSteps(m.text || m.content || ''),
+ current: false,
+ });
+ }
+
+ if (plan && Array.isArray(plan.steps) && plan.steps.length) {
+ const title = _compactText(plan.initial_message || '', 96)
+ || (tasks.length ? tasks[tasks.length - 1].title : '')
+ || _currentConversationTitle()
+ || _label('conversation_info.task_plan_fallback', 'Execution plan');
+ const current = {
+ id: 'plan-current',
+ title,
+ time: plan.updated_at || plan.created_at || '',
+ steps: plan.steps,
+ current: true,
+ };
+ if (tasks.length) {
+ tasks[tasks.length - 1] = { ...tasks[tasks.length - 1], ...current };
+ } else {
+ tasks.push(current);
+ }
+ }
+
+ return tasks.sort((a, b) => new Date(b.time || 0).getTime() - new Date(a.time || 0).getTime());
+ }
+
+ function _statusLabel(status) {
+ const raw = String(status || 'pending');
+ const fallback = {
+ pending: 'Pending',
+ in_progress: 'Running',
+ done: 'Done',
+ failed: 'Failed',
+ skipped: 'Skipped',
+ blocked: 'Blocked',
+ }[raw] || raw;
+ return _label(`conversation_info.status.${raw}`, fallback);
+ }
+
+ function _statusIcon(status) {
+ const raw = String(status || 'pending');
+ const iconName = {
+ pending: 'hourglass',
+ in_progress: 'play',
+ done: 'check-circle',
+ failed: 'x-circle',
+ skipped: 'skip-forward',
+ blocked: 'document-pencil',
+ }[raw] || 'info';
+ if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {
+ return window.uiIconHtml(iconName, 'ui-icon conversation-info-step-status-icon');
+ }
+ return '';
+ }
+
+ function _assigneeLabel(raw) {
+ const a = String(raw || '').trim();
+ if (!a) return '';
+ if (a === 'commander') return _label('chat.recipient_commander', 'Commander');
+ if (a === 'user') return _label('chat.from_user', 'User');
+ return '@' + a;
+ }
+
+ function _renderStep(step) {
+ const status = String(step.status || 'pending');
+ const assignee = _assigneeLabel(step.assignee);
+ const reason = step.failure_reason
+ ? `<div class="conversation-info-step-reason">${escapeHtml(_compactText(step.failure_reason, 96))}</div>`
+ : '';
+ return `
+ <div class="conversation-info-step is-${escapeHtml(status)}">
+ <div class="conversation-info-step-head">
+ <span class="conversation-info-step-icon" aria-label="${escapeHtml(status)}">${_statusIcon(status)}</span>
+ <span class="conversation-info-step-index">${escapeHtml(step.index ? `${step.index}.` : '')}</span>
+ <span class="conversation-info-step-title">${escapeHtml(step.title || '')}</span>
+ <span class="conversation-info-status">${escapeHtml(_statusLabel(status))}</span>
+ </div>
+ ${assignee ? `<div class="conversation-info-step-meta">${escapeHtml(assignee)}</div>` : ''}
+ ${reason}
+ </div>
+ `;
+ }
+
+ function _renderTasks() {
+ const tasks = _buildTasks();
+ if (!tasks.length) {
+ return `<div class="conversation-info-empty">${escapeHtml(_label('conversation_info.empty_tasks', 'No tasks yet'))}</div>`;
+ }
+ return `<div class="conversation-info-task-list">${tasks.map((task) => {
+ const count = Array.isArray(task.steps) ? task.steps.length : 0;
+ const stepsHtml = count
+ ? task.steps.map(_renderStep).join('')
+ : `<div class="conversation-info-empty is-small">${escapeHtml(_label('conversation_info.empty_steps', 'No steps'))}</div>`;
+ return `
+ <div class="conversation-info-task">
+ <div class="conversation-info-task-summary">
+ <span class="conversation-info-task-title">${escapeHtml(task.title || _label('conversation_info.task_plan_fallback', 'Execution plan'))}</span>
+ </div>
+ <div class="conversation-info-task-steps">${stepsHtml}</div>
+ </div>
+ `;
+ }).join('')}</div>`;
+ }
+
+ function _collectProducedFiles() {
+ const byPath = new Map();
+ for (const m of _snapshot.history || []) {
+ const ts = m && (m.ts || m.time || '');
+ const produced = Array.isArray(m && m.produced) ? m.produced : [];
+ for (const p of produced) {
+ if (!p) continue;
+ byPath.set(String(p), { path: String(p), time: ts });
+ }
+ }
+ const planSteps = _snapshot.plan && Array.isArray(_snapshot.plan.steps)
+ ? _snapshot.plan.steps : [];
+ for (const step of planSteps) {
+ const produced = Array.isArray(step && step.output_files) ? step.output_files : [];
+ for (const p of produced) {
+ if (!p) continue;
+ const key = String(p);
+ if (!byPath.has(key)) byPath.set(key, { path: key, time: _snapshot.plan.updated_at || '' });
+ }
+ }
+ return Array.from(byPath.values()).sort((a, b) => String(a.path).localeCompare(String(b.path)));
+ }
+
+ function _buildFileTree(files) {
+ const root = { dirs: new Map(), files: [] };
+ const common = _commonDirSegments(files.map((f) => f.path));
+ for (const file of files) {
+ const all = _splitPath(file.path);
+ const rel = _samePrefix(common, all) ? all.slice(common.length) : all;
+ const parts = rel.length ? rel : [_baseName(file.path)];
+ let node = root;
+ for (const part of parts.slice(0, -1)) {
+ if (!node.dirs.has(part)) node.dirs.set(part, { dirs: new Map(), files: [] });
+ node = node.dirs.get(part);
+ }
+ node.files.push({ ...file, name: parts[parts.length - 1] || _baseName(file.path) });
+ }
+ return root;
+ }
+
+ function _renderTreeNode(node, depth) {
+ const dirs = Array.from(node.dirs.entries()).sort((a, b) => a[0].localeCompare(b[0]));
+ const files = node.files.slice().sort((a, b) => a.name.localeCompare(b.name));
+ const dirHtml = dirs.map(([name, child]) => `
+ <details class="conversation-info-dir" style="--depth:${depth}" open>
+ <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>
+ </summary>
+ ${_renderTreeNode(child, depth + 1)}
+ </details>
+ `).join('');
+ const fileHtml = files.map((file) => `
+ <button type="button" class="conversation-info-file" style="--depth:${depth}"
+ data-file-path="${escapeHtml(file.path)}" title="${escapeHtml(file.path)}">
+ <span class="conversation-info-file-icon">${_iconForName(file.name)}</span>
+ <span class="conversation-info-file-name">${escapeHtml(file.name)}</span>
+ </button>
+ `).join('');
+ return dirHtml + fileHtml;
+ }
+
+ function _renderFiles() {
+ const files = _collectProducedFiles();
+ if (!files.length) {
+ return `<div class="conversation-info-empty">${escapeHtml(_label('conversation_info.empty_files', 'No generated files yet'))}</div>`;
+ }
+ const tree = _buildFileTree(files);
+ return `<div class="conversation-info-tree">${_renderTreeNode(tree, 0)}</div>`;
+ }
+
+ function _collectConversationAttachments() {
+ const byName = new Map();
+ for (const m of _snapshot.history || []) {
+ const ts = m && (m.ts || m.time || '');
+ const attachments = Array.isArray(m && m.attachments) ? m.attachments : [];
+ for (const name of attachments) {
+ if (typeof name !== 'string' || !name) continue;
+ if (!byName.has(name)) {
+ byName.set(name, { name, kind: _kindForName(name), bytes: 0, time: ts, pending: false });
+ }
+ }
+ }
+ for (const item of _snapshot.attachments || []) {
+ const name = String(item && item.name || '');
+ if (!name) continue;
+ byName.set(name, {
+ name,
+ kind: item.kind || _kindForName(name),
+ bytes: Number(item.bytes) || 0,
+ time: item.mtime ? new Date(Number(item.mtime) * 1000).toISOString() : '',
+ pending: true,
+ });
+ }
+ return Array.from(byName.values()).sort((a, b) => {
+ const at = new Date(a.time || 0).getTime();
+ const bt = new Date(b.time || 0).getTime();
+ if (bt !== at) return bt - at;
+ return String(a.name || '').localeCompare(String(b.name || ''));
+ });
+ }
+
+ function _renderAttachments() {
+ const items = _collectConversationAttachments();
+ if (!items.length) {
+ return `<div class="conversation-info-empty">${escapeHtml(_label('conversation_info.empty_attachments', 'No attachments'))}</div>`;
+ }
+ return `<div class="conversation-info-attachment-list">${items.map((item) => {
+ const name = String(item.name || '');
+ const size = _formatBytes(item.bytes);
+ const meta = [item.kind || '', size].filter(Boolean).join(' · ');
+ return `
+ <button type="button" class="conversation-info-attachment" data-attachment-name="${escapeHtml(name)}" title="${escapeHtml(name)}">
+ <span class="conversation-info-file-icon">${_iconForName(name, item.kind)}</span>
+ <span class="conversation-info-attachment-main">
+ <span class="conversation-info-file-name">${escapeHtml(name)}</span>
+ ${meta ? `<span class="conversation-info-attachment-meta">${escapeHtml(meta)}</span>` : ''}
+ </span>
+ </button>
+ `;
+ }).join('')}</div>`;
+ }
+
+ function _renderBody() {
+ const body = document.getElementById('conversation-info-body');
+ if (!body) return;
+ if (!_cid) {
+ body.innerHTML = `<div class="conversation-info-empty">${escapeHtml(_label('conversation_info.no_conversation', 'Open a conversation to see details'))}</div>`;
+ return;
+ }
+ if (_loading) {
+ body.innerHTML = `<div class="conversation-info-empty">${escapeHtml(_label('common.loading', 'Loading…'))}</div>`;
+ return;
+ }
+ if (_error) {
+ body.innerHTML = `<div class="conversation-info-empty is-error">${escapeHtml(_label('conversation_info.load_failed', 'Could not load conversation info', { reason: _error }))}</div>`;
+ return;
+ }
+ if (_activeTab === 'files') body.innerHTML = _renderFiles();
+ else if (_activeTab === 'attachments') body.innerHTML = _renderAttachments();
+ else body.innerHTML = _renderTasks();
+ }
+
+ function _syncChrome() {
+ const panel = document.getElementById('conversation-info-panel');
+ const toggle = document.getElementById('conversation-info-toggle');
+ if (panel) panel.hidden = !_open;
+ if (toggle) {
+ toggle.classList.toggle('is-active', _open);
+ toggle.setAttribute('aria-expanded', _open ? 'true' : 'false');
+ }
+ document.querySelectorAll('.conversation-info-tab').forEach((tab) => {
+ tab.classList.toggle('is-active', tab.dataset.infoTab === _activeTab);
+ });
+ }
+
+ function _setOpen(next) {
+ _open = !!next;
+ _syncChrome();
+ if (_open) refresh(_cid);
+ }
+
+ async function refresh(cid, opts = {}) {
+ const target = cid || _cid;
+ if (!target || target !== _cid || !_open) return;
+ const seq = ++_seq;
+ const silent = !!opts.silent;
+ if (!silent) {
+ _loading = true;
+ _error = '';
+ _renderBody();
+ }
+ try {
+ const snapshot = await _load(target);
+ if (seq !== _seq || target !== _cid) return;
+ _snapshot = snapshot;
+ _error = '';
+ } catch (err) {
+ if (seq !== _seq || target !== _cid) return;
+ _error = (err && err.message) || String(err);
+ } finally {
+ if (seq === _seq && target === _cid) {
+ _loading = false;
+ _renderBody();
+ }
+ }
+ }
+
+ function bind(cid) {
+ _cid = cid || null;
+ _open = false;
+ _snapshot = { conversation: null, history: [], plan: null, attachments: [] };
+ _error = '';
+ _loading = false;
+ _seq++;
+ _syncChrome();
+ _renderBody();
+ if (_open && _cid) refresh(_cid);
+ }
+
+ function unbind() {
+ bind(null);
+ }
+
+ function _openFile(absPath) {
+ if (!absPath || typeof openChatFileViewer !== 'function') return;
+ openChatFileViewer(absPath, _baseName(absPath), _cid ? { cid: _cid } : undefined);
+ }
+
+ async function _openAttachment(name) {
+ if (!_cid || !name || typeof openChatFileViewer !== 'function') return;
+ try {
+ const res = await window.orkas.invoke('attachments.absPath', { cid: _cid, name });
+ if (!res || !res.ok || !res.path) {
+ _infoLog.warn('attachment preview resolve failed', { cid: _cid, name, error: res && res.error });
+ return;
+ }
+ openChatFileViewer(res.path, name, { cid: _cid });
+ } catch (err) {
+ _infoLog.warn('attachment preview threw', { cid: _cid, name, error: String(err && err.message || err) });
+ }
+ }
+
+ function _bindDom() {
+ const toggle = document.getElementById('conversation-info-toggle');
+ const close = document.getElementById('conversation-info-close');
+ const body = document.getElementById('conversation-info-body');
+ if (toggle && toggle.dataset.bound !== '1') {
+ toggle.dataset.bound = '1';
+ toggle.addEventListener('click', () => _setOpen(!_open));
+ }
+ if (close && close.dataset.bound !== '1') {
+ close.dataset.bound = '1';
+ close.addEventListener('click', () => _setOpen(false));
+ }
+ document.querySelectorAll('.conversation-info-tab').forEach((tab) => {
+ if (tab.dataset.bound === '1') return;
+ tab.dataset.bound = '1';
+ tab.addEventListener('click', () => {
+ _activeTab = tab.dataset.infoTab || 'tasks';
+ _syncChrome();
+ _renderBody();
+ });
+ });
+ if (body && body.dataset.bound !== '1') {
+ body.dataset.bound = '1';
+ body.addEventListener('click', (ev) => {
+ const file = ev.target.closest('.conversation-info-file[data-file-path]');
+ if (file) {
+ ev.preventDefault();
+ _openFile(file.dataset.filePath || '');
+ return;
+ }
+ const attachment = ev.target.closest('.conversation-info-attachment[data-attachment-name]');
+ if (attachment) {
+ ev.preventDefault();
+ _openAttachment(attachment.dataset.attachmentName || '');
+ }
+ });
+ }
+ _syncChrome();
+ _renderBody();
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', _bindDom, { once: true });
+ } else {
+ _bindDom();
+ }
+ window.addEventListener('i18n-change', () => {
+ _syncChrome();
+ _renderBody();
+ });
+
+ return {
+ bind,
+ unbind,
+ refresh,
+ refreshAttachments: refresh,
+ };
+})();
+
+window.ConversationInfo = ConversationInfo;
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index dc903e96..021b68bc 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -1,5 +1,10 @@
const _convLog = createLogger('conversation');
+function _uiIconHtml(name, className) {
+ if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') return window.uiIconHtml(name, className || 'ui-icon');
+ return '';
+}
+
// ─── @-mention highlighting (post-render DOM walk) ────────────────────────
// Wrap `@<token>` matches in a `<span class="msg-mention">` so the chat
// bubbles paint mentions in accent color. Done after markdown render via a
@@ -348,6 +353,7 @@ function onEnterConversationView() {
// loadConversationHistory is intentionally skipped). Without this hook,
// the rail would keep displaying the previous cid's plan content.
if (window.PlanRail) window.PlanRail.bind(currentCid || null);
+ if (window.ConversationInfo) window.ConversationInfo.bind(currentCid || null);
// Quote preview is per-cid; rerender so a quote captured in another conv
// doesn't bleed into this one (and a quote left in this conv reappears
// when the user navigates back).
@@ -362,6 +368,7 @@ function _forgetCidRecipient(cid) {
delete _recipientByCid[cid];
_saveRecipientMap();
}
+ setGroupConversationBusy(cid, false);
_latestInFlight.delete(cid);
_lastInteractiveTurnAgent.delete(cid);
// Drop any pending quote for the deleted conv (memory only — no localStorage).
@@ -645,6 +652,7 @@ async function _refreshGroupMembers(cid) {
const data = await res.json();
if (data?.ok && Array.isArray(data.actors)) {
_groupMembersCache.set(cid, data.actors);
+ _refreshActorPlaceholders(cid);
// Roster change can flip the inline "create agent" button visibility:
// a freshly @-mentioned agent joins members.json before it streams a
// reply, and the button must hide as soon as that happens.
@@ -656,6 +664,18 @@ async function _refreshGroupMembers(cid) {
} catch (_) { /* non-fatal */ }
return _groupMembersCache.get(cid) || [];
}
+
+function _rememberGroupActor(cid, actor) {
+ if (!cid || !actor || !actor.id) return;
+ const existing = _groupMembersCache.get(cid) || [];
+ const idx = existing.findIndex((x) => x && x.id === actor.id);
+ const next = existing.slice();
+ if (idx >= 0) next[idx] = { ...next[idx], ...actor };
+ else next.push(actor);
+ _groupMembersCache.set(cid, next);
+ _refreshActorPlaceholders(cid, actor.id);
+}
+
// Read-side normalizer: jsonl records written before the multi-edit
// migration carry singular `created_agent`; new ones carry plural
// `created_agents`. Returns the array, or `null` when neither field is set.
@@ -698,6 +718,7 @@ function _groupMsgToLegacy(gm) {
...(_normalizeCreatedAgents(gm) ? { created_agents: _normalizeCreatedAgents(gm) } : {}),
...(_normalizeCreatedSkills(gm) ? { created_skills: _normalizeCreatedSkills(gm) } : {}),
...(Array.isArray(gm.artifacts) && gm.artifacts.length ? { artifacts: gm.artifacts } : {}),
+ ...(Array.isArray(gm.marketplace_requests) && gm.marketplace_requests.length ? { marketplace_requests: gm.marketplace_requests } : {}),
...(gm.plan_announcement ? { _plan_announcement: true } : {}),
...(Array.isArray(gm.process) && gm.process.length ? { process: gm.process } : {}),
};
@@ -727,6 +748,11 @@ const CHAT_ATTACH_ACCEPT = [
const CHAT_IMAGE_EXTS = ['.png', '.jpg', '.jpeg', '.webp', '.gif'];
const CHAT_VIDEO_EXTS = ['.mp4', '.webm', '.mov', '.m4v', '.ogv'];
+function _chatFileIconHtml(name, kind) {
+ if (typeof window !== 'undefined' && typeof window.fileKindIconHtml === 'function') return window.fileKindIconHtml(name, kind);
+ return '';
+}
+
function _chatAttachExtOf(name) {
const i = (name || '').lastIndexOf('.');
return i >= 0 ? name.slice(i).toLowerCase() : '';
@@ -754,6 +780,9 @@ function _chatAttachList(cid) {
function _chatAttachSet(cid, items) {
_chatAttachments.set(cid, items);
_chatAttachRenderChips(cid);
+ if (cid && cid === currentCid && window.ConversationInfo) {
+ window.ConversationInfo.refreshAttachments(cid);
+ }
}
function _chatAttachClear(cid) {
@@ -786,12 +815,8 @@ function _chatAttachRenderChips(cid) {
host.style.display = '';
host.innerHTML = items.map((it, i) => {
const icon = it.kind === 'image'
- ? (it.dataUrl ? `<img class="chat-attach-thumb" src="${it.dataUrl}" alt="">` : '🖼')
- : it.kind === 'video'
- ? '🎬'
- : it.kind === 'pdf' ? '📄'
- : it.kind === 'docx' ? '📝'
- : '📃';
+ ? (it.dataUrl ? `<img class="chat-attach-thumb" src="${it.dataUrl}" alt="">` : _chatFileIconHtml(it.name, it.kind))
+ : _chatFileIconHtml(it.name, it.kind);
const label = escapeHtml(it.name);
const busy = it.status === 'uploading';
const errored = it.status === 'error';
@@ -948,11 +973,7 @@ function _renderMessageAttachmentsHtml(names, cid) {
const items = names.map((n) => {
const ext = _chatAttachExtOf(n);
const kind = _chatAttachKindFromExt(ext);
- const icon = kind === 'pdf' ? '📄'
- : kind === 'docx' ? '📝'
- : kind === 'image' ? '🖼'
- : kind === 'video' ? '🎬'
- : '📃';
+ const icon = _chatFileIconHtml(n, kind);
const label = escapeHtml(n);
if (kind === 'image' && cid) {
const url = _chatMediaUrl(cid, n);
@@ -984,28 +1005,7 @@ function _renderMessageAttachmentsHtml(names, cid) {
// offering "open the containing folder" for unsupported kinds.
function _iconForProduced(name) {
- const ext = (name.split('.').pop() || '').toLowerCase();
- if (ext === 'pdf') return '📄';
- if (ext === 'docx' || ext === 'doc') return '📝';
- if (['png', 'jpg', 'jpeg', 'webp', 'gif', 'svg', 'bmp', 'ico'].includes(ext)) return '🖼';
- if (['mp4', 'webm', 'mov', 'm4v', 'ogv', 'avi', 'mkv'].includes(ext)) return '🎬';
- if (['mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac'].includes(ext)) return '🎵';
- if (['md', 'markdown', 'txt', 'log', 'rst', 'tex'].includes(ext)) return '📃';
- if (['json', 'yaml', 'yml', 'toml', 'csv', 'tsv', 'xlsx', 'xls', 'xml', 'ini', 'conf'].includes(ext)) return '📊';
- if (['zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', '7z', 'rar'].includes(ext)) return '📦';
- // Source code / scripts — covers .py / .ts / web / shell / mainstream langs.
- // Anything else falls through to the generic "file" icon below.
- if ([
- 'py', 'pyi', 'ipynb',
- 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs',
- 'html', 'htm', 'css', 'scss', 'sass', 'less',
- 'sh', 'bash', 'zsh', 'fish', 'ps1', 'bat', 'cmd',
- 'rb', 'go', 'rs', 'java', 'kt', 'kts', 'scala',
- 'c', 'cpp', 'cc', 'cxx', 'h', 'hpp', 'hxx',
- 'php', 'swift', 'lua', 'pl', 'pm', 'r', 'dart',
- 'sql', 'graphql', 'gql', 'proto',
- ].includes(ext)) return '📜';
- return '📄';
+ return _chatFileIconHtml(name);
}
function _renderMessageProducedHtml(absPaths) {
@@ -1515,17 +1515,18 @@ async function loadConversationHistory(cid) {
const processingFresh = convMeta.processing === true
&& convMeta.processing_since
&& (Date.now() - new Date(convMeta.processing_since).getTime()) < 15 * 60 * 1000;
- if (lastMsg?.role === 'user' && !isConvPending(cid) && processingFresh) {
+ const wasPendingBeforeHistoryRecovery = isConvPending(cid);
+ if (processingFresh && !wasPendingBeforeHistoryRecovery) {
+ setGroupConversationBusy(cid, true);
+ _updateConvSidebarBadge(cid, true);
+ startPolling(cid);
+ if (cid === currentCid) _updateConvSendUI(cid);
+ }
+ if (lastMsg?.role === 'user' && !wasPendingBeforeHistoryRecovery && processingFresh) {
pollMsgCounts.set(cid, history.length);
- const loadingEl = appendChatMessage({
- role: 'assistant',
- content: `<span class="chat-replying">${escapeHtml(t('chat.thinking'))}</span>`,
- time: nowIsoLocal(),
- });
+ const loadingEl = _createStreamingAssistantMessage(container, { hiddenUntilActor: true });
pendingConvs.set(cid, { loadingEl, needsIndicator: false });
_updateConvSendUI(cid);
- _updateConvSidebarBadge(cid, true);
- startPolling(cid);
} else if (isConvPending(cid)) {
// User navigated away and back during an in-flight request. The stream
// reader loop in createChatController.send() holds the original msgEl
@@ -1534,18 +1535,18 @@ async function loadConversationHistory(cid) {
// Minting a new one here (as before) stranded the stream: events kept
// landing on the orphaned node and the new bubble stayed at "thinking…"
// until stream end / polling rescue.
- const state = pendingConvs.get(cid);
+ let state = pendingConvs.get(cid);
+ if (!state) {
+ state = { loadingEl: null, needsIndicator: false, controller: null, aborted: false };
+ pendingConvs.set(cid, state);
+ }
pollMsgCounts.set(cid, history.length);
if (state.loadingEl) {
const emptyEl = container.querySelector('.empty');
if (emptyEl) emptyEl.remove();
_appendBeforeSpacer(container, state.loadingEl);
} else {
- const loadingEl = appendChatMessage({
- role: 'assistant',
- content: `<span class="chat-replying">${escapeHtml(t('chat.thinking'))}</span>`,
- time: nowIsoLocal(),
- });
+ const loadingEl = _createStreamingAssistantMessage(container, { hiddenUntilActor: true });
state.loadingEl = loadingEl;
}
state.needsIndicator = false;
@@ -1557,8 +1558,10 @@ async function loadConversationHistory(cid) {
// adds it post-scroll and it ends up below the visible area.
_ensureConvCreateAgentInline();
_scrollToBottomNoAnim(container);
+ if (window.ConversationInfo) window.ConversationInfo.refresh(cid);
} catch (e) {
container.innerHTML = `<div class="empty">${escapeHtml(t('chat.load_failed', { msg: e.message || '' }))}</div>`;
+ if (window.ConversationInfo) window.ConversationInfo.refresh(cid);
}
}
@@ -1695,7 +1698,11 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
// `_stripSurvivingStructuralBlocks` in strip-structural-blocks.js).
let displayContent = rawContent;
if (!isHtmlSnippet) {
- if (role === 'user') displayContent = _stripArtifactResultTagForDisplay(_stripSubmissionTagForDisplay(rawContent));
+ if (role === 'user') {
+ displayContent = _stripMarketplaceInstallResultTagForDisplay(
+ _stripArtifactResultTagForDisplay(_stripSubmissionTagForDisplay(rawContent)),
+ );
+ }
else if (role === 'assistant') displayContent = _stripSurvivingStructuralBlocks(rawContent);
}
const contentHtml = isHtmlSnippet
@@ -1735,7 +1742,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
? `<div class="chat-msg-header chat-msg-header-user"><span class="chat-msg-time">${formatTime(message.time || new Date().toISOString())}</span></div>`
: `<div class="chat-msg-header">${avatarHtml}<span class="chat-msg-from">${escapeHtml(headerName)}</span><span class="chat-msg-time">${formatTime(message.time || new Date().toISOString())}</span></div>`;
const planAnnHtml = message._plan_announcement
- ? `<div class="chat-plan-announce">📋 ${escapeHtml(t('chat.plan_announce'))}</div>` : '';
+ ? `<div class="chat-plan-announce">${_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
// + archive button (the legacy `.chat-meta` slot). Lives OUTSIDE the
// bubble so chips read as a footer, not as inline body content.
@@ -1776,6 +1783,12 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
_mountChatInputForm(formHost, msgDiv, message, opts);
}
}
+ // Commander → user marketplace install confirmation cards. The model can
+ // request approval, but only this human click path performs the install.
+ if (role === 'assistant' && Array.isArray(message.marketplace_requests) && message.marketplace_requests.length) {
+ const bubble = msgDiv.querySelector('.chat-bubble');
+ if (bubble) _mountMarketplaceInstallRequests(bubble, msgDiv, message, opts);
+ }
// Interactive web-app artifacts (assistant messages only) — sandboxed
// `<iframe>` over the `chat-app://` protocol, appended after the form so it
// reads as "reply text → embedded app". See chat-artifact.js.
@@ -1790,7 +1803,7 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
_attachBubbleArchiveBtn(msgDiv, () => rawContent);
}
// Persisted-process trail is independent of body type — it must render
- // for HTML-stub bodies too (e.g. CLI errors like `<span>⚠️ ...</span>`),
+ // for HTML-stub bodies too (e.g. CLI warning spans),
// otherwise after a refresh the only visible signal of a failed run is
// the red error line and "what happened" is gone. Auto-expand for any
// empty / abort-stub / HTML-stub body so the rail IS the content.
@@ -1870,6 +1883,191 @@ function _mountChatInputForm(host, msgDiv, message, opts) {
});
}
+function _marketplaceRequestKindLabel(kind) {
+ return kind === 'skill' ? t('marketplace_request.kind_skill') : t('marketplace_request.kind_agent');
+}
+
+function _marketplaceRequestStatusLabel(status) {
+ if (status === 'installed') return t('marketplace_request.status_installed');
+ if (status === 'skipped') return t('marketplace_request.status_skipped');
+ if (status === 'failed') return t('marketplace_request.status_failed');
+ return t('marketplace_request.status_pending');
+}
+
+function _marketplaceRequestAgentAvatarHtml(req) {
+ return renderAvatarHtml(req.icon || '', req.color || '', {
+ size: 32,
+ seed: req.id || req.name || 'marketplace-agent',
+ extraClass: 'marketplace-card-avatar chat-marketplace-request-avatar',
+ dataAttrs: { 'mp-avatar-slot': '1' },
+ });
+}
+
+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' },
+};
+
+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;
+}
+
+function _marketplaceRequestAuthorBadgeHtml(createUid) {
+ if (!createUid) return '';
+ const label = String(createUid) === '0'
+ ? t('marketplace.author_platform')
+ : t('marketplace.author_user').replace('{uid}', String(createUid));
+ const cls = String(createUid) === '0' ? 'marketplace-card-chip is-platform' : 'marketplace-card-chip is-user';
+ return `<span class="${cls}">${escapeHtml(label)}</span>`;
+}
+
+async function _hydrateMarketplaceRequestMeta(card, req, cid, msgId) {
+ if (!card || !req) return;
+ const hasAvatar = req.kind !== 'agent' || req.icon || req.color;
+ const hasCardMeta = req.description_zh || req.description_en || req.category || req.create_uid;
+ if (hasAvatar && hasCardMeta) return;
+ try {
+ const q = req.name || req.id || '';
+ const channel = req.kind === 'skill' ? 'marketplace.listSkills' : 'marketplace.listAgents';
+ const res = await window.orkas.invoke(channel, { q, size: 20 });
+ const row = (res?.list || []).find((x) => x && x.id === req.id);
+ if (!row) return;
+ req.icon = row.icon || '';
+ req.color = row.color || '';
+ req.description_zh = row.description_zh || '';
+ req.description_en = row.description_en || '';
+ req.category = row.category || '';
+ req.create_uid = row.create_uid || '';
+ _renderMarketplaceInstallCard(card, req, cid, msgId);
+ } catch (_) { /* fallback content is already rendered */ }
+}
+
+function _setMarketplaceCardBusy(card, busy) {
+ if (!card) return;
+ card.dataset.busy = busy ? '1' : '0';
+ card.classList.toggle('is-busy', !!busy);
+ card.querySelectorAll('button').forEach((btn) => { btn.disabled = !!busy; });
+}
+
+function _renderMarketplaceInstallCard(card, req, cid, msgId) {
+ if (!card || !req) return;
+ const status = req.status || 'pending';
+ const kind = req.kind === 'skill' ? 'skill' : 'agent';
+ card.className = `marketplace-card chat-marketplace-request is-${status}`;
+ card.dataset.marketplaceRequestId = String(req.request_id || '');
+ card.dataset.marketplaceKind = kind;
+ const name = req.name || req.id || '';
+ const kindLabel = _marketplaceRequestKindLabel(kind);
+ const statusLabel = _marketplaceRequestStatusLabel(status);
+ const version = req.version ? t('marketplace.version').replace('{version}', String(req.version)) : '';
+ const lang = getLang();
+ const descText = pickDesc(req, lang) || req.reason || '';
+ const desc = descText ? `<div class="marketplace-card-desc">${escapeHtml(descText)}</div>` : '';
+ const catLabel = _marketplaceRequestCategoryLabel(req.category, lang);
+ const meta = [
+ version ? `<span class="marketplace-card-chip is-version">${escapeHtml(version)}</span>` : '',
+ catLabel ? `<span class="marketplace-card-chip">${escapeHtml(catLabel)}</span>` : '',
+ _marketplaceRequestAuthorBadgeHtml(req.create_uid),
+ ].filter(Boolean).join('');
+ const error = req.error ? `<div class="chat-marketplace-request-error">${escapeHtml(req.error)}</div>` : '';
+ const iconHtml = kind === 'agent'
+ ? _marketplaceRequestAgentAvatarHtml(req)
+ : '';
+ const actions = status === 'pending'
+ ? `<div class="marketplace-card-actions chat-marketplace-request-actions">
+ <button type="button" class="btn btn-primary btn-sm" data-mp-decision="install">${escapeHtml(t('marketplace_request.install'))}</button>
+ <button type="button" class="btn btn-sm" data-mp-decision="skip">${escapeHtml(t('marketplace_request.skip'))}</button>
+ </div>`
+ : `<div class="marketplace-card-actions chat-marketplace-request-actions">
+ <span class="chat-marketplace-request-status">${escapeHtml(statusLabel)}</span>
+ </div>`;
+ card.innerHTML = `
+ <div class="marketplace-card-header chat-marketplace-request-head">
+ ${iconHtml}
+ <div class="chat-marketplace-request-main">
+ <div class="chat-marketplace-request-title-row">
+ <span class="marketplace-card-name chat-marketplace-request-title">${escapeHtml(name)}</span>
+ <span class="marketplace-card-chip chat-marketplace-request-kind">${escapeHtml(kindLabel)}</span>
+ </div>
+ </div>
+ </div>
+ ${desc}
+ ${error}
+ <div class="marketplace-card-footer chat-marketplace-request-footer">
+ <div class="marketplace-card-meta">${meta}</div>
+ ${actions}
+ </div>
+ `;
+
+ const installBtn = card.querySelector('[data-mp-decision="install"]');
+ const skipBtn = card.querySelector('[data-mp-decision="skip"]');
+ if (installBtn) {
+ installBtn.addEventListener('click', () => {
+ _resolveMarketplaceInstallRequest(card, { ...req, kind }, cid, msgId, 'install');
+ });
+ }
+ if (skipBtn) {
+ skipBtn.addEventListener('click', () => {
+ _resolveMarketplaceInstallRequest(card, { ...req, kind }, cid, msgId, 'skip');
+ });
+ }
+ _hydrateMarketplaceRequestMeta(card, { ...req, kind }, cid, msgId);
+}
+
+function _mountMarketplaceInstallRequests(host, msgDiv, message, opts) {
+ const cid = opts.cid || currentCid;
+ if (!cid || !host || !message) return;
+ const msgId = msgDiv.dataset.msgId || message._msg_id || '';
+ if (!msgId) return;
+ const requests = Array.isArray(message.marketplace_requests) ? message.marketplace_requests : [];
+ for (const req of requests) {
+ if (!req || !req.request_id) continue;
+ const selector = `.chat-marketplace-request[data-marketplace-request-id="${CSS.escape(String(req.request_id))}"]`;
+ if (host.querySelector(selector)) continue;
+ const card = document.createElement('div');
+ host.appendChild(card);
+ _renderMarketplaceInstallCard(card, req, cid, msgId);
+ }
+}
+
+async function _resolveMarketplaceInstallRequest(card, req, cid, msgId, decision) {
+ if (!card || card.dataset.busy === '1') return;
+ _setMarketplaceCardBusy(card, true);
+ const installBtn = card.querySelector('[data-mp-decision="install"]');
+ if (decision === 'install' && installBtn) installBtn.textContent = t('marketplace.installing');
+ try {
+ const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/marketplace-install`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ msgId, requestId: req.request_id, decision }),
+ });
+ const data = await res.json();
+ if (!data || data.ok === false) {
+ throw new Error((data && data.error) || 'marketplace install request failed');
+ }
+ const updated = data.request || { ...req, status: decision === 'install' ? 'installed' : 'skipped' };
+ _renderMarketplaceInstallCard(card, updated, cid, msgId);
+ if (updated.status === 'installed') {
+ if (updated.kind === 'agent') { try { loadAgents?.(true); } catch (_) {} }
+ else { try { loadSkills?.(true); } catch (_) {} }
+ }
+ const submissionText = data.submission && data.submission.text;
+ if (submissionText) await sendInCurrentConversation(submissionText);
+ } catch (err) {
+ _setMarketplaceCardBusy(card, false);
+ const reason = (err && err.message) || String(err);
+ _convLog.warn('marketplace install request failed', reason);
+ try { await uiAlert(t('marketplace.install_failed').replace('{reason}', reason)); } catch (_) {}
+ }
+}
+
// Insert a "process info" block above the assistant bubble content
// using the items we stored at stream time. Collapsed by default so
// old threads stay tidy; the user can click ▶ to expand. Exception:
@@ -1897,9 +2095,11 @@ function _renderPersistedProcess(msgDiv, items, { expanded = false } = {}) {
else if (item && item.type === 'event') text = _formatEventLine(item.event) || '';
if (!text) continue;
const line = document.createElement('div');
- const kind = _processKindOf(text);
+ const kind = item && item.type === 'event'
+ ? _eventProcessKind(item.event, text)
+ : _processKindOf(text);
line.className = 'stream-process-line' + (kind ? ' kind-' + kind : '');
- line.textContent = text;
+ _setProcessLineContent(line, text, kind);
body.appendChild(line);
}
if (body.childElementCount === 0) return; // nothing renderable
@@ -1954,7 +2154,7 @@ function _renderQuotePreview() {
const trunc = String(q.text || '');
const fileChips = (q.produced || []).map((p) => {
const base = String(p || '').split(/[\\/]/).pop() || p;
- return `<span class="chat-quote-file" title="${escapeHtml(p)}">📎 ${escapeHtml(base)}</span>`;
+ return `<span class="chat-quote-file" title="${escapeHtml(p)}">${_chatFileIconHtml(base)}<span class="chat-quote-file-label">${escapeHtml(base)}</span></span>`;
}).join('');
wrap.innerHTML = `
<div class="chat-quote-header">
@@ -2046,14 +2246,14 @@ function _attachBubbleArchiveBtn(msgDiv, getContent) {
const text = typeof getContent === 'function' ? (getContent() || '') : '';
if (!text.trim() || copyBtn.disabled) return;
copyBtn.disabled = true;
- const orig = copyBtn.textContent;
+ const orig = copyBtn.innerHTML;
try {
await navigator.clipboard.writeText(text);
- copyBtn.textContent = t('chat.copy_done');
+ copyBtn.innerHTML = `${_uiIconHtml('check', 'ui-icon btn-inline-icon')}<span>${escapeHtml(t('chat.copy_done'))}</span>`;
} catch (err) {
copyBtn.textContent = t('chat.copy_failed');
}
- setTimeout(() => { copyBtn.textContent = orig; copyBtn.disabled = false; }, 1500);
+ setTimeout(() => { copyBtn.innerHTML = orig; copyBtn.disabled = false; }, 1500);
});
btn.addEventListener('click', async (e) => {
e.stopPropagation();
@@ -2068,7 +2268,7 @@ function _attachBubbleArchiveBtn(msgDiv, getContent) {
});
if (!pick) return;
btn.disabled = true;
- const orig = btn.textContent;
+ const orig = btn.innerHTML;
try {
const res = await apiFetch('/api/contexts/write', {
method: 'POST',
@@ -2077,7 +2277,7 @@ function _attachBubbleArchiveBtn(msgDiv, getContent) {
});
const data = await res.json();
if (data.ok) {
- btn.textContent = t('chat.archive_done');
+ btn.innerHTML = `${_uiIconHtml('check', 'ui-icon btn-inline-icon')}<span>${escapeHtml(t('chat.archive_done'))}</span>`;
if (currentView === 'contexts' && typeof loadContexts === 'function') {
loadContexts();
}
@@ -2089,7 +2289,7 @@ function _attachBubbleArchiveBtn(msgDiv, getContent) {
btn.textContent = t('chat.archive_failed');
await uiAlert(t('chat.archive_failed_with_reason', { reason: err.message || err }));
}
- setTimeout(() => { btn.textContent = orig; btn.disabled = false; }, 2000);
+ setTimeout(() => { btn.innerHTML = orig; btn.disabled = false; }, 2000);
});
actionsRow.appendChild(actions);
}
@@ -2453,7 +2653,7 @@ function _msTs(input) {
return Date.now();
}
-function _createStreamingAssistantMessage(container) {
+function _createStreamingAssistantMessage(container, opts = {}) {
if (typeof container === 'string') container = document.getElementById(container);
if (!container) container = document.getElementById('chat-history');
const emptyEl = container.querySelector('.empty');
@@ -2495,6 +2695,10 @@ function _createStreamingAssistantMessage(container) {
</div>
`;
msg.dataset.placeholder = '1';
+ if (opts.hiddenUntilActor) {
+ msg.dataset.identityPending = '1';
+ msg.style.display = 'none';
+ }
// Pin placeholder by creation time so `_insertByTimestamp` keeps it in
// chronological order with surrounding messages. Updated to the actual
// gm.ts when the placeholder finalizes (so the bubble's position settles
@@ -2509,30 +2713,92 @@ function _hideThinking(msg) {
if (thinking) thinking.style.display = 'none';
}
-// Map the leading glyph of a formatted line to a semantic CSS class so the
-// stylesheet can tone errors red, tool calls blue, etc. The full glyph
-// palette + which event each one comes from is documented at the top of
-// `_formatEventLine`. Keep the two in sync — adding a new glyph there
-// without an entry here means the line renders in the default body color
-// (the muted slate baseline), which is what produced the "everything is
-// gray" look users complained about for CLI output.
+const _PROCESS_GLYPH_KIND = {
+ '\u25EF': 'err',
+ '\u2717': 'err',
+ '\u25CB': 'warn',
+ '\u25C9': 'patch',
+ '\u25A0': 'tool',
+ '\u25B7': 'out',
+ '\u25C6': 'think',
+ '\u25C7': 'info',
+ '\u25B6': 'bound',
+ '\u25CF': 'bound',
+ '\u25A3': 'plan',
+ '\u25D0': 'live',
+ '\u25AA': 'meta',
+};
+const _PROCESS_KIND_ICON = {
+ bound: 'play',
+ tool: 'squareFilled',
+ plan: 'clipboard-list',
+ patch: 'document-pencil',
+ think: 'diamond',
+ live: 'live',
+ out: 'output',
+ meta: 'dot',
+ warn: 'warning',
+ err: 'x-circle',
+ info: 'info',
+};
+
function _processKindOf(text) {
const g = (text || '').trimStart().charAt(0);
- if (g === '◯' || g === '✗') return 'err'; // hard error / failed tool end
- if (g === '○') return 'warn'; // awaiting approval / soft warn
- if (g === '◉') return 'patch'; // file change
- if (g === '■') return 'tool'; // tool call (start / end ok)
- if (g === '▷') return 'out'; // command / cli stdout-or-stderr
- if (g === '◆') return 'think'; // reasoning / reply marker
- if (g === '◇') return 'info'; // auto-approved permission audit (kind-info)
- if (g === '▶' || g === '●') return 'bound'; // lifecycle start / end
- if (g === '▣') return 'plan'; // plan announcement
- if (g === '◐') return 'live'; // live generating preview
- if (g === '▪') return 'meta'; // lifecycle / fallback meta
- return '';
+ return _PROCESS_GLYPH_KIND[g] || '';
}
-function _streamingAppendProgress(msg, text) {
+function _processLineText(text) {
+ return String(text || '').replace(/^\s*[\u25EF\u2717\u25CB\u25C9\u25A0\u25B7\u25C6\u25C7\u25B6\u25CF\u25A3\u25D0\u25AA]\uFE0F?\s*/u, '');
+}
+
+function _setProcessLineContent(line, text, kind) {
+ if (!line) return;
+ const body = _processLineText(text);
+ line.dataset.processText = body;
+ const icon = kind ? _uiIconHtml(_PROCESS_KIND_ICON[kind] || 'info', 'ui-icon stream-process-icon') : '';
+ line.innerHTML = `${icon}<span class="stream-process-text">${escapeHtml(body)}</span>`;
+}
+
+function _eventProcessKind(evt, text) {
+ if (!evt || typeof evt !== 'object') return _processKindOf(text);
+ const stream = evt.stream;
+ const data = evt.data || {};
+ if (stream === 'lifecycle') {
+ const p = data.phase;
+ if (p === 'error') return 'err';
+ if (p === 'start' || p === 'end') return 'bound';
+ return 'meta';
+ }
+ if (stream === 'item') return 'think';
+ if (stream === 'plan') return 'plan';
+ if (stream === 'tool') return data.isError ? 'err' : 'tool';
+ if (stream === 'command_output') return (!data.stdout && data.stderr) ? 'warn' : 'out';
+ if (stream === 'patch') return 'patch';
+ if (stream === 'approval') return 'warn';
+ if (stream === 'error') return 'err';
+ if (stream === 'cli') {
+ const type = String(data.type || '').toLowerCase();
+ if (type === 'tool-event') return 'tool';
+ if (type === 'process-info') return 'bound';
+ if (type === 'stderr-line' || type === 'idle') return 'warn';
+ if (type === 'permission-request') return 'info';
+ if (type === 'raw-line') return 'meta';
+ if (type === 'log') {
+ const level = String(data.level || 'info').toLowerCase();
+ return level === 'error' ? 'err' : level === 'warn' ? 'warn' : 'meta';
+ }
+ if (type === 'status') {
+ const st = String(data.status || '').toLowerCase();
+ if (st === 'error' || st === 'failed' || st === 'timeout') return 'err';
+ if (st === 'cancelled' || st === 'aborted') return 'warn';
+ if (st === 'session_ready' || st === 'running' || st === 'result' || st === 'completed' || st === 'usage') return 'bound';
+ return 'meta';
+ }
+ }
+ return _processKindOf(text) || 'meta';
+}
+
+function _streamingAppendProgress(msg, text, kindHint) {
// Keep the "thinking…" row visible alongside the process trace — hiding it
// while only process info shows makes long tool runs look stuck. The row
// is cleared when the final reply (or an error) arrives.
@@ -2548,9 +2814,12 @@ function _streamingAppendProgress(msg, text) {
// without being yanked back.
const innerWasAtBottom = _isNearBottom(body, 10);
const line = document.createElement('div');
- const kind = _processKindOf(text);
+ const kind = kindHint || _processKindOf(text);
line.className = 'stream-process-line' + (kind ? ' kind-' + kind : '');
- line.textContent = text;
+ if (kind === 'bound' && /^tokens\b/.test(_processLineText(text))) {
+ line.dataset.streamUsage = '1';
+ }
+ _setProcessLineContent(line, text, kind);
body.appendChild(line);
if (innerWasAtBottom) body.scrollTop = body.scrollHeight;
// Outer chat-history follows independently — its own sticky-bottom
@@ -2709,7 +2978,8 @@ function _streamingMarkAborted(msg) {
function _finishStreamingMsg(cid) {
pendingConvs.delete(cid);
- stopPolling(cid);
+ if (isGroupConversationBusy(cid)) startPolling(cid);
+ else stopPolling(cid);
_updateConvSidebarBadge(cid, false);
if (cid === currentCid) _updateConvSendUI(cid);
// Drain the next queued message for this conversation, if any.
@@ -3089,7 +3359,7 @@ function createChatController(config) {
);
if (hooks.onUserAppended) hooks.onUserAppended(userMsgEl, content, id);
- const msgEl = _createStreamingAssistantMessage(historyEl);
+ const msgEl = _createStreamingAssistantMessage(historyEl, { hiddenUntilActor: true });
if (hooks.onAssistantStart) hooks.onAssistantStart(msgEl, id);
// On send, pin the user's message to the top of the viewport once;
@@ -3311,19 +3581,52 @@ const _groupPlaceholders = new Map(); // key = `${cid}:${actorId}` → element
function _phKey(cid, actorId) { return `${cid}:${actorId || ''}`; }
-function _setPlaceholderActor(ph, actorId) {
+function _knownGroupActorLabel(cid, actorId) {
+ if (!actorId) return '';
+ if (actorId === 'commander') return t('chat.from_commander');
+ if (typeof _agentsCache !== 'undefined' && Array.isArray(_agentsCache)) {
+ const a = _agentsCache.find((x) => x && x.agent_id === actorId);
+ if (a && a.name) return a.name;
+ }
+ const cached = _groupMembersCache.get(cid) || [];
+ const a = cached.find((x) => x && x.id === actorId);
+ return a && a.name ? a.name : '';
+}
+
+function _setPlaceholderActor(ph, actorId, opts = {}) {
if (!ph) return;
+ const cid = opts.cid || currentCid;
+ const force = !!opts.force;
ph.dataset.fromActor = actorId || '';
+ const label = _knownGroupActorLabel(cid, actorId);
+ const ready = !!actorId && (actorId === 'commander' || !!label || !!opts.allowFallback);
const chip = ph.querySelector('[data-role="from-chip"]');
- if (chip && !chip.textContent) {
- const label = actorId === 'commander'
- ? (t('chat.from_commander'))
- : (_groupActorLabel(actorId) || (t('chat.from_agent_unknown')));
- chip.textContent = label;
+ if (chip && (force || !chip.textContent)) {
+ chip.textContent = label || (opts.allowFallback ? t('chat.from_agent_unknown') : '');
}
const avatarSlot = ph.querySelector('[data-role="from-avatar"]');
- if (avatarSlot && !avatarSlot.firstChild && actorId) {
- avatarSlot.innerHTML = _renderActorAvatarHtml(actorId);
+ if (avatarSlot && actorId && (force || !avatarSlot.firstChild)) {
+ avatarSlot.innerHTML = label
+ ? _renderActorAvatarHtml(actorId)
+ : '';
+ }
+ if (ph.dataset.identityPending === '1') {
+ if (ready) {
+ ph.style.display = '';
+ delete ph.dataset.identityPending;
+ } else {
+ ph.style.display = 'none';
+ }
+ }
+}
+
+function _refreshActorPlaceholders(cid, actorId) {
+ if (!cid) return;
+ for (const [key, ph] of _groupPlaceholders.entries()) {
+ 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 });
}
}
@@ -3342,15 +3645,18 @@ function _ensureActorPlaceholder(cid, actorId, fallbackPh) {
if (fallbackPh && fallbackPh.parentElement
&& fallbackPh.dataset.finalized !== '1'
&& (!fallbackPh.dataset.fromActor || fallbackPh.dataset.fromActor === actorId)) {
- _setPlaceholderActor(fallbackPh, actorId);
+ _setPlaceholderActor(fallbackPh, actorId, { cid });
_groupPlaceholders.set(k, fallbackPh);
return fallbackPh;
}
const container = document.getElementById('chat-history');
if (!container) return null;
- ph = _createStreamingAssistantMessage(container);
- _setPlaceholderActor(ph, actorId);
+ ph = _createStreamingAssistantMessage(container, { hiddenUntilActor: true });
+ _setPlaceholderActor(ph, actorId, { cid });
_groupPlaceholders.set(k, ph);
+ if (actorId && actorId !== 'commander' && !_knownGroupActorLabel(cid, actorId)) {
+ _refreshGroupMembers(cid).then(() => _refreshActorPlaceholders(cid, actorId)).catch(() => {});
+ }
return ph;
}
@@ -3399,7 +3705,7 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
}
}
// Also fill the from chip in case state_changed never set it.
- _setPlaceholderActor(ph, gm.from);
+ _setPlaceholderActor(ph, gm.from, { cid, force: true, allowFallback: true });
// Plan-announcement label (commander first plan_set).
if (gm.plan_announcement) {
@@ -3407,7 +3713,7 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
if (bubble && !bubble.querySelector('.chat-plan-announce')) {
const lbl = document.createElement('div');
lbl.className = 'chat-plan-announce';
- lbl.textContent = `📋 ${t('chat.plan_announce')}`;
+ lbl.innerHTML = `${_uiIconHtml('clipboard-list', 'ui-icon chat-plan-announce-icon')}<span>${escapeHtml(t('chat.plan_announce'))}</span>`;
bubble.insertBefore(lbl, bubble.firstChild);
}
}
@@ -3473,6 +3779,18 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
}
}
+ if (Array.isArray(gm.marketplace_requests) && gm.marketplace_requests.length) {
+ const bubble = ph.querySelector('.chat-bubble');
+ if (bubble) {
+ const reqMessage = {
+ role: 'assistant',
+ marketplace_requests: gm.marketplace_requests,
+ _msg_id: gm.id,
+ };
+ _mountMarketplaceInstallRequests(bubble, ph, reqMessage, { cid });
+ }
+ }
+
// Interactive web-app artifacts (chat-app:// iframe). Idempotent — skips
// ids already mounted in this bubble.
if (Array.isArray(gm.artifacts) && gm.artifacts.length && typeof window.mountMessageArtifacts === 'function') {
@@ -3497,6 +3815,7 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
// user's view; visible end-of-turn replies will bump shortly after).
if (evData.type === 'message' && evData.msg && !evData.msg.dispatch) {
_bumpConvToTop(cid);
+ if (window.ConversationInfo) window.ConversationInfo.refresh(cid);
}
// Cross-cid leakage guard: per-cid controllers stay alive when the user
// navigates away mid-stream (a legit pattern — let the conv finish in
@@ -3594,6 +3913,17 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
const actor = String(evData.actor || '');
const data = evData.data || {};
if (!actor) return;
+ // A renderer can attach after the actor's initial `state_changed(running)`
+ // event has already passed (refresh, tab switch, scheduled/remote run).
+ // Process events are proof that work is still active, so recover the
+ // composer state here instead of leaving the button in blue "send" mode
+ // while a live placeholder is visibly thinking.
+ if (!isGroupConversationBusy(cid)) {
+ setGroupConversationBusy(cid, true);
+ _updateConvSidebarBadge(cid, true);
+ startPolling(cid);
+ if (cid === currentCid) _updateConvSendUI(cid);
+ }
const target = _ensureActorPlaceholder(cid, actor, streamingMsg);
if (!target) return;
// Diagnostic — count how many deltas reach the renderer per actor.
@@ -3620,14 +3950,17 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
// when an interactive agent's step enters in_progress, the user's next
// reply should default to that agent without them having to @-mention.
_evaluateAutoRecipient(cid);
- if (window.PlanRail) window.PlanRail.refresh(cid);
+ if (window.PlanRail) window.PlanRail.refresh(cid, { force: true });
+ if (window.ConversationInfo) window.ConversationInfo.refresh(cid, { silent: true });
} else if (evData.type === 'state_changed') {
// Each in_flight actor gets a placeholder so its delta tokens / tool
// calls render in its own bubble even before its `message` arrives.
// Adopt the controller's initial placeholder for the first actor.
const st = evData.state || {};
- if (Array.isArray(st.in_flight)) {
- for (const actorId of st.in_flight) {
+ const inFlight = Array.isArray(st.in_flight) ? st.in_flight.slice() : [];
+ setGroupConversationBusy(cid, st.status === 'running' || inFlight.length > 0);
+ if (inFlight.length) {
+ for (const actorId of inFlight) {
if (!actorId) continue;
_ensureActorPlaceholder(cid, actorId, streamingMsg);
}
@@ -3635,7 +3968,7 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
// Mirror in_flight so _evaluateAutoRecipient knows when commander is
// mid-turn (release the chip back to commander even if plan still has
// an interactive agent's done step as the most-recent terminal).
- _latestInFlight.set(cid, Array.isArray(st.in_flight) ? st.in_flight.slice() : []);
+ _latestInFlight.set(cid, inFlight);
// state_changed also fires on plan reconcile boundaries — re-evaluate
// the auto-target so the chip matches the current dispatch state even
// when a plan_changed event was missed (e.g. on first connect).
@@ -3643,9 +3976,14 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
// Plan rail hides retry/skip/abort buttons whenever any worker is in
// flight (avoids racing user actions against an in-progress turn).
if (window.PlanRail) {
- window.PlanRail.setInFlight(cid, Array.isArray(st.in_flight) ? st.in_flight : []);
+ window.PlanRail.setInFlight(cid, inFlight);
}
+ if (window.ConversationInfo) window.ConversationInfo.refresh(cid, { silent: true });
+ _updateConvSidebarBadge(cid, false);
+ if (cid === currentCid) _updateConvSendUI(cid);
} else if (evData.type === 'aborted') {
+ setGroupConversationBusy(cid, false);
+ _latestInFlight.set(cid, []);
// 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
@@ -3670,6 +4008,8 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
_groupPlaceholders.delete(k);
if (ph && ph.parentElement) ph.remove();
}
+ _updateConvSidebarBadge(cid, false);
+ if (cid === currentCid) _updateConvSendUI(cid);
} else if (evData.type === 'turn_silent') {
// The actor's turn ended without producing a persisted message
// (executor returned outcome=silent). Two sub-cases:
@@ -3703,7 +4043,10 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
}
}
} else if (evData.type === 'member_joined') {
- // Refresh the cache so subsequent bubbles can render the agent's name.
+ // Refresh the cache so subsequent bubbles and already-mounted
+ // placeholders can render the agent's real name/avatar instead of the
+ // neutral streaming shell.
+ _rememberGroupActor(cid, evData.actor);
_refreshGroupMembers(cid);
}
}
@@ -3799,6 +4142,17 @@ function _stripArtifactResultTagForDisplay(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 /
@@ -3935,12 +4289,8 @@ function _streamingAppendFinalDelta(msg, piece) {
// exactly one semantic role — stick to this table when adding new streams:
//
// ▶ reasoning start ● reasoning done
-// ◆ thinking ◇ reply (final)
-// ◐ generating (live)
-// ■ tool call ▣ plan
-// ▷ command output ◉ file change
-// ○ awaiting confirmation ◯ error
-// ▪ other / fallback
+// Process-pane text is plain content; _eventProcessKind maps events to SVG
+// icons and semantic CSS classes.
function _formatEventLine(evt) {
if (!evt || typeof evt !== 'object') return null;
const { stream, data } = evt;
@@ -3968,7 +4318,7 @@ function _formatEventLine(evt) {
if (itemType.includes('tool') || itemType.includes('function') ||
itemType.includes('message')) return null;
const prefix = itemType.includes('reasoning') ? t('chat.stream.thinking') :
- (itemType ? `◆ ${itemType}` : '◆');
+ (itemType || t('chat.stream.thinking'));
const detail = data?.text || data?.summary || data?.name || '';
const detailStr = detail ? ` — ${String(detail).replace(/\s+/g, ' ')}` : '';
return `${prefix} ${phaseCn(data?.phase)}${detailStr}`.trim();
@@ -3988,7 +4338,6 @@ function _formatEventLine(evt) {
const phase = data?.phase || data?.status;
const p = phaseCn(phase);
const isError = !!data?.isError;
- const marker = phase === 'end' ? (isError ? '✗' : '■') : '■';
// On start → show arguments (bash command / file path / JSON fallback).
// On end → prefer result_preview so users see what the call returned.
let detail = '';
@@ -4012,23 +4361,20 @@ function _formatEventLine(evt) {
detail = detail.replace(/\s+/g, ' ').trim();
if (detail.length > 160) detail = detail.slice(0, 160) + '…';
const detailStr = detail ? ' · ' + detail : '';
- return `${marker} ${name}${p ? ' · ' + p : ''}${detailStr}`;
+ return `${name}${p ? ' · ' + p : ''}${detailStr}`;
}
if (stream === 'command_output') {
// Distinguish stderr from stdout so CLI agents (claude code / codex /
// openclaw / opencode / hermes) don't render their entire spool in a
- // single muted slate. We keep ▷ for stdout, swap to ○ (kind-warn,
- // amber) for stderr — many CLIs route progress and prompts to stderr,
- // so we stop short of treating it as a hard error (◯) which would dye
- // the whole sub-stream red. Falls back to stdout styling if the event
- // doesn't disambiguate via separate stdout/stderr fields.
+ // single muted slate. Stderr maps to kind-warn; stdout maps to kind-out.
+ // Falls back to stdout styling if the event doesn't disambiguate via
+ // separate stdout/stderr fields.
const stdout = data?.stdout;
const stderr = data?.stderr;
const text = data?.text || stdout || stderr || '';
if (!text) return t('chat.stream.command_empty');
- const isStderrOnly = !stdout && stderr;
- return isStderrOnly ? `○ ${text}` : `▷ ${text}`;
+ return String(text);
}
if (stream === 'patch') {
@@ -4063,7 +4409,7 @@ function _formatEventLine(evt) {
// CLI-backed agents (claude code / codex / openclaw / opencode / hermes)
// emit `LocalEvent`s that bus.ts wraps verbatim as `{stream:'cli', data:e}`.
// Without this branch the catch-all below dumped them as
- // `▪ cli {json}` which is (a) unreadable JSON and (b) lands in
+ // `cli {json}` which is (a) unreadable JSON and (b) lands in
// kind-meta — exactly the "all gray" symptom users see for CLI runs.
// Field shapes mirror `local_agents/backends/base.ts::LocalEvent`.
if (stream === 'cli') {
@@ -4081,17 +4427,17 @@ function _formatEventLine(evt) {
detail = detail.replace(/\s+/g, ' ').trim();
if (detail.length > 160) detail = detail.slice(0, 160) + '…';
const detailStr = detail ? ' · ' + detail : '';
- return `■ ${name}${phase ? ' · ' + phase : ''}${detailStr}`;
+ return `${name}${phase ? ' · ' + phase : ''}${detailStr}`;
}
if (cliType === 'process-info') {
// Fired once at CLI spawn; surface as a milestone so the user sees
// the run starting. cmd/args is enough — full cwd is noisy.
const cmd = String(data?.cmd || '').trim();
- return cmd ? `▶ ${cmd}` : null;
+ return cmd || null;
}
if (cliType === 'status') {
- // Bucket statuses into milestone (▶/●), warn (○) and error (◯) so
- // they pick up the right kind class downstream.
+ // Bucket statuses into milestone, warn and error so they pick up the
+ // right kind class downstream.
const st = String(data?.status || '').toLowerCase();
if (!st) return null;
// Format usage suffix when present (any status can carry it; we
@@ -4115,8 +4461,8 @@ function _formatEventLine(evt) {
}
if (tokParts.length) parts.push(tokParts.join(' '));
const cacheParts = [];
- // Spell out read/write explicitly — the earlier `cache↻ / cache✎`
- // glyphs were too cryptic. cache_read = hit on prior prompt
+ // Spell out read/write explicitly; compact cache glyphs were
+ // too cryptic. cache_read = hit on prior prompt
// prefix (1/10x price); cache_write = first-time write to the
// cache (1.25x price). Long claude turns are mostly cache_read.
if (typeof u.cacheRead === 'number') cacheParts.push('cache_read=' + u.cacheRead);
@@ -4137,22 +4483,22 @@ function _formatEventLine(evt) {
// than appending one row per pulse. See _renderAgentEvent
// for the in-place update logic.
if (!usageSuffix) return null;
- return '● tokens' + usageSuffix;
+ return 'tokens' + usageSuffix;
}
- if (st === 'session_ready' || st === 'running') return `▶ ${st}`;
- if (st === 'result' || st === 'completed') return `● ${st}${usageSuffix}`;
- if (st === 'error' || st === 'failed' || st === 'timeout') return `◯ ${st}${usageSuffix}`;
- if (st === 'cancelled' || st === 'aborted') return `○ ${st}`;
- return `▪ ${st}`;
+ if (st === 'session_ready' || st === 'running') return st;
+ if (st === 'result' || st === 'completed') return `${st}${usageSuffix}`;
+ if (st === 'error' || st === 'failed' || st === 'timeout') return `${st}${usageSuffix}`;
+ if (st === 'cancelled' || st === 'aborted') return st;
+ return st;
}
if (cliType === 'stderr-line') {
// CLIs route progress + diagnostics to stderr — treat as soft warn
- // (○, kind-warn amber) rather than a hard error (◯, kind-err red),
- // matching the heuristic we use for `command_output` stderr above.
+ // rather than a hard error, matching the heuristic we use for
+ // `command_output` stderr above.
const line = String(data?.line || '').replace(/\s+/g, ' ').trim();
if (!line) return null;
const trimmed = line.length > 160 ? line.slice(0, 160) + '…' : line;
- return `○ ${trimmed}`;
+ return trimmed;
}
// Unknown CLI event types: hide rather than dump JSON.
if (cliType === 'log') {
@@ -4164,10 +4510,7 @@ function _formatEventLine(evt) {
const msg = String(data?.message || '').replace(/\s+/g, ' ').trim();
if (!msg) return null;
const trimmed = msg.length > 200 ? msg.slice(0, 200) + '…' : msg;
- const glyph = level === 'error' ? '◯'
- : level === 'warn' ? '○'
- : '▪';
- return `${glyph} [${level}] ${trimmed}`;
+ return `[${level}] ${trimmed}`;
}
if (cliType === 'raw-line') {
// Non-JSON stdout that the backend couldn't parse as its protocol
@@ -4176,11 +4519,11 @@ function _formatEventLine(evt) {
const line = String(data?.line || '').replace(/\s+/g, ' ').trim();
if (!line) return null;
const trimmed = line.length > 200 ? line.slice(0, 200) + '…' : line;
- return `▪ ${trimmed}`;
+ return trimmed;
}
if (cliType === 'permission-request') {
// Auto-approved tool-use request the CLI gated through
- // control_request. Surface as kind-info (◇) so users can audit
+ // control_request. Surface as kind-info so users can audit
// which tools the daemon allowed without prompting.
const tool = String(data?.tool || '').trim() || 'tool';
const decision = data?.autoDecided === 'deny' ? 'denied' : 'allowed';
@@ -4190,21 +4533,21 @@ function _formatEventLine(evt) {
inputSummary = s.replace(/\s+/g, ' ').trim();
if (inputSummary.length > 120) inputSummary = inputSummary.slice(0, 120) + '…';
}
- return `◇ ${decision}: ${tool}${inputSummary ? ' · ' + inputSummary : ''}`;
+ return `${decision}: ${tool}${inputSummary ? ' · ' + inputSummary : ''}`;
}
if (cliType === 'idle') {
// Runner-emitted heartbeat on prolonged silence — kind-warn so the
// user sees the row stand out from the regular stderr noise.
const ms = Number(data?.stalledMs || 0);
const secs = Math.max(1, Math.round(ms / 1000));
- return `○ no output for ${secs}s`;
+ return `no output for ${secs}s`;
}
// Unknown CLI event types: hide rather than dump JSON. Devtools archive
// still records them verbatim under `<uid>/local/test/` for debugging.
return null;
}
- return `▪ ${stream} ${JSON.stringify(data || {})}`;
+ return `${stream} ${JSON.stringify(data || {})}`;
}
// Render a live openclaw agent event into the streaming bubble. Assistant
@@ -4241,18 +4584,19 @@ function _renderAgentEvent(msg, evt) {
// and overwrite. If none exists yet, fall through to append.
const rows = body.querySelectorAll('.stream-process-line');
for (let i = rows.length - 1; i >= 0; i--) {
- if (rows[i].textContent.startsWith('● tokens · ')) {
- rows[i].textContent = newLine;
+ if (rows[i].dataset.streamUsage === '1') {
+ _setProcessLineContent(rows[i], newLine, 'bound');
return;
}
}
}
- _streamingAppendProgress(msg, newLine);
+ _streamingAppendProgress(msg, newLine, 'bound');
return;
}
const line = _formatEventLine(evt);
if (!line) return;
+ const lineKind = _eventProcessKind(evt, line);
// All tool result rows — CLI-backed AND in-process — are
// click-to-expand. Two storage paths for the full body, decided per
// event shape:
@@ -4288,11 +4632,11 @@ function _renderAgentEvent(msg, evt) {
// reads better expanded anyway.
const truncated = path || (fullOutput && fullOutput.replace(/\s+/g, ' ').trim().length > 160);
if (truncated) {
- _streamingAppendToolResultRow(msg, line, path, fullOutput);
+ _streamingAppendToolResultRow(msg, line, path, fullOutput, lineKind);
return;
}
}
- _streamingAppendProgress(msg, line);
+ _streamingAppendProgress(msg, line, lineKind);
}
/** Append a tool-event result row that can expand its full output. Two
@@ -4307,7 +4651,7 @@ function _renderAgentEvent(msg, evt) {
* and would double the memory). A delegated click handler set up once
* per bubble does the lookup so we don't bind a closure per row.
*/
-function _streamingAppendToolResultRow(msg, previewText, outputPath, fullOutput) {
+function _streamingAppendToolResultRow(msg, previewText, outputPath, fullOutput, kindHint) {
const container = msg.querySelector('[data-role="process-container"]');
if (container) container.style.display = '';
const body = msg.querySelector('[data-role="process"]');
@@ -4315,9 +4659,9 @@ function _streamingAppendToolResultRow(msg, previewText, outputPath, fullOutput)
const innerWasAtBottom = _isNearBottom(body, 10);
const line = document.createElement('div');
- const kind = _processKindOf(previewText);
+ const kind = kindHint || _processKindOf(previewText);
line.className = 'stream-process-line is-expandable' + (kind ? ' kind-' + kind : '');
- line.textContent = previewText;
+ _setProcessLineContent(line, previewText, kind);
if (outputPath) line.dataset.toolResultPath = outputPath;
if (fullOutput) line._fullOutput = fullOutput;
line.title = t('chat.tool_result_expand_hint');
@@ -4389,7 +4733,7 @@ function _streamingUpdateLive(msg, prefix, text, appendDelta) {
let line = body.querySelector('.stream-process-live');
if (!line) {
line = document.createElement('div');
- line.className = 'stream-process-line stream-process-live';
+ line.className = 'stream-process-line stream-process-live kind-live';
body.appendChild(line);
msg._liveBuf = '';
}
@@ -4397,7 +4741,7 @@ function _streamingUpdateLive(msg, prefix, text, appendDelta) {
else msg._liveBuf = text;
// Show last ~200 chars to keep the row compact
const preview = msg._liveBuf.length > 200 ? '…' + msg._liveBuf.slice(-200) : msg._liveBuf;
- line.textContent = prefix + preview;
+ _setProcessLineContent(line, prefix + preview, 'live');
if (innerWasAtBottom) body.scrollTop = body.scrollHeight;
_stickBottomFromMsg(msg);
}
@@ -4406,6 +4750,7 @@ function _streamingUpdateLive(msg, prefix, text, appendDelta) {
function _resolveConvReply(cid, text, isError) {
const state = pendingConvs.get(cid);
pendingConvs.delete(cid);
+ setGroupConversationBusy(cid, false);
stopPolling(cid);
_updateConvSidebarBadge(cid, false);
@@ -4494,11 +4839,16 @@ function _renderConvDisabledBanner(cid) {
function abortConvStream(cid) {
const state = pendingConvs.get(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 (_) {}
- if (!state) return;
+ if (!state) {
+ _updateConvSidebarBadge(cid, false);
+ if (cid === currentCid) _updateConvSendUI(cid);
+ return;
+ }
// No-controller case: the pendingConvs entry was minted by
// `loadConversationHistory`'s polling-rescue branch (user opened a conv
// whose worker was started from outside this renderer — scheduled-task
@@ -4544,7 +4894,7 @@ function _updateConvSidebarBadge(cid, _unused) {
// clears when main emits `done`, which can trail the stop click; until then
// the bubble already shows the "stopped" state so the streaming badge would lie.
const state = pendingConvs.get(cid);
- const pending = !!state && !state.aborted;
+ const pending = isConvPending(cid) && !(state && state.aborted);
// Use _getQueue so a queue persisted in localStorage is picked up even if
// the conversation hasn't been opened in this session yet.
const queued = _getQueue(cid).length;
@@ -4576,4 +4926,3 @@ function _refreshAllConvBadges() {
if (cid) _updateConvSidebarBadge(cid);
});
}
-
diff --git a/src/renderer/modules/i18n.js b/src/renderer/modules/i18n.js
index f432831d..ad2f8dcb 100644
--- a/src/renderer/modules/i18n.js
+++ b/src/renderer/modules/i18n.js
@@ -2,8 +2,8 @@
//
// Contract:
// initI18n() – called once at boot
-// t(key, vars?) – sync lookup, current lang → en → raw key
-// getLang() – 'zh' | 'en'
+// t(key, vars?) – sync lookup, current lang → fallback → raw key
+// getLang() – current UI language code
// setLang(lang) – persists via IPC, refreshes DOM,
// dispatches 'i18n-change' on window
// applyDomI18n(root?) – fills [data-i18n] /
@@ -11,7 +11,7 @@
// [data-i18n-title] under root (or
// document)
//
-// Tables ship under `src/renderer/locales/{zh,en}.json`. The primary delivery
+// Tables ship under `src/renderer/locales/*.json`. The primary delivery
// is a synchronous `ipcRenderer.sendSync('orkas:bootI18n')` in preload, which
// hands the renderer `{lang, tables}` before any DOM script runs — see the
// `_bootSyncI18n` IIFE below. The async `window.orkas.getLocales` /
@@ -27,9 +27,47 @@
const _i18nLog = createLogger('i18n');
let _currentLang = 'en';
-let _tables = { zh: {}, en: {} };
+let _tables = {};
let _ready = false;
+const _LOCALES = [
+ { code: 'zh', label: '简体中文', htmlLang: 'zh-CN', intlLocale: 'zh-CN', fallback: 'en' },
+ { code: 'en', label: 'English', htmlLang: 'en', intlLocale: 'en-US', fallback: null },
+ { code: 'ja', label: '日本語', htmlLang: 'ja', intlLocale: 'ja-JP', fallback: 'en' },
+];
+const _LOCALE_BY_CODE = _LOCALES.reduce((acc, meta) => {
+ acc[meta.code] = meta;
+ return acc;
+}, {});
+
+function isSupportedLang(lang) {
+ return !!_LOCALE_BY_CODE[lang];
+}
+
+function getSupportedLanguages() {
+ return _LOCALES.map((meta) => ({ ...meta }));
+}
+
+function getLocaleMeta(lang) {
+ return _LOCALE_BY_CODE[lang] || _LOCALE_BY_CODE.en;
+}
+
+function fallbackChain(lang) {
+ const out = [];
+ const seen = new Set();
+ let cur = isSupportedLang(lang) ? lang : 'en';
+ while (cur && !seen.has(cur)) {
+ out.push(cur);
+ seen.add(cur);
+ cur = getLocaleMeta(cur).fallback;
+ }
+ return out;
+}
+
+function _setDocumentLang(lang) {
+ document.documentElement.setAttribute('lang', getLocaleMeta(lang).htmlLang);
+}
+
// Synchronous boot path. preload.js does `ipcRenderer.sendSync('orkas:bootI18n')`
// and exposes the result on `window.__orkasI18nBoot` BEFORE any DOM scripts
// run. By the time this script tag executes (index.html line 1118 — after all
@@ -41,11 +79,11 @@ let _ready = false;
try {
const boot = (typeof window !== 'undefined') ? window.__orkasI18nBoot : null;
if (!boot || !boot.tables) return;
- if (boot.lang === 'zh' || boot.lang === 'en') _currentLang = boot.lang;
- _tables = { zh: boot.tables.zh || {}, en: boot.tables.en || {} };
+ if (isSupportedLang(boot.lang)) _currentLang = boot.lang;
+ _tables = boot.tables || {};
_ready = true;
applyDomI18n();
- document.documentElement.setAttribute('lang', _currentLang);
+ _setDocumentLang(_currentLang);
} catch (err) {
_i18nLog.warn('sync i18n boot failed; falling back to async', {
error: (err && err.message) || String(err),
@@ -59,8 +97,11 @@ function _lookup(key, lang) {
}
function t(key, vars) {
- let raw = _lookup(key, _currentLang);
- if (raw == null && _currentLang !== 'en') raw = _lookup(key, 'en');
+ let raw;
+ for (const lang of fallbackChain(_currentLang)) {
+ raw = _lookup(key, lang);
+ if (raw != null) break;
+ }
if (raw == null) raw = key;
if (!vars) return raw;
return raw.replace(/\{(\w+)\}/g, (m, name) => (vars[name] != null ? String(vars[name]) : m));
@@ -73,26 +114,23 @@ async function initI18n() {
try {
const langRes = await window.orkas.getLanguage();
const localesRes = await window.orkas.getLocales();
- if (langRes && langRes.ok && (langRes.language === 'zh' || langRes.language === 'en')) {
+ if (langRes && langRes.ok && isSupportedLang(langRes.language)) {
_currentLang = langRes.language;
}
if (localesRes && localesRes.ok && localesRes.tables) {
- _tables = {
- zh: localesRes.tables.zh || {},
- en: localesRes.tables.en || {},
- };
+ _tables = localesRes.tables || {};
}
} catch (err) {
_i18nLog.warn('initI18n failed, using defaults', { error: (err && err.message) || String(err) });
}
_ready = true;
applyDomI18n();
- document.documentElement.setAttribute('lang', _currentLang);
+ _setDocumentLang(_currentLang);
return _currentLang;
}
async function setLang(lang) {
- if (lang !== 'zh' && lang !== 'en') return _currentLang;
+ if (!isSupportedLang(lang)) return _currentLang;
if (lang === _currentLang) return _currentLang;
try {
const res = await window.orkas.setLanguage(lang);
@@ -106,7 +144,7 @@ async function setLang(lang) {
_currentLang = lang;
}
applyDomI18n();
- document.documentElement.setAttribute('lang', _currentLang);
+ _setDocumentLang(_currentLang);
window.dispatchEvent(new CustomEvent('i18n-change', { detail: { lang: _currentLang } }));
return _currentLang;
}
diff --git a/src/renderer/modules/icons.js b/src/renderer/modules/icons.js
new file mode 100644
index 00000000..8d0c1c78
--- /dev/null
+++ b/src/renderer/modules/icons.js
@@ -0,0 +1,152 @@
+// Shared inline SVG icons for the PC renderer.
+// Keep all reusable app icons here; call sites render by name instead of
+// hardcoding SVG paths or using emoji.
+(function () {
+ const root = typeof window !== 'undefined' ? window : globalThis;
+
+ const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'webp', 'gif', 'svg', 'bmp', 'ico']);
+ const VIDEO_EXTS = new Set(['mp4', 'webm', 'mov', 'm4v', 'ogv', 'avi', 'mkv']);
+ const AUDIO_EXTS = new Set(['mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac']);
+ const TEXT_EXTS = new Set(['md', 'markdown', 'txt', 'log', 'rst', 'tex']);
+ const DATA_EXTS = new Set(['json', 'yaml', 'yml', 'toml', 'csv', 'tsv', 'xlsx', 'xls', 'xml', 'ini', 'conf']);
+ const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', '7z', 'rar']);
+ const CODE_EXTS = new Set([
+ 'py', 'pyi', 'ipynb',
+ 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs',
+ 'html', 'htm', 'css', 'scss', 'sass', 'less',
+ 'sh', 'bash', 'zsh', 'fish', 'ps1', 'bat', 'cmd',
+ 'rb', 'go', 'rs', 'java', 'kt', 'kts', 'scala',
+ 'c', 'cpp', 'cc', 'cxx', 'h', 'hpp', 'hxx',
+ 'php', 'swift', 'lua', 'pl', 'pm', 'r', 'dart',
+ 'sql', 'graphql', 'gql', 'proto',
+ ]);
+
+ function wrapUiIcon(name, inner, className) {
+ const cls = `${className || 'ui-icon'} is-${name}`;
+ return `<svg class="${cls}" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${inner}</svg>`;
+ }
+
+ function wrapFileIcon(kind, inner) {
+ return `<svg class="chat-file-kind-icon is-${kind}" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${inner}</svg>`;
+ }
+
+ const UI_ICONS = {
+ search: '<circle cx="11" cy="11" r="7"></circle><path d="m21 21-4.3-4.3"></path>',
+ settings: '<circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3 1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8 1.7 1.7 0 0 0 1.5 1h.1a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"></path>',
+ terminal: '<path d="m8 8 4 4-4 4"></path><path d="M14 16h4"></path><rect x="3" y="4" width="18" height="16" rx="3"></rect>',
+ x: '<path d="M18 6 6 18M6 6l12 12"></path>',
+ mic: '<path d="M12 3a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V6a3 3 0 0 0-3-3z"></path><path d="M19 11a7 7 0 0 1-14 0"></path><path d="M12 18v3"></path><path d="M8 21h8"></path>',
+ send: '<path d="M22 2 11 13"></path><path d="m22 2-7 20-4-9-9-4 20-7z"></path>',
+ stop: '<rect x="6" y="6" width="12" height="12" rx="2"></rect>',
+ 'chevron-down': '<path d="m6 9 6 6 6-6"></path>',
+ 'panel-list': '<rect x="3" y="4" width="18" height="16" rx="2"></rect><path d="M15 4v16"></path><path d="M7 8h4"></path><path d="M7 12h4"></path><path d="M7 16h4"></path>',
+ folder: '<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>',
+ 'folder-open': '<path d="M3 8V6a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v1"></path><path d="M3.2 10.5A2 2 0 0 1 5.1 9h14.2a1.5 1.5 0 0 1 1.4 1.9l-1.5 5.7A3 3 0 0 1 16.3 19H5.2a2 2 0 0 1-2-1.6L2 12.4a1.6 1.6 0 0 1 1.2-1.9z"></path>',
+ file: '<path d="M7 3.5h7l4 4v13H7z"></path><path d="M14 3.5v4h4"></path>',
+ 'clipboard-list': '<rect x="4" y="4" width="16" height="18" rx="2"></rect><path d="M9 4h6M9 8h6M8 12h8M8 16h8M8 20h5"></path><path d="M9 2h6v4H9z"></path>',
+ hourglass: '<path d="M7 3h10M7 21h10M8 3c0 5 8 5 8 9s-8 4-8 9M16 3c0 5-8 5-8 9s8 4 8 9"></path>',
+ play: '<circle cx="12" cy="12" r="9"></circle><path d="M10 8l6 4-6 4z"></path>',
+ 'play-triangle': '<path d="M8 5v14l11-7z" fill="currentColor" stroke="none"></path>',
+ check: '<path d="M5 12l4 4L19 6"></path>',
+ 'check-circle': '<circle cx="12" cy="12" r="9"></circle><path d="M8 12.5l2.6 2.6L16.5 9"></path>',
+ 'x-circle': '<circle cx="12" cy="12" r="9"></circle><path d="M9 9l6 6M15 9l-6 6"></path>',
+ 'skip-forward': '<path d="M5 7l6 5-6 5z"></path><path d="M13 7l6 5-6 5z"></path><path d="M21 6v12"></path>',
+ 'document-pencil': '<path d="M7 3.5h7l4 4v13H7z"></path><path d="M14 3.5v4h4"></path><path d="M9 17l1-3 5.5-5.5 2 2L12 16l-3 1z"></path>',
+ refresh: '<path d="M20 12a8 8 0 0 1-13.7 5.7"></path><path d="M4 12A8 8 0 0 1 17.7 6.3"></path><path d="M17 3v4h-4M7 21v-4h4"></path>',
+ warning: '<path d="M12 3l10 18H2z"></path><path d="M12 9v5"></path><path d="M12 18h.01"></path>',
+ square: '<rect x="5" y="5" width="14" height="14" rx="3"></rect>',
+ pencil: '<path d="M5 18.5l3.5-.8 9-9-2.2-2.2-9 9L5 18.5z"></path><path d="M13.5 6.5l2 2"></path>',
+ eye: '<path d="M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6z"></path><circle cx="12" cy="12" r="2.5"></circle>',
+ command: '<path d="M9 9H6.5a3 3 0 1 1 3-3V18a3 3 0 1 1-3-3H18a3 3 0 1 1-3 3V6a3 3 0 1 1 3 3H9z"></path>',
+ link: '<path d="M10 13a5 5 0 0 0 7.1 0l2-2a5 5 0 0 0-7.1-7.1l-1.1 1.1"></path><path d="M14 11a5 5 0 0 0-7.1 0l-2 2a5 5 0 0 0 7.1 7.1l1.1-1.1"></path>',
+ image: '<rect x="3.5" y="4.5" width="17" height="15" rx="2.5"></rect><circle cx="8.5" cy="9" r="1.6"></circle><path d="M5 17l4.4-4.4a1.5 1.5 0 0 1 2.1 0L14 15l2-2a1.5 1.5 0 0 1 2.1 0L20 14.9"></path>',
+ list: '<path d="M9 6h11M9 12h11M9 18h11"></path><path d="M4 6h.01M4 12h.01M4 18h.01"></path>',
+ 'list-ordered': '<path d="M10 6h10M10 12h10M10 18h10"></path><path d="M4 5h1v3M4 8h2"></path><path d="M4 11.5h2L4 14h2"></path><path d="M4 17h2v3H4"></path>',
+ quote: '<path d="M9 7H5v5h4v5H4"></path><path d="M20 7h-4v5h4v5h-5"></path>',
+ code: '<path d="m9 8-4 4 4 4"></path><path d="m15 8 4 4-4 4"></path>',
+ 'code-block': '<path d="M8 9l-3 3 3 3"></path><path d="M16 9l3 3-3 3"></path><path d="M12 6l-2 12"></path><rect x="3.5" y="4.5" width="17" height="15" rx="2.5"></rect>',
+ circle: '<circle cx="12" cy="12" r="7"></circle>',
+ squareFilled: '<rect x="6" y="6" width="12" height="12" rx="2"></rect>',
+ diamond: '<path d="M12 4l8 8-8 8-8-8z"></path>',
+ dot: '<circle cx="12" cy="12" r="3" fill="currentColor" stroke="none"></circle>',
+ output: '<path d="M5 7l6 5-6 5z"></path><path d="M13 7h6"></path><path d="M13 12h6"></path><path d="M13 17h6"></path>',
+ info: '<circle cx="12" cy="12" r="9"></circle><path d="M12 11v5"></path><path d="M12 8h.01"></path>',
+ live: '<path d="M12 4a8 8 0 1 1-8 8"></path><path d="M12 4v8h8"></path>',
+ };
+
+ const FILE_ICONS = {
+ image: wrapFileIcon('image', '<rect x="3.5" y="4.5" width="17" height="15" rx="2.5"></rect><circle cx="8.5" cy="9" r="1.6"></circle><path d="M5 17l4.4-4.4a1.5 1.5 0 0 1 2.1 0L14 15l2-2a1.5 1.5 0 0 1 2.1 0L20 14.9"></path>'),
+ video: wrapFileIcon('video', '<rect x="3.5" y="5.5" width="17" height="13" rx="2.5"></rect><path d="M10 9.2v5.6l5-2.8-5-2.8z"></path>'),
+ audio: wrapFileIcon('audio', '<path d="M9 18V6l9-2v12"></path><circle cx="6.5" cy="18" r="2.5"></circle><circle cx="15.5" cy="16" r="2.5"></circle>'),
+ pdf: wrapFileIcon('pdf', '<path d="M7 3.5h7l4 4v13H7z"></path><path d="M14 3.5v4h4"></path><path d="M8.8 15.5h6.4"></path><path d="M9.8 12h4.4"></path>'),
+ doc: wrapFileIcon('doc', '<path d="M7 3.5h7l4 4v13H7z"></path><path d="M14 3.5v4h4"></path><path d="M9.5 11h5"></path><path d="M9.5 14h5"></path><path d="M9.5 17h3.5"></path>'),
+ text: wrapFileIcon('text', '<path d="M6.5 4.5h11v15h-11z"></path><path d="M9 9h6"></path><path d="M9 12h6"></path><path d="M9 15h4"></path>'),
+ data: wrapFileIcon('data', '<rect x="4.5" y="5.5" width="15" height="13" rx="2"></rect><path d="M4.5 10h15"></path><path d="M9.5 5.5v13"></path><path d="M14.5 5.5v13"></path>'),
+ archive: wrapFileIcon('archive', '<path d="M5 8.5 12 5l7 3.5-7 3.5L5 8.5z"></path><path d="M5 8.5v7L12 19l7-3.5v-7"></path><path d="M12 12v7"></path>'),
+ code: wrapFileIcon('code', '<path d="m9 8-4 4 4 4"></path><path d="m15 8 4 4-4 4"></path><path d="m13 6-2 12"></path>'),
+ file: wrapFileIcon('file', '<path d="M7 3.5h7l4 4v13H7z"></path><path d="M14 3.5v4h4"></path>'),
+ };
+
+ function extOf(name) {
+ const base = String(name || '').split(/[\\/]/).pop() || '';
+ const idx = base.lastIndexOf('.');
+ return idx >= 0 ? base.slice(idx + 1).toLowerCase() : '';
+ }
+
+ function normalizeFileKind(kind, ext) {
+ const raw = String(kind || '').toLowerCase();
+ if (raw === 'docx' || raw === 'doc') return 'doc';
+ if (raw === 'spreadsheet') return 'data';
+ if (raw === 'binary') return 'file';
+ if (['image', 'video', 'audio', 'pdf', 'doc', 'text', 'data', 'archive', 'code', 'file'].includes(raw)) return raw;
+ if (IMAGE_EXTS.has(ext)) return 'image';
+ if (VIDEO_EXTS.has(ext)) return 'video';
+ if (AUDIO_EXTS.has(ext)) return 'audio';
+ if (ext === 'pdf') return 'pdf';
+ if (ext === 'docx' || ext === 'doc') return 'doc';
+ if (TEXT_EXTS.has(ext)) return 'text';
+ if (DATA_EXTS.has(ext)) return 'data';
+ if (ARCHIVE_EXTS.has(ext)) return 'archive';
+ if (CODE_EXTS.has(ext)) return 'code';
+ return 'file';
+ }
+
+ function uiIconHtml(name, className) {
+ const key = String(name || 'info');
+ return wrapUiIcon(key, UI_ICONS[key] || UI_ICONS.info, className);
+ }
+
+ function fileKindForName(name, kind) {
+ return normalizeFileKind(kind, extOf(name));
+ }
+
+ function fileKindIconHtml(name, kind) {
+ const normalized = fileKindForName(name, kind);
+ return FILE_ICONS[normalized] || FILE_ICONS.file;
+ }
+
+ function hydrateUiIcons(rootEl) {
+ if (typeof document === 'undefined') return;
+ const scope = rootEl || document;
+ const nodes = scope.querySelectorAll ? scope.querySelectorAll('[data-ui-icon]') : [];
+ nodes.forEach((node) => {
+ const name = node.getAttribute('data-ui-icon');
+ const className = node.getAttribute('data-ui-icon-class') || 'ui-icon';
+ node.innerHTML = uiIconHtml(name, className);
+ node.setAttribute('aria-hidden', 'true');
+ });
+ }
+
+ root.uiIconHtml = uiIconHtml;
+ root.hydrateUiIcons = hydrateUiIcons;
+ root.fileKindForName = fileKindForName;
+ root.fileKindIconHtml = fileKindIconHtml;
+
+ if (typeof document !== 'undefined') {
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', () => hydrateUiIcons(), { once: true });
+ } else {
+ hydrateUiIcons();
+ }
+ }
+})();
diff --git a/src/renderer/modules/ipc-shim.js b/src/renderer/modules/ipc-shim.js
index d7c23fa1..c94dc53d 100644
--- a/src/renderer/modules/ipc-shim.js
+++ b/src/renderer/modules/ipc-shim.js
@@ -69,6 +69,7 @@ const _IPC_ROUTES = [
['POST', /^\/api\/conversations\/([^/]+)\/plan\/steps\/(\d+)\/skip$/, 'groupChat.skipStep', ['cid', 'stepIndex']],
['POST', /^\/api\/conversations\/([^/]+)\/events\/stream$/, 'groupChat.events', ['cid'], { stream: true }],
['POST', /^\/api\/conversations\/([^/]+)\/form-submitted$/, 'groupChat.markFormSubmitted', ['cid']],
+ ['POST', /^\/api\/conversations\/([^/]+)\/marketplace-install$/, 'groupChat.resolveMarketplaceInstallRequest', ['cid']],
['GET', /^\/api\/conversations\/([^/]+)\/attachments$/, 'conversations.attachments.list', ['cid']],
['POST', /^\/api\/conversations\/([^/]+)\/attachments\/upload$/, { upload: 'conversations.attachments.upload' }, ['cid']],
['DELETE', /^\/api\/conversations\/([^/]+)\/attachments$/, 'conversations.attachments.delete', ['cid']],
@@ -268,4 +269,3 @@ function apiFetch(url, options) {
return window.orkas.invoke(channel, payload).then(_mockJsonResponse);
}
-
diff --git a/src/renderer/modules/kb-picker.js b/src/renderer/modules/kb-picker.js
index 2a64191a..bbfddc82 100644
--- a/src/renderer/modules/kb-picker.js
+++ b/src/renderer/modules/kb-picker.js
@@ -18,6 +18,13 @@ let _kbPickerCurrentDir = ''; // '' = root
let _kbPickerExpanded = new Set();
let _kbPickerTree = [];
+function _kbPickerUiIconHtml(name, className) {
+ if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {
+ return window.uiIconHtml(name, className);
+ }
+ return '';
+}
+
/**
* Open the picker. Resolves with `{ path }` where `path` is KB-relative
* (e.g. "notes/meeting.md"); resolves with `null` on cancel or background
@@ -89,7 +96,7 @@ function _kbPickerRenderTree() {
let html = `
<div class="${rootClass}" data-kb-picker-dir="">
<span class="kb-picker-caret kb-picker-caret-empty"></span>
- <span class="kb-picker-icon">${ICON_FOLDER_OPEN}</span>
+ <span class="kb-picker-icon">${_kbPickerUiIconHtml('folder-open', 'kb-picker-folder-icon')}</span>
<span class="kb-picker-label">${escapeHtml(t('contexts.root_label'))}</span>
</div>
`;
@@ -105,7 +112,9 @@ function _kbPickerRenderNodes(nodes, depth) {
.map((n) => {
const open = _kbPickerExpanded.has(n.path);
const active = _kbPickerCurrentDir === n.path ? ' active' : '';
- const icon = open ? ICON_FOLDER_OPEN : ICON_FOLDER_CLOSED;
+ const icon = open
+ ? _kbPickerUiIconHtml('folder-open', 'kb-picker-folder-icon')
+ : _kbPickerUiIconHtml('folder', 'kb-picker-folder-icon');
const childrenHtml = open
? _kbPickerRenderNodes(n.children || [], depth + 1)
: '';
diff --git a/src/renderer/modules/marketplace.js b/src/renderer/modules/marketplace.js
index 144386e4..9fead6a6 100644
--- a/src/renderer/modules/marketplace.js
+++ b/src/renderer/modules/marketplace.js
@@ -605,7 +605,7 @@ function _mpRender() {
const chips = [
`<button type="button" class="marketplace-chip${_mpState.category === '' ? ' is-active' : ''}" data-mp-cat="">${escapeHtml(t('marketplace.all'))}</button>`,
...cats.map((c) => {
- const label = lang === 'zh' ? (c.name_zh || c.name_en || c.code) : (c.name_en || c.name_zh || c.code);
+ const label = pickLocalizedName(c, lang) || c.code;
const active = _mpState.category === c.code ? ' is-active' : '';
return `<button type="button" class="marketplace-chip${active}" data-mp-cat="${escapeHtml(c.code)}">${escapeHtml(label)}</button>`;
}),
@@ -732,7 +732,7 @@ function _mpCategoryLabel(code, lang) {
if (!code) return '';
const c = _mpState.categories.find((x) => x.code === code);
if (!c) return code;
- return lang === 'zh' ? (c.name_zh || c.name_en || code) : (c.name_en || c.name_zh || code);
+ return pickLocalizedName(c, lang) || code;
}
// ─── Detail view rendering ───
@@ -1080,7 +1080,7 @@ async function mountMarketplaceCategorySelect(elId, initialValue = '') {
_aiSelectMount(el, {
options: categories.map((c) => ({
value: c.code,
- label: lang === 'zh' ? (c.name_zh || c.name_en || c.code) : (c.name_en || c.name_zh || c.code),
+ label: pickLocalizedName(c, lang) || c.code,
})),
value: initialValue || (categories[0] && categories[0].code) || '',
});
diff --git a/src/renderer/modules/plan-rail.js b/src/renderer/modules/plan-rail.js
index cdbbac24..0fc6f785 100644
--- a/src/renderer/modules/plan-rail.js
+++ b/src/renderer/modules/plan-rail.js
@@ -9,7 +9,7 @@
* - On `failed` steps (and only when state.in_flight is empty),
* surface retry / skip / abort actions wired to IPC
* - On `pending` steps with `transient_attempts > 0`, render a small
- * `🔁 N/2` badge so users see the auto-retry in flight (otherwise the
+ * retry badge so users see the auto-retry in flight (otherwise the
* transient retry would silently look like the step is just stuck)
* - Click a step row → scroll chat-history to that step's `output_msg_id`
*
@@ -22,24 +22,143 @@ const _planRailLog = createLogger('plan-rail');
// FIXED status → icon mapping. Single source of truth — no LLM input,
// no backend, no locales should ever inject a different glyph.
const STATUS_ICON = {
- pending: '⏳',
- in_progress: '▶️',
- done: '✅',
- failed: '❌',
- skipped: '⏭️',
- blocked: '📝',
+ pending: 'hourglass',
+ in_progress: 'play',
+ done: 'check-circle',
+ failed: 'x-circle',
+ skipped: 'skip-forward',
+ blocked: 'document-pencil',
};
-const TRANSIENT_BADGE_ICON = '🔁';
+const TRANSIENT_BADGE_ICON = 'refresh';
const MAX_TRANSIENT_RETRIES = 2; // mirrors plan_executor.ts
+function _planIcon(name, className) {
+ if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') return window.uiIconHtml(name, className || 'ui-icon plan-rail-svg-icon');
+ return '';
+}
+
let _currentCid = null;
let _currentInFlight = [];
let _refreshInflight = null; // dedup overlapping refresh requests
+let _refreshSeq = 0; // invalidate stale forced refresh responses
+let _lastPlan = null;
+const _stepActionRequests = new Set();
function _isStepActionable(step, inFlight) {
return step.status === 'failed' && (!inFlight || inFlight.length === 0);
}
+function _stepActionKey(cid, stepIndex) {
+ return `${cid || ''}:${Number(stepIndex) || 0}`;
+}
+
+function _hasStepActionRequest(step) {
+ if (!_currentCid || !step) return false;
+ return _stepActionRequests.has(_stepActionKey(_currentCid, step.index));
+}
+
+function _setStepActionRequest(cid, stepIndex, pending) {
+ const key = _stepActionKey(cid, stepIndex);
+ if (pending) _stepActionRequests.add(key);
+ else _stepActionRequests.delete(key);
+}
+
+function _clearStepActionRequests(cid) {
+ const prefix = `${cid || ''}:`;
+ for (const key of Array.from(_stepActionRequests)) {
+ if (!cid || key.startsWith(prefix)) _stepActionRequests.delete(key);
+ }
+}
+
+function _pruneStepActionRequests(plan) {
+ if (!_currentCid || !plan || !Array.isArray(plan.steps)) return;
+ const liveSteps = new Set(
+ plan.steps
+ .filter(Boolean)
+ .map((s) => _stepActionKey(_currentCid, s.index)),
+ );
+ const prefix = `${_currentCid}:`;
+ for (const key of Array.from(_stepActionRequests)) {
+ if (key.startsWith(prefix) && !liveSteps.has(key)) _stepActionRequests.delete(key);
+ }
+}
+
+function _lockRenderedStepActions(stepEl) {
+ if (!stepEl) return;
+ stepEl.querySelectorAll('[data-action]').forEach((el) => {
+ el.disabled = true;
+ el.setAttribute('aria-disabled', 'true');
+ });
+}
+
+function _applyOptimisticStepStatus(cid, stepIndex, status, patch = {}) {
+ if (!cid || cid !== _currentCid || !_lastPlan || !Array.isArray(_lastPlan.steps)) return;
+ const steps = _lastPlan.steps.map((step) => {
+ if (!step || Number(step.index) !== Number(stepIndex)) return step;
+ return { ...step, ...patch, status };
+ });
+ _render({ ..._lastPlan, steps });
+}
+
+function _rerenderCachedPlan() {
+ if (_lastPlan) _render(_lastPlan);
+}
+
+function _beginStepAction(cid, stepIndex, stepEl, optimistic = null) {
+ _setStepActionRequest(cid, stepIndex, true);
+ // A recovery click changes the local interaction contract immediately:
+ // any older plan fetch that resolves after this point must not repaint the
+ // failed row and resurrect retry / skip / abort while the POST is in flight.
+ _refreshSeq += 1;
+ _refreshInflight = null;
+ _lockRenderedStepActions(stepEl);
+ if (optimistic && optimistic.status) {
+ _applyOptimisticStepStatus(cid, stepIndex, optimistic.status, optimistic.patch || {});
+ } else {
+ _rerenderCachedPlan();
+ }
+}
+
+async function _finishStepAction(cid, stepIndex, opts = {}) {
+ const refreshPromise = PlanRail.refresh(cid, { force: true });
+ if (opts.refreshInfo) _refreshConversationInfo(cid);
+ if (opts.clearAfterRefresh) {
+ try { await refreshPromise; }
+ finally {
+ _setStepActionRequest(cid, stepIndex, false);
+ if (cid === _currentCid) _rerenderCachedPlan();
+ }
+ return;
+ }
+ _setStepActionRequest(cid, stepIndex, false);
+ if (opts.rerender && cid === _currentCid) _rerenderCachedPlan();
+}
+
+function _refreshConversationInfo(cid) {
+ if (window.ConversationInfo && typeof window.ConversationInfo.refresh === 'function') {
+ window.ConversationInfo.refresh(cid, { silent: true });
+ }
+}
+
+async function _postStepAction(cid, stepIndex, action) {
+ const res = await apiFetch(
+ `/api/conversations/${encodeURIComponent(cid)}/plan/steps/${stepIndex}/${action}`,
+ { method: 'POST' },
+ );
+ return res.json().catch(() => ({}));
+}
+
+function _alertStepActionFailure(action, reason) {
+ const normalized = reason || 'unknown';
+ if (action === 'retry') {
+ uiAlert(t('plan.error.retry_failed', { reason: normalized }) || `Retry failed: ${normalized}`);
+ } else if (action === 'skip') {
+ uiAlert(t('plan.error.skip_failed', { reason: normalized }) || `Skip failed: ${normalized}`);
+ } else if (action === 'abort') {
+ uiAlert(t('plan.error.abort_failed', { reason: normalized }) || `Abort failed: ${normalized}`);
+ }
+}
+
function _formatAssigneeMeta(raw) {
const a = (raw || '').trim();
if (!a) return '';
@@ -50,7 +169,7 @@ function _formatAssigneeMeta(raw) {
}
function _buildStepHtml(step) {
- const icon = STATUS_ICON[step.status] || STATUS_ICON.pending;
+ const icon = _planIcon(STATUS_ICON[step.status] || STATUS_ICON.pending, 'ui-icon plan-rail-svg-icon');
const num = `${step.index}.`;
const title = escapeHtml(step.title || '');
// assignee literals `commander` / `user` are role tokens (commander wrote them via
@@ -60,12 +179,13 @@ function _buildStepHtml(step) {
const meta = _formatAssigneeMeta(step.assignee);
const transient = (step.status === 'pending' || step.status === 'in_progress')
&& Number(step.transient_attempts) > 0
- ? `<span class="plan-rail-step-transient">${TRANSIENT_BADGE_ICON} ${step.transient_attempts}/${MAX_TRANSIENT_RETRIES}</span>`
+ ? `<span class="plan-rail-step-transient">${_planIcon(TRANSIENT_BADGE_ICON, 'ui-icon plan-rail-transient-icon')}<span>${step.transient_attempts}/${MAX_TRANSIENT_RETRIES}</span></span>`
: '';
const reason = step.failure_reason
? `<div class="plan-rail-step-reason">${escapeHtml(step.failure_reason)}</div>`
: '';
- const actions = _isStepActionable(step, _currentInFlight)
+ const actionRequested = _hasStepActionRequest(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>
@@ -102,14 +222,17 @@ function _render(plan) {
// right).
const wrap = root.closest('.chat-input-wrapper');
if (!plan || !Array.isArray(plan.steps) || plan.steps.length === 0) {
+ _lastPlan = null;
root.style.display = 'none';
body.innerHTML = '';
progress.textContent = '';
if (wrap) wrap.classList.remove('has-plan-rail');
return;
}
+ _lastPlan = plan;
root.style.display = '';
if (wrap) wrap.classList.add('has-plan-rail');
+ _pruneStepActionRequests(plan);
progress.textContent = _buildProgressText(plan);
body.innerHTML = plan.steps.map(_buildStepHtml).join('');
}
@@ -127,11 +250,12 @@ async function _fetchPlan(cid) {
}
}
-async function _doRefresh(cid) {
+async function _doRefresh(cid, seq) {
if (!cid) return;
if (cid !== _currentCid) return; // view switched mid-fetch
const plan = await _fetchPlan(cid);
if (cid !== _currentCid) return;
+ if (seq !== _refreshSeq) return;
_render(plan);
}
@@ -144,6 +268,8 @@ const PlanRail = {
bind(cid) {
_currentCid = cid || null;
_currentInFlight = [];
+ _clearStepActionRequests();
+ _refreshSeq += 1;
// Drop any pending refresh from the previous cid — its result would
// race with this bind's fetch and could write stale content into the
// DOM. The cid-mismatch guard inside _doRefresh covers most of it,
@@ -160,17 +286,23 @@ const PlanRail = {
_currentCid = null;
_currentInFlight = [];
_refreshInflight = null;
+ _refreshSeq += 1;
+ _clearStepActionRequests();
_render(null);
},
- /** Re-fetch + re-render. Coalesces concurrent calls for the SAME cid;
- * bind() is responsible for clearing the slot when cid changes. */
- refresh(cid) {
+ /** Re-fetch + re-render. Coalesces concurrent calls for the SAME cid unless
+ * force=true, which is used after user actions so stale pre-click fetches
+ * cannot re-enable old recovery buttons. */
+ refresh(cid, opts = {}) {
if (!cid || cid !== _currentCid) return;
- if (_refreshInflight) return _refreshInflight;
+ if (_refreshInflight && !opts.force) return _refreshInflight;
+ const seq = ++_refreshSeq;
_refreshInflight = (async () => {
- try { await _doRefresh(cid); }
- finally { _refreshInflight = null; }
+ try { await _doRefresh(cid, seq); }
+ finally {
+ if (seq === _refreshSeq) _refreshInflight = null;
+ }
})();
return _refreshInflight;
},
@@ -180,6 +312,7 @@ const PlanRail = {
setInFlight(cid, inFlight) {
if (cid !== _currentCid) return;
_currentInFlight = Array.isArray(inFlight) ? inFlight.slice() : [];
+ _rerenderCachedPlan();
PlanRail.refresh(cid);
},
};
@@ -217,53 +350,71 @@ document.addEventListener('click', async (ev) => {
const btn = ev.target.closest('[data-action]');
if (btn) {
ev.stopPropagation();
+ if (btn.disabled) return;
const stepEl = btn.closest('[data-step-index]');
const stepIndex = stepEl ? Number(stepEl.dataset.stepIndex) : NaN;
const cid = _currentCid;
if (!cid || !Number.isFinite(stepIndex)) return;
+ if (_stepActionRequests.has(_stepActionKey(cid, stepIndex))) return;
const action = btn.dataset.action;
if (action === 'retry') {
+ _beginStepAction(cid, stepIndex, stepEl, {
+ status: 'pending',
+ patch: {
+ failure_reason: '',
+ output_msg_id: '',
+ transient_attempts: 0,
+ },
+ });
try {
- const res = await apiFetch(
- `/api/conversations/${encodeURIComponent(cid)}/plan/steps/${stepIndex}/retry`,
- { method: 'POST' },
- );
- const data = await res.json().catch(() => ({}));
+ const data = await _postStepAction(cid, stepIndex, 'retry');
if (!data?.ok) {
- uiAlert(t('plan.error.retry_failed', { reason: data?.error || 'unknown' }) || `Retry failed: ${data?.error || 'unknown'}`);
+ _alertStepActionFailure('retry', data?.error);
}
} catch (err) {
- uiAlert(t('plan.error.retry_failed', { reason: err && err.message }) || `Retry failed: ${err && err.message}`);
+ _alertStepActionFailure('retry', err && err.message);
+ } finally {
+ await _finishStepAction(cid, stepIndex, { refreshInfo: true, clearAfterRefresh: true });
}
return;
}
if (action === 'skip') {
+ _beginStepAction(cid, stepIndex, stepEl);
const ok = await uiConfirm(t('plan.confirm.skip'));
- if (!ok) return;
+ if (!ok) {
+ await _finishStepAction(cid, stepIndex, { rerender: true });
+ return;
+ }
try {
- const res = await apiFetch(
- `/api/conversations/${encodeURIComponent(cid)}/plan/steps/${stepIndex}/skip`,
- { method: 'POST' },
- );
- const data = await res.json().catch(() => ({}));
+ const data = await _postStepAction(cid, stepIndex, 'skip');
if (!data?.ok) {
- uiAlert(t('plan.error.skip_failed', { reason: data?.error || 'unknown' }) || `Skip failed: ${data?.error || 'unknown'}`);
+ _alertStepActionFailure('skip', data?.error);
+ } else {
+ _applyOptimisticStepStatus(cid, stepIndex, 'skipped');
}
} catch (err) {
- uiAlert(t('plan.error.skip_failed', { reason: err && err.message }) || `Skip failed: ${err && err.message}`);
+ _alertStepActionFailure('skip', err && err.message);
+ } finally {
+ await _finishStepAction(cid, stepIndex, { refreshInfo: true, clearAfterRefresh: true });
}
return;
}
if (action === 'abort') {
+ _beginStepAction(cid, stepIndex, stepEl);
const ok = await uiConfirm(t('plan.confirm.abort'));
- if (!ok) return;
+ if (!ok) {
+ await _finishStepAction(cid, stepIndex, { rerender: true });
+ return;
+ }
try {
await apiFetch(
`/api/conversations/${encodeURIComponent(cid)}/abort`,
{ method: 'POST' },
);
} catch (err) {
- uiAlert(t('plan.error.abort_failed', { reason: err && err.message }) || `Abort failed: ${err && err.message}`);
+ _alertStepActionFailure('abort', err && err.message);
+ } finally {
+ await _finishStepAction(cid, stepIndex, { refreshInfo: true, clearAfterRefresh: true });
}
return;
}
diff --git a/src/renderer/modules/projects.js b/src/renderer/modules/projects.js
index cc9fdb09..e1df4b0e 100644
--- a/src/renderer/modules/projects.js
+++ b/src/renderer/modules/projects.js
@@ -15,6 +15,13 @@
const _projectsLog = createLogger('projects');
+function _projectUiIconHtml(name, className) {
+ if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {
+ return window.uiIconHtml(name, className);
+ }
+ return '';
+}
+
// Live cache of projects fetched from the backend. Mirrors `_agentsCache` /
// `_skillsCache` patterns. `null` = not yet fetched.
let _projectsCache = null;
@@ -139,7 +146,7 @@ function _renderInlineCreateRow() {
// rather than a separate widget shape.
return `
<div class="project-row project-row-create" data-create>
- <span class="project-icon">${ICON_FOLDER_CLOSED}</span>
+ <span class="project-icon">${_projectUiIconHtml('folder', 'project-folder-icon')}</span>
<input type="text" class="project-rename-input" id="project-create-input"
placeholder="${placeholder}" autocomplete="off" spellcheck="false" />
</div>
@@ -149,13 +156,9 @@ function _renderInlineCreateRow() {
function _renderProjectRow(p, convs) {
const expanded = !!_projectsExpanded[p.project_id];
const editing = _projectsInlineRenamePid === p.project_id;
- // Reuse KB tree's folder SVG icons; open variant when expanded, closed
- // otherwise. Defined as global consts in modules/skills.js (script load
- // order: skills.js loads after projects.js, but renderProjectsSection
- // only runs post-DOMContentLoaded by which point all scripts have
- // initialised). No separate caret — the icon's open/closed state IS the
- // expand indicator (matches the KB tree pattern).
- const folderIcon = expanded ? ICON_FOLDER_OPEN : ICON_FOLDER_CLOSED;
+ const folderIcon = expanded
+ ? _projectUiIconHtml('folder-open', 'project-folder-icon')
+ : _projectUiIconHtml('folder', 'project-folder-icon');
const moreTitle = escapeHtml(t('project.menu.more_actions'));
const safeName = escapeHtml(p.name || '');
const nameNode = editing
@@ -680,7 +683,9 @@ function _showCommanderProjectPicker(anchor) {
if (isActive) {
const check = document.createElement('span');
check.className = 'workspace-menu-check';
- check.textContent = '✓';
+ check.innerHTML = typeof window !== 'undefined' && typeof window.uiIconHtml === 'function'
+ ? window.uiIconHtml('check', 'ui-icon workspace-check-icon')
+ : '';
row.appendChild(check);
}
row.addEventListener('click', () => {
diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.js
index 24bdae67..353efe75 100644
--- a/src/renderer/modules/settings.js
+++ b/src/renderer/modules/settings.js
@@ -19,6 +19,7 @@ let _settingsState = {
pickerModelSel: null,
addBtnBound: false,
dragState: null,
+ appUpdateBound: false,
};
async function loadSettings() {
@@ -26,6 +27,7 @@ async function loadSettings() {
// (通用 by default — matches the is-active class on the markup).
if (typeof initSettingsTabs === 'function') initSettingsTabs();
_settingsBindLanguageOnce();
+ _settingsBindAppUpdateOnce();
_settingsSyncLanguageRadio();
_settingsBindClearAllConvsOnce();
await Promise.all([
@@ -35,6 +37,7 @@ async function loadSettings() {
_settingsRefreshSearchProfiles(),
_settingsRefreshImageProfiles(),
_settingsRefreshCommanderAvatar(),
+ _settingsRefreshAppUpdate(),
_settingsRefreshMetacognition(),
_settingsRefreshDataRoot(),
]);
@@ -44,10 +47,128 @@ async function loadSettings() {
_settingsRenderSearchSection();
_settingsRenderImageSection();
_settingsRenderCommanderAvatar();
+ _settingsRenderAppUpdate();
_settingsRenderMetacognition();
_settingsRenderDataRoot();
- // Account card (views/login/account_settings.js — absent in OrkasOpen, so this is a no-op there).
+ // Account card + subscription card (views/login/account_settings.js — absent in
+ // OrkasOpen, so these are no-ops there). renderSubscriptionSettings rebinds the
+ // action button's click handler with the current subscription state on every
+ // render — opening the panel is the canonical "guarantee fresh button binding"
+ // moment, so call it explicitly here (not just from the account.onChange listener
+ // which only fires on state changes — for a Free user with no transitions the
+ // listener never fires after boot, leaving the button bound to whatever its
+ // first render captured).
if (typeof renderAccountSettings === 'function') renderAccountSettings();
+ if (typeof renderSubscriptionSettings === 'function') renderSubscriptionSettings();
+}
+
+// ── Desktop auto-update ──
+// The main process owns the updater lifecycle; settings only mirrors its
+// state and sends user intent (enable, check, install).
+
+function _settingsBindAppUpdateOnce() {
+ if (_settingsState.appUpdateBound) return;
+ _settingsState.appUpdateBound = true;
+ try {
+ if (window.orkas && typeof window.orkas.onPushEvent === 'function') {
+ _settingsRenderAppUpdate();
+ });
+ }
+ } catch (err) {
+ _settingsLog.warn('app update push subscription failed', err);
+ }
+}
+
+async function _settingsRefreshAppUpdate() {
+ try {
+ } catch (_) {
+ }
+}
+
+function _settingsFormatUpdateStatus(s) {
+ if (!s.supported) return '';
+ switch (s.phase) {
+ case 'checking':
+ case 'available':
+ case 'downloading': {
+ const pct = Number.isFinite(s.percent) ? Math.max(0, Math.min(100, s.percent)).toFixed(0) : '0';
+ }
+ case 'downloaded':
+ case 'not_available':
+ case 'error':
+ case 'not_configured':
+ default:
+ }
+}
+
+function _settingsRenderAppUpdate() {
+
+ if (cb) cb.checked = s ? !!s.enabled : true;
+ if (status) {
+ status.textContent = _settingsFormatUpdateStatus(s);
+ status.className = s?.phase === 'error' ? 'settings-status error' : 'settings-status muted';
+ }
+ if (checkBtn) {
+ checkBtn.disabled = !s || !s.canCheck;
+ }
+ if (downloadBtn) {
+ downloadBtn.hidden = !s?.canDownload;
+ downloadBtn.disabled = !s?.canDownload;
+ }
+ if (installBtn) {
+ installBtn.hidden = !s?.canInstall;
+ installBtn.disabled = !s?.canInstall;
+ }
+
+ if (cb && !cb.dataset.bound) {
+ cb.addEventListener('change', async () => {
+ const next = !!cb.checked;
+ try {
+ if (res && res.ok && res.state) {
+ _settingsRenderAppUpdate();
+ } else {
+ cb.checked = !next;
+ }
+ } catch (err) {
+ cb.checked = !next;
+ _settingsLog.warn('set app update failed', err);
+ }
+ });
+ cb.dataset.bound = '1';
+ }
+ if (checkBtn && !checkBtn.dataset.bound) {
+ checkBtn.addEventListener('click', async () => {
+ try {
+ if (res && res.ok && res.state) {
+ _settingsRenderAppUpdate();
+ }
+ } catch (err) {
+ _settingsLog.warn('check update failed', err);
+ }
+ });
+ checkBtn.dataset.bound = '1';
+ }
+ if (downloadBtn && !downloadBtn.dataset.bound) {
+ downloadBtn.addEventListener('click', async () => {
+ try {
+ if (res && res.ok && res.state) {
+ _settingsRenderAppUpdate();
+ }
+ } catch (err) {
+ _settingsLog.warn('download update failed', err);
+ }
+ });
+ downloadBtn.dataset.bound = '1';
+ }
+ if (installBtn && !installBtn.dataset.bound) {
+ installBtn.addEventListener('click', async () => {
+ try {
+ } catch (err) {
+ _settingsLog.warn('install update failed', err);
+ }
+ });
+ installBtn.dataset.bound = '1';
+ }
}
// ── Commander avatar ──
@@ -234,7 +355,7 @@ function _settingsRenderDataRoot() {
}
}
-// ── Language dropdown (zh / en) ──
+// ── Language dropdown ──
// Bound once on first panel open; `loadSettings` then calls _settingsSyncLanguageRadio()
// to re-sync the dropdown's current value with whatever setLang() last persisted.
// Option labels are each language's autonym (本族语自称), intentionally NOT routed
@@ -244,8 +365,13 @@ function _settingsRenderDataRoot() {
let _settingsLanguageSel = null; // _aiSelectMount api
const _SETTINGS_LANG_OPTIONS = [
- { value: 'zh', label: '简体中文' },
- { value: 'en', label: 'English' },
+ ...((typeof getSupportedLanguages === 'function')
+ ? getSupportedLanguages().map((l) => ({ value: l.code, label: l.label }))
+ : [
+ { value: 'zh', label: '简体中文' },
+ { value: 'en', label: 'English' },
+ { value: 'ja', label: '日本語' },
+ ]),
];
function _settingsBindLanguageOnce() {
@@ -257,7 +383,7 @@ function _settingsBindLanguageOnce() {
value: (typeof getLang === 'function') ? getLang() : 'en',
});
_settingsLanguageSel.onChange(async (next) => {
- if (next !== 'zh' && next !== 'en') return;
+ if (typeof isSupportedLang === 'function' && !isSupportedLang(next)) return;
try {
await setLang(next);
_settingsLog.info('language changed', { lang: next });
@@ -351,6 +477,7 @@ window.addEventListener('i18n-change', () => {
_settingsRenderEntries();
_settingsRenderSearchSection();
_settingsRenderImageSection();
+ _settingsRenderAppUpdate();
_settingsRenderMetacognition();
});
diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.js
index 23741d07..f40daf09 100644
--- a/src/renderer/modules/skills.js
+++ b/src/renderer/modules/skills.js
@@ -4,6 +4,13 @@ const _skillsLog = createLogger('skills');
let _skillsCache = null;
let _selectedSkill = null; // { source, id }
+function _skillUiIconHtml(name, className) {
+ if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {
+ return window.uiIconHtml(name, className);
+ }
+ return '';
+}
+
/** Version + category + author chips for a marketplace-installed skill. Mirrors the
* marketplace card footer. `_resolveCategoryLabel` is defined in `agents.js` (flat top-level
* scope per CLAUDE.md §8). Author chip: `create_uid='0'` → 官方 badge; non-zero → user badge. */
@@ -158,7 +165,7 @@ function renderSkillsGrid(skills) {
<div class="skill-card-actions">
${platformChips}
<button type="button" class="skill-card-use" data-skill-use title="${useTitle}" aria-label="${useTitle}">
- <svg class="icon-play" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><polygon points="5,3 5,13 13,8" fill="currentColor"/></svg>
+ ${_skillUiIconHtml('play-triangle', 'icon-play')}
</button>
</div>
</div>
@@ -442,10 +449,10 @@ async function expandSkillTree(source, id, childrenEl) {
bindTreeNodes(childrenEl, source, id);
}
-// SVG icons for tree nodes
-const ICON_FOLDER_CLOSED = '<svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 5.5a1.5 1.5 0 0 1 1.5-1.5h3.3a1.5 1.5 0 0 1 1.2.6l.9 1.2a1.5 1.5 0 0 0 1.2.6H16a1.5 1.5 0 0 1 1.5 1.5V14a1.5 1.5 0 0 1-1.5 1.5H4A1.5 1.5 0 0 1 2.5 14V5.5Z"/></svg>';
-const ICON_FOLDER_OPEN = '<svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7V5.5A1.5 1.5 0 0 1 4.5 4h3.1a1.5 1.5 0 0 1 1.2.6l.9 1.2a1.5 1.5 0 0 0 1.2.6H16a1.5 1.5 0 0 1 1.5 1.5V8"/><path d="M2.2 9.2A1 1 0 0 1 3.2 8h13.6a1 1 0 0 1 .97 1.24l-1.2 5A1.5 1.5 0 0 1 15.1 15.4H4.2a1.5 1.5 0 0 1-1.46-1.16l-1.1-4.6a1 1 0 0 1 .06-.44Z"/></svg>';
-const ICON_FILE = '<svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M11.5 2.5H5.5A1.5 1.5 0 0 0 4 4v12a1.5 1.5 0 0 0 1.5 1.5h9A1.5 1.5 0 0 0 16 16V7l-4.5-4.5Z"/><path d="M11 2.5V7h4.5"/></svg>';
+// Tree icons are centralized in modules/icons.js; classes here only control sizing/color.
+const ICON_FOLDER_CLOSED = _skillUiIconHtml('folder', 'skill-tree-node-svg');
+const ICON_FOLDER_OPEN = _skillUiIconHtml('folder-open', 'skill-tree-node-svg');
+const ICON_FILE = _skillUiIconHtml('file', 'skill-tree-node-svg');
function fileIconSvg(ext) {
// Generic file icon; color is differentiated via data-ext
@@ -1487,4 +1494,3 @@ function _renderSkillEnabledButton(skill) {
finally { btn.disabled = false; }
});
}
-
diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.js
index 4904d407..dbdabe4b 100644
--- a/src/renderer/modules/state.js
+++ b/src/renderer/modules/state.js
@@ -12,8 +12,22 @@ let conversations = [];
// key: cid, value: { loadingEl: HTMLElement | null, needsIndicator: bool,
// controller: AbortController | null, aborted: bool }
const pendingConvs = new Map();
+// Group-chat runtime state is emitted independently from the request
+// controller. Keep it in the same pending predicate so delegated agents keep
+// the send button in "replying/stop" mode until the whole turn is quiescent.
+const groupBusyConvs = new Map();
-function isConvPending(cid) { return pendingConvs.has(cid); }
+function isGroupConversationBusy(cid) { return groupBusyConvs.has(cid); }
+
+function setGroupConversationBusy(cid, busy) {
+ if (!cid) return;
+ if (busy) groupBusyConvs.set(cid, true);
+ else groupBusyConvs.delete(cid);
+}
+
+function isConvPending(cid) {
+ return pendingConvs.has(cid) || isGroupConversationBusy(cid);
+}
// Per-conversation queued messages (sent sequentially, one at a time).
// key: cid, value: Array<{ id, content, skill }>
@@ -96,6 +110,7 @@ function stopPolling(cid) {
function _onPolledResponse(cid, content, isError = false) {
const state = pendingConvs.get(cid);
pendingConvs.delete(cid);
+ setGroupConversationBusy(cid, false);
_updateConvSidebarBadge(cid, false);
const el = state?.loadingEl;
@@ -334,4 +349,3 @@ function autoGrow(el, maxPx) {
el.style.height = 'auto';
el.style.height = Math.min(el.scrollHeight, maxPx) + 'px';
}
-
diff --git a/src/renderer/modules/strip-structural-blocks.js b/src/renderer/modules/strip-structural-blocks.js
index 98bc7e94..d07d5c25 100644
--- a/src/renderer/modules/strip-structural-blocks.js
+++ b/src/renderer/modules/strip-structural-blocks.js
@@ -394,10 +394,10 @@ function _stripSkillCreateContainer(buf, fallbackPlaceholder) {
function _stripSurvivingStructuralBlocks(text) {
if (!text) return text;
let out = text;
- // `artifact-result` is a user→artifact result tag (user-side render strips
- // it via `_stripArtifactResultTagForDisplay`); included here so it's also
- // removed if it ever leaks into assistant text (LLM quoting / hallucination).
- for (const tag of ['agent', 'agent-input-form', 'agent-input-submission', 'artifact-result', 'skill']) {
+ // `artifact-result` and `marketplace-install-result` are user→system result
+ // tags (user-side render strips them); included here so they are also
+ // removed if they ever leak into assistant text (LLM quoting / hallucination).
+ for (const tag of ['agent', 'agent-input-form', 'agent-input-submission', 'artifact-result', 'marketplace-install-result', 'skill']) {
out = _stripOuterTagBlocks(out, tag);
}
// `<<<skill-file>>>` blocks: backend `extractSkillFileBlocks` strips them
diff --git a/src/renderer/modules/user-workspace.js b/src/renderer/modules/user-workspace.js
index 35f4096a..0d9dce3b 100644
--- a/src/renderer/modules/user-workspace.js
+++ b/src/renderer/modules/user-workspace.js
@@ -161,12 +161,13 @@ function _createWorkspaceChip(target) {
// ("给:" / "项目:" / "工作区:") — the folder icon was replaced per UX
// feedback so all three left-side chips read as "[label]: [value]".
const prefix = (t('workspace.chip_label'));
+ const chevronIcon = (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function')
+ ? window.uiIconHtml('chevron-down', 'workspace-chip-chevron')
+ : '';
chip.innerHTML =
`<span class="workspace-chip-prefix">${escapeHtml(prefix)}</span>` +
'<span class="workspace-chip-label"></span>' +
- '<svg class="workspace-chip-chevron" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.5">' +
- '<polyline points="6 9 12 15 18 9"/>' +
- '</svg>';
+ chevronIcon;
chip.addEventListener('click', (e) => {
e.stopPropagation();
@@ -282,7 +283,9 @@ function _createMenuItem(text, isActive, onClick) {
if (isActive) {
const check = document.createElement('span');
check.className = 'workspace-menu-check';
- check.textContent = '✓';
+ check.innerHTML = typeof window !== 'undefined' && typeof window.uiIconHtml === 'function'
+ ? window.uiIconHtml('check', 'ui-icon workspace-check-icon')
+ : '';
item.appendChild(check);
}
item.addEventListener('click', onClick);
diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.js
index 137f02bd..58919792 100644
--- a/src/renderer/modules/utils.js
+++ b/src/renderer/modules/utils.js
@@ -1,18 +1,49 @@
// ─── Utilities ───
+function _baseLang(lang) {
+ return (lang || '').split(/[-_]/)[0] || 'en';
+}
+
+function descriptionLocale(lang) {
+ return _baseLang(lang) === 'zh' ? 'zh' : 'en';
+}
+
+function pickLocalizedField(obj, base, lang, fallbackLang = 'en') {
+ if (!obj || !base) return '';
+ const cur = _baseLang(lang);
+ const candidates = [
+ `${base}_${cur}`,
+ `${base}_${fallbackLang}`,
+ `${base}_en`,
+ `${base}_zh`,
+ base,
+ ];
+ const seen = new Set();
+ for (const key of candidates) {
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const v = obj[key];
+ if (v !== null && v !== undefined && String(v).trim()) return String(v).trim();
+ }
+ return '';
+}
+
+function pickLocalizedName(obj, lang) {
+ return pickLocalizedField(obj, 'name', lang);
+}
+
/** Pick a skill / agent description for the active UI language with cross-
* language fallback. Mirrors `pickDescription` in core-agent's skills/types
* — keep these two in sync if the fallback rule changes.
*
- * `lang === 'zh'`: description_zh || description_en || ''. Mirror for 'en'.
- * Cross-fallback guarantees a non-empty string whenever any side is filled,
- * so users never see blank entries when only one locale was authored. */
+ * Description storage is intentionally still zh/en only: non-Chinese UI
+ * languages use the English description first. Cross-fallback guarantees a
+ * non-empty string whenever any side is filled. */
function pickDesc(spec, lang) {
if (!spec) return '';
- const zh = (spec.description_zh || '').trim();
- const en = (spec.description_en || '').trim();
- if (lang === 'zh') return zh || en || '';
- return en || zh || '';
+ const primary = pickLocalizedField(spec, 'description', descriptionLocale(lang));
+ if (primary) return primary;
+ return pickLocalizedField(spec, 'description', lang);
}
function escapeHtml(str) {
@@ -51,18 +82,6 @@ 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
@@ -309,252 +328,6 @@ 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) {
- const text = String(props.text == null ? '' : props.text);
- // 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
@@ -732,7 +505,7 @@ function formatTime(iso) {
function _aiSelectMount(el, config) {
if (!el) return null;
const state = {
- options: [], // [{value, label, hint?}]
+ options: [], // [{value, label, hint?, iconName?}]
value: '',
placeholder: (t('ai_select.placeholder')),
onChange: () => {},
@@ -741,13 +514,15 @@ function _aiSelectMount(el, config) {
};
Object.assign(state, config || {});
+ const caretIcon = (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function')
+ ? window.uiIconHtml('chevron-down', 'ai-select-caret')
+ : '';
+
el.classList.add('ai-select');
el.innerHTML = `
<button type="button" class="ai-select-trigger" aria-haspopup="listbox">
<span class="ai-select-label"></span>
- <svg class="ai-select-caret" viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.8">
- <path d="m4 6 4 4 4-4"></path>
- </svg>
+ ${caretIcon}
</button>
<div class="ai-select-popover" role="listbox" hidden></div>
`;
@@ -756,13 +531,26 @@ function _aiSelectMount(el, config) {
const labelEl = el.querySelector('.ai-select-label');
const popover = el.querySelector('.ai-select-popover');
+ const renderOptionLabel = (target, opt) => {
+ target.innerHTML = '';
+ if (opt && opt.iconName && typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {
+ const iconWrap = document.createElement('span');
+ iconWrap.className = 'ai-select-option-icon';
+ iconWrap.innerHTML = window.uiIconHtml(opt.iconName, 'ui-icon ai-select-svg-icon');
+ target.appendChild(iconWrap);
+ }
+ const text = document.createElement('span');
+ text.textContent = opt ? opt.label : state.placeholder;
+ target.appendChild(text);
+ };
+
const renderTrigger = () => {
const opt = state.options.find(o => o.value === state.value);
if (opt) {
- labelEl.textContent = opt.label;
+ renderOptionLabel(labelEl, opt);
labelEl.classList.remove('placeholder');
} else {
- labelEl.textContent = state.placeholder;
+ renderOptionLabel(labelEl, null);
labelEl.classList.add('placeholder');
}
el.dataset.value = state.value || '';
@@ -785,7 +573,7 @@ function _aiSelectMount(el, config) {
if (idx === state.activeIdx) item.classList.add('hover');
const main = document.createElement('div');
main.className = 'ai-select-item-label';
- main.textContent = opt.label;
+ renderOptionLabel(main, opt);
item.appendChild(main);
if (opt.hint) {
const hint = document.createElement('div');
@@ -957,7 +745,5 @@ 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 3946796b..f4c03e34 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -15,6 +15,20 @@
--radius-sm: 10px;
}
+.ui-icon {
+ display: inline-block;
+ width: 1em;
+ height: 1em;
+ flex: 0 0 auto;
+ color: currentColor;
+ vertical-align: -0.12em;
+}
+.btn-inline-icon {
+ width: 14px;
+ height: 14px;
+ margin-right: 4px;
+}
+
* { box-sizing: border-box; margin: 0; padding: 0; }
/* ─── Global scrollbar — thin, subtle. Without this rule, any scrollable
@@ -83,6 +97,7 @@ body {
display: flex;
align-items: center;
gap: 8px;
+ flex-shrink: 0;
}
.logo-icon {
@@ -105,6 +120,7 @@ body {
display: flex;
flex-direction: column;
gap: 4px;
+ flex-shrink: 0;
}
/* Sidebar search trigger — sits between the logo strip and the action list. */
@@ -123,8 +139,14 @@ body {
cursor: pointer;
transition: all 0.15s;
-webkit-app-region: no-drag;
+ flex-shrink: 0;
}
.sidebar-search-btn:hover { background: #f1f5f9; color: var(--text); }
+.sidebar-search-icon {
+ width: 14px;
+ height: 14px;
+ flex-shrink: 0;
+}
.sidebar-search-btn .sidebar-search-label { flex: 1; text-align: left; }
.sidebar-search-btn .sidebar-search-kbd {
font-size: 10.5px;
@@ -134,6 +156,19 @@ body {
border: 1px solid var(--border);
border-radius: 4px;
background: #fff;
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+}
+.sidebar-search-command-icon {
+ width: 11px;
+ height: 11px;
+}
+
+.sidebar-footer-icon {
+ width: 14px;
+ height: 14px;
+ flex-shrink: 0;
}
/* ── Global search overlay (Cmd+K) ─────────────────────────────────────── */
@@ -165,7 +200,17 @@ body {
padding: 14px 16px;
border-bottom: 1px solid var(--border);
}
-.search-input-icon { color: #94a3b8; flex-shrink: 0; }
+.search-input-icon {
+ width: 18px;
+ height: 18px;
+ color: #94a3b8;
+ flex-shrink: 0;
+}
+.search-close-icon {
+ width: 16px;
+ height: 16px;
+ display: block;
+}
#search-input {
flex: 1;
border: none;
@@ -416,6 +461,7 @@ body {
padding: 6px 12px 10px;
border-top: 1px solid var(--border);
background: #fafafa;
+ flex-shrink: 0;
}
.sidebar-footer-btn {
display: inline-flex;
@@ -436,37 +482,38 @@ body {
.sidebar-footer-btn:hover { background: #f1f5f9; color: var(--text); }
.sidebar-footer-btn.active { background: #eff6ff; color: var(--primary); font-weight: 600; }
-.sidebar-section {
+.sidebar-conversation-nav {
flex: 1;
min-height: 0;
padding: 4px 8px 8px;
display: flex;
flex-direction: column;
- overflow: hidden;
+ overflow-y: auto;
border-top: 1px solid var(--border);
margin-top: 4px;
}
+.sidebar-conversation-nav::-webkit-scrollbar { width: 4px; }
+.sidebar-conversation-nav::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.1); border-radius: 3px; }
-/* Projects section sits on top of conversations; let it stay intrinsic-sized
- (rows are short, even ~20 projects fit in a small slab) while the
- conversations section underneath takes the remaining height. Cap so a user
- with dozens of projects doesn't push the conv list off-screen — internal
- scroll engages. */
-.sidebar-projects-section {
+.sidebar-section {
flex: 0 0 auto;
- max-height: 40vh;
- border-top: 1px solid var(--border);
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ overflow: visible;
+}
+
+/* Projects and the catch-all conversation list are one conversation
+ navigation surface. The parent .sidebar-conversation-nav owns scrolling so
+ project conversations and ordinary conversations move together. */
+.sidebar-projects-section {
+ border-top: 0;
}
-/* Conversations section under Projects — share the same conceptual area as
- Projects (per UX feedback "可以认为是同样的区域"). The divider stays as
- a hairline visual cue but in a much lighter tone so the two sections
- read as related rather than partitioned. Falls back to var(--border)
- on platforms / themes where the muted variant isn't defined. */
.sidebar-conversations-section {
- flex: 1 1 auto;
border-top: 1px solid rgba(15, 23, 42, 0.05);
- margin-top: 0;
+ margin-top: 8px;
+ padding-top: 4px;
}
.sidebar-section-title-row {
@@ -480,8 +527,8 @@ body {
padding: 12px 4px 6px;
font-size: 11px;
font-weight: 700;
- text-transform: uppercase;
- letter-spacing: 0.6px;
+ text-transform: none;
+ letter-spacing: 0;
color: #9ca3af;
}
@@ -510,15 +557,12 @@ body {
/* ─── Projects list ─── */
.projects-list {
- flex: 1;
- overflow-y: auto;
+ overflow: visible;
display: flex;
flex-direction: column;
gap: 1px;
- padding-right: 2px;
+ padding-right: 0;
}
-.projects-list::-webkit-scrollbar { width: 4px; }
-.projects-list::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.1); border-radius: 3px; }
.project-row {
display: flex;
@@ -835,17 +879,13 @@ body {
}
.conversation-list {
- flex: 1;
- overflow-y: auto;
+ overflow: visible;
display: flex;
flex-direction: column;
gap: 1px;
- padding-right: 2px;
+ padding-right: 0;
}
-.conversation-list::-webkit-scrollbar { width: 4px; }
-.conversation-list::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.1); border-radius: 3px; }
-
.conv-item {
display: flex;
align-items: center;
@@ -1382,6 +1422,14 @@ body.model-not-configured .main-content { flex-direction: column; }
border-radius: 8px;
flex-shrink: 0;
}
+.skills-chat-input-area .chat-send-btn .send-icon {
+ width: 16px;
+ height: 16px;
+}
+.skills-chat-input-area .chat-send-btn .stop-icon {
+ width: 14px;
+ height: 14px;
+}
/* SKILL.md body — sits inside a "使用说明" section now; padding/scroll
moved to the parent .skills-detail-content. */
@@ -1575,6 +1623,8 @@ body.model-not-configured .main-content { flex-direction: column; }
.skill-card-use .icon-play,
.agent-card-use .icon-play,
.btn-icon-use .icon-play {
+ width: 14px;
+ height: 14px;
display: block;
}
@@ -1833,185 +1883,6 @@ 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;
@@ -2057,66 +1928,412 @@ body.model-not-configured .main-content { flex-direction: column; }
color: var(--muted);
margin-bottom: 22px;
}
-
-.new-chat-input-wrapper {
- width: 100%;
- max-width: 720px;
+
+.new-chat-input-wrapper {
+ width: 100%;
+ max-width: 720px;
+}
+
+.new-chat-input-area {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 7px 16px;
+ background: #fff;
+ border: 1px solid var(--border-strong);
+ border-radius: 18px;
+ box-shadow: 0 8px 32px rgba(15, 23, 42, 0.08);
+ transition: all 0.2s;
+ /* See `.chat-input-area` — anchor for the floating workspace chip. */
+ position: relative;
+}
+
+.new-chat-input-area:focus-within {
+ border-color: var(--primary);
+ box-shadow: 0 8px 32px rgba(37, 99, 235, 0.16);
+ transform: translateY(-2px);
+}
+
+.new-chat-input-area textarea {
+ flex: 0 1 auto;
+ width: 100%;
+ border: none;
+ outline: none;
+ resize: none;
+ padding: 4px 4px;
+ font-size: 16px;
+ line-height: 1.55;
+ max-height: 260px;
+ min-height: 35px;
+ background: transparent;
+ color: var(--text);
+ font-family: inherit;
+}
+
+/* New-chat mirror inherits the wrap rules from `.chat-input-mirror-wrap`
+ * but the new-chat textarea uses 16px (not 15px), so we override the
+ * mirror's font-size in this scope to keep them aligned. */
+.new-chat-input-area .chat-input-mirror {
+ font-size: 16px;
+}
+
+/* ─── Chat (matches agent-cowork board) ─── */
+.chat-container {
+ display: flex;
+ flex-direction: row;
+ height: 100%;
+ background: #f8fafc;
+ position: relative;
+}
+
+.chat-main-pane {
+ position: relative;
+ flex: 1 1 auto;
+ min-width: 0;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ background: #f8fafc;
+ /* Used by `.chat-input-form { width: 40cqw }`. */
+ container-type: inline-size;
+}
+
+.conversation-info-toggle {
+ position: absolute;
+ top: 16px;
+ right: 18px;
+ z-index: 12;
+ width: 34px;
+ height: 34px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid rgba(148, 163, 184, 0.45);
+ border-radius: 8px;
+ background: rgba(255, 255, 255, 0.92);
+ color: #64748b;
+ box-shadow: 0 6px 18px rgba(15, 23, 42, 0.08);
+ cursor: pointer;
+ transition: background 120ms ease, color 120ms ease, border-color 120ms ease, box-shadow 120ms ease;
+}
+.conversation-info-toggle:hover,
+.conversation-info-toggle.is-active {
+ background: #fff;
+ color: var(--primary);
+ border-color: rgba(37, 99, 235, 0.35);
+ box-shadow: 0 8px 22px rgba(37, 99, 235, 0.14);
+}
+.conversation-info-toggle-icon {
+ width: 18px;
+ height: 18px;
+}
+
+.conversation-info-panel {
+ flex: 0 0 min(380px, 36vw);
+ width: min(380px, 36vw);
+ min-width: 320px;
+ max-width: 420px;
+ 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;
+}
+.conversation-info-panel[hidden] { display: none !important; }
+.conversation-info-header {
+ flex: 0 0 auto;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 16px 16px 12px;
+ border-bottom: 1px solid var(--border);
+}
+.conversation-info-title {
+ font-size: 15px;
+ font-weight: 650;
+ color: var(--text);
+}
+.conversation-info-close {
+ 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;
+}
+.conversation-info-close:hover {
+ color: #0f172a;
+ background: #f1f5f9;
+ border-color: #e2e8f0;
+}
+.conversation-info-tabs {
+ flex: 0 0 auto;
+ display: flex;
+ gap: 4px;
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--border);
+}
+.conversation-info-tab {
+ flex: 1 1 0;
+ min-width: 0;
+ border: none;
+ border-radius: 8px;
+ padding: 7px 8px;
+ background: transparent;
+ color: var(--muted);
+ font-size: 12px;
+ font-family: inherit;
+ cursor: pointer;
+}
+.conversation-info-tab:hover { color: var(--text); background: #f8fafc; }
+.conversation-info-tab.is-active {
+ color: var(--text);
+ background: var(--accent-soft, #eef2ff);
+ font-weight: 600;
+}
+.conversation-info-body {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow: auto;
+ padding: 12px;
+}
+.conversation-info-empty {
+ min-height: 160px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ padding: 18px;
+ color: #94a3b8;
+ font-size: 13px;
+ line-height: 1.5;
+}
+.conversation-info-empty.is-small {
+ min-height: 0;
+ justify-content: flex-start;
+ padding: 8px 0;
+ font-size: 12px;
+}
+.conversation-info-empty.is-error { color: var(--danger); }
+
+.conversation-info-task-list {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+.conversation-info-task {
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: #fff;
+ overflow: hidden;
+}
+.conversation-info-task-summary {
+ display: flex;
+ align-items: center;
+ padding: 12px 12px 6px;
+}
+.conversation-info-task-title {
+ display: block;
+ color: #0f172a;
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 1.4;
+ overflow-wrap: anywhere;
+}
+.conversation-info-task-steps {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: 8px 12px 14px;
+}
+.conversation-info-step {
+ padding: 0;
+}
+.conversation-info-step-head {
+ display: grid;
+ grid-template-columns: 18px auto minmax(0, 1fr) auto;
+ align-items: start;
+ gap: 6px;
+}
+.conversation-info-step-icon {
+ width: 18px;
+ height: 18px;
+ color: #64748b;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ margin-top: 1px;
+}
+.conversation-info-step-status-icon {
+ width: 16px;
+ height: 16px;
+}
+.conversation-info-step.is-done .conversation-info-step-icon { color: #16a34a; }
+.conversation-info-step.is-in_progress .conversation-info-step-icon { color: #2563eb; }
+.conversation-info-step.is-failed .conversation-info-step-icon { color: #dc2626; }
+.conversation-info-step.is-skipped .conversation-info-step-icon { color: #94a3b8; }
+.conversation-info-step.is-blocked .conversation-info-step-icon { color: #d97706; }
+.conversation-info-step-index {
+ color: #64748b;
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ line-height: 1.45;
+}
+.conversation-info-step-title {
+ min-width: 0;
+ color: #0f172a;
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 1.4;
+ overflow-wrap: anywhere;
+}
+.conversation-info-status {
+ justify-self: end;
+ max-width: 92px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ border-radius: 999px;
+ padding: 2px 6px;
+ background: #f1f5f9;
+ color: #64748b;
+ font-size: 10px;
+ font-weight: 600;
+}
+.conversation-info-step-meta,
+.conversation-info-step-reason {
+ margin-top: 3px;
+ margin-left: 24px;
+ color: #64748b;
+ font-size: 12px;
+ line-height: 1.45;
+ overflow-wrap: anywhere;
+}
+.conversation-info-step-reason { color: var(--danger); }
+
+.conversation-info-tree,
+.conversation-info-attachment-list {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+}
+.conversation-info-dir {
+ display: flex;
+ flex-direction: column;
+}
+.conversation-info-dir-summary {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-height: 28px;
+ padding: 4px 8px 4px calc(8px + var(--depth, 0) * 14px);
+ border-radius: 8px;
+ color: #475569;
+ font-size: 12px;
+ cursor: pointer;
+ list-style: none;
+}
+.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;
+ height: 18px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: #f59e0b;
}
-
-.new-chat-input-area {
- display: flex;
- flex-direction: column;
- gap: 6px;
- padding: 7px 16px;
- background: #fff;
- border: 1px solid var(--border-strong);
- border-radius: 18px;
- box-shadow: 0 8px 32px rgba(15, 23, 42, 0.08);
- transition: all 0.2s;
- /* See `.chat-input-area` — anchor for the floating workspace chip. */
- position: relative;
+.conversation-info-dir-svg-icon {
+ width: 16px;
+ height: 16px;
+ display: block;
}
-
-.new-chat-input-area:focus-within {
- border-color: var(--primary);
- box-shadow: 0 8px 32px rgba(37, 99, 235, 0.16);
- transform: translateY(-2px);
+.conversation-info-dir-folder-open { display: none; }
+.conversation-info-dir[open] > .conversation-info-dir-summary .conversation-info-dir-folder-closed { display: none; }
+.conversation-info-dir[open] > .conversation-info-dir-summary .conversation-info-dir-folder-open { display: inline-flex; }
+.conversation-info-dir-name,
+.conversation-info-file-name {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
-
-.new-chat-input-area textarea {
- flex: 0 1 auto;
+.conversation-info-file,
+.conversation-info-attachment {
width: 100%;
+ min-height: 30px;
+ display: flex;
+ align-items: center;
+ gap: 7px;
border: none;
- outline: none;
- resize: none;
- padding: 4px 4px;
- font-size: 16px;
- line-height: 1.55;
- max-height: 260px;
- min-height: 35px;
+ border-radius: 8px;
+ padding: 5px 8px 5px calc(8px + var(--depth, 0) * 14px);
background: transparent;
- color: var(--text);
+ color: #334155;
+ font-size: 12px;
font-family: inherit;
+ text-align: left;
+ cursor: pointer;
}
-
-/* New-chat mirror inherits the wrap rules from `.chat-input-mirror-wrap`
- * but the new-chat textarea uses 16px (not 15px), so we override the
- * mirror's font-size in this scope to keep them aligned. */
-.new-chat-input-area .chat-input-mirror {
- font-size: 16px;
+.conversation-info-file:hover,
+.conversation-info-attachment:hover { background: #f1f5f9; }
+.conversation-info-file-icon {
+ flex: 0 0 auto;
+ width: 18px;
+ height: 18px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ font-size: 14px;
+ line-height: 1;
}
-
-/* ─── Chat (matches agent-cowork board) ─── */
-.chat-container {
+.conversation-info-attachment {
+ padding-left: 8px;
+ border: 1px solid transparent;
+}
+.conversation-info-attachment:hover { border-color: #e2e8f0; }
+.conversation-info-attachment-main {
+ min-width: 0;
display: flex;
flex-direction: column;
- height: 100%;
- background: #f8fafc;
- position: relative;
- /* Used by `.chat-input-form { width: 40cqw }`. */
- container-type: inline-size;
+ gap: 2px;
+}
+.conversation-info-attachment-meta {
+ color: #94a3b8;
+ font-size: 11px;
}
+@media (max-width: 920px) {
+ .conversation-info-panel {
+ position: absolute;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ width: min(360px, calc(100% - 48px));
+ min-width: 0;
+ flex-basis: auto;
+ }
+}
/* Inline "创建智能体" entry pinned to the end of #chat-history — divider
lines on both sides with a small button in the middle. Hidden during
@@ -2330,7 +2547,15 @@ body.model-not-configured .main-content { flex-direction: column; }
transform: none;
}
-.chat-send-btn .stop-icon { display: none; }
+.chat-send-btn .send-icon {
+ width: 18px;
+ height: 18px;
+}
+.chat-send-btn .stop-icon {
+ width: 16px;
+ height: 16px;
+ display: none;
+}
.chat-send-btn.streaming {
background: #dc2626;
}
@@ -2411,6 +2636,9 @@ body.model-not-configured .main-content { flex-direction: column; }
max-width: 240px;
}
.chat-attach-chip .chat-attach-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
font-size: 14px;
line-height: 1;
flex-shrink: 0;
@@ -2528,6 +2756,15 @@ body.model-not-configured .main-content { flex-direction: column; }
text-overflow: ellipsis;
white-space: nowrap;
}
+.chat-quote-preview .chat-quote-file .chat-file-kind-icon {
+ flex: 0 0 auto;
+ width: 14px;
+ height: 14px;
+}
+.chat-quote-preview .chat-quote-file-label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
/* "+" button — sits left of the textarea inside .chat-input-area */
.chat-attach-btn {
@@ -2551,6 +2788,32 @@ body.model-not-configured .main-content { flex-direction: column; }
color: #334155;
}
+/* Mic button — voice-to-text. Reuses .chat-attach-btn's box; adds the
+ recording / finalizing states. Stripped in OrkasOpen — see
+ OpenSource/SyncCode/strip-rules.json. */
+.chat-mic-btn svg { display: block; }
+.chat-mic-icon {
+ width: 15px;
+ height: 15px;
+}
+.chat-mic-btn.is-recording {
+ color: #dc2626;
+ background: #fee2e2;
+ animation: chat-mic-pulse 1.3s ease-in-out infinite;
+}
+.chat-mic-btn.is-recording:hover {
+ color: #dc2626;
+ background: #fecaca;
+}
+.chat-mic-btn.is-busy {
+ color: #94a3b8;
+ cursor: default;
+}
+@keyframes chat-mic-pulse {
+ 0%, 100% { box-shadow: 0 0 0 0 rgba(220, 38, 38, 0.28); }
+ 60% { box-shadow: 0 0 0 5px rgba(220, 38, 38, 0); }
+}
+
/* Bottom row inside the input area: [+] [recipient] [project] [skill]
[workspace] ... [send]. Wraps row-by-row on narrow windows so chips
never overflow the input box. */
@@ -2590,6 +2853,14 @@ body.model-not-configured .main-content { flex-direction: column; }
border-color: rgba(37, 99, 235, 0.2);
color: #1e293b;
}
+.chat-msg-attach-icon,
+.chat-msg-produced-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 auto;
+ line-height: 1;
+}
.chat-message.user .chat-msg-attach-icon { color: #334155; }
.chat-msg-attach.is-image {
padding: 4px;
@@ -2815,6 +3086,19 @@ body.model-not-configured .main-content { flex-direction: column; }
border: none;
display: block;
}
+.chat-file-viewer-video-wrap {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: #020617;
+}
+.chat-file-viewer-video {
+ max-width: 100%;
+ max-height: 100%;
+ background: #020617;
+}
.chat-file-viewer-md {
padding: 24px 32px;
color: #0f172a;
@@ -2880,6 +3164,22 @@ body.model-not-configured .main-content { flex-direction: column; }
.chat-msg-produced-item:hover {
background: rgba(34, 197, 94, 0.16);
}
+.chat-file-kind-icon {
+ display: block;
+ width: 16px;
+ height: 16px;
+ color: currentColor;
+}
+.chat-file-kind-icon.is-image { color: #16a34a; }
+.chat-file-kind-icon.is-video { color: #7c3aed; }
+.chat-file-kind-icon.is-audio { color: #db2777; }
+.chat-file-kind-icon.is-pdf { color: #dc2626; }
+.chat-file-kind-icon.is-doc { color: #2563eb; }
+.chat-file-kind-icon.is-text,
+.chat-file-kind-icon.is-file { color: #64748b; }
+.chat-file-kind-icon.is-data { color: #0891b2; }
+.chat-file-kind-icon.is-archive { color: #b45309; }
+.chat-file-kind-icon.is-code { color: #475569; }
.chat-msg-produced-label {
display: inline-block;
overflow: hidden;
@@ -3177,6 +3477,71 @@ body.model-not-configured .main-content { flex-direction: column; }
color: var(--muted);
}
+/* Marketplace install request card. Same inline-panel scale as input forms:
+ the user explicitly approves before any marketplace resource is installed. */
+.chat-marketplace-request {
+ margin-top: 10px;
+ width: min(360px, 100%);
+ max-width: 100%;
+ min-width: 280px;
+ background: #fff;
+ border-color: rgba(0,0,0,0.08);
+}
+.chat-marketplace-request.is-installed {
+ background: #fff;
+ border-color: rgba(34, 197, 94, 0.26);
+}
+.chat-marketplace-request.is-skipped {
+ background: #fff;
+ border-color: rgba(148, 163, 184, 0.35);
+}
+.chat-marketplace-request.is-failed {
+ background: #fff;
+ border-color: rgba(239, 68, 68, 0.28);
+}
+.chat-marketplace-request-head {
+ align-items: center;
+}
+.marketplace-card-header.chat-marketplace-request-head {
+ align-items: center;
+}
+.chat-marketplace-request-avatar {
+ flex: 0 0 auto;
+}
+.chat-marketplace-request-main {
+ min-width: 0;
+ flex: 1 1 auto;
+}
+.chat-marketplace-request-title-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+}
+.marketplace-card-name.chat-marketplace-request-title { flex: 0 1 auto; }
+.chat-marketplace-request-kind { flex: 0 0 auto; }
+.chat-marketplace-request-status {
+ flex: 0 0 auto;
+ padding: 2px 8px;
+ border-radius: 999px;
+ background: rgba(0,0,0,0.05);
+ border: 1px solid rgba(15, 23, 42, 0.08);
+ color: var(--muted);
+ font-size: 11px;
+ font-weight: 500;
+}
+.chat-marketplace-request-error {
+ line-height: 1.45;
+ color: var(--muted);
+}
+.chat-marketplace-request-error { color: var(--danger); }
+.chat-marketplace-request-actions {
+ gap: 6px;
+}
+.chat-marketplace-request.is-busy {
+ opacity: 0.82;
+}
+
/* Interactive web-app artifact card — sandboxed `<iframe>` over the
`chat-app://` protocol, embedded inside the assistant `.chat-bubble`.
See modules/chat-artifact.js. Understated chrome (a title bar + reload)
@@ -3598,6 +3963,9 @@ body.model-not-configured .main-content { flex-direction: column; }
/* Plan announcement card — rendered as the leading line of the bubble
* when commander emits its initial plan_set message. */
.chat-plan-announce {
+ display: flex;
+ align-items: center;
+ gap: 6px;
font-size: 12px;
font-weight: 600;
color: var(--text-muted, #6b7280);
@@ -3605,6 +3973,11 @@ body.model-not-configured .main-content { flex-direction: column; }
padding-bottom: 6px;
border-bottom: 1px dashed var(--border-soft, #e5e7eb);
}
+.chat-plan-announce-icon {
+ width: 14px;
+ height: 14px;
+ color: var(--primary);
+}
.chat-bubble {
padding: 12px 18px;
@@ -3703,14 +4076,14 @@ body.model-not-configured .main-content { flex-direction: column; }
this baseline and read as supporting context. */
color: #94a3b8;
font-family: ui-monospace, SFMono-Regular, monospace;
- /* Force text-style rendering for symbols like ▶ ✓ ◆ ⚙ ▸ ✎ — otherwise
- some systems render them as larger colored emoji glyphs. */
- font-variant-emoji: text;
}
.stream-process-body::-webkit-scrollbar { width: 4px; }
.stream-process-body::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.1); border-radius: 3px; }
.stream-process-line {
+ display: flex;
+ align-items: flex-start;
+ gap: 6px;
padding: 1px 0;
white-space: pre-wrap;
word-break: break-all;
@@ -3733,20 +4106,28 @@ body.model-not-configured .main-content { flex-direction: column; }
and (b) folding into Normal loses the "someone is
waiting on you" signal at the rail level.
4. Error — hard error / failed tool; red-500 + 500 weight.
- Glyphs in `_processKindOf` map into these classes — adding a new
- glyph there needs a matching rule here, otherwise the line falls
- back to the Normal baseline. */
-.stream-process-line.kind-bound { color: #64748b; font-weight: 500; } /* ▶ ● lifecycle milestones */
-.stream-process-line.kind-tool { color: #64748b; font-weight: 500; } /* ■ tool call */
-.stream-process-line.kind-plan { color: #64748b; font-weight: 500; } /* ▣ plan announcement */
-.stream-process-line.kind-patch { color: #64748b; font-weight: 500; } /* ◉ file change */
-.stream-process-line.kind-think { color: #94a3b8; } /* ◆ ◇ reasoning / reply markers */
-.stream-process-line.kind-live { color: #94a3b8; } /* ◐ live generating */
-.stream-process-line.kind-out { color: #94a3b8; } /* ▷ command stdout */
-.stream-process-line.kind-meta { color: #94a3b8; } /* ▪ fallback / lifecycle meta */
-.stream-process-line.kind-warn { color: #d97706; } /* ○ awaiting approval / cli stderr */
-.stream-process-line.kind-err { color: #ef4444; font-weight: 500; } /* ◯ ✗ hard error / failed tool */
-.stream-process-line.kind-info { color: #6366f1; } /* ◇ auto-approved permission audit row */
+ `_eventProcessKind` maps events into these classes; old persisted
+ glyph-prefixed rows are normalized at render time. */
+.stream-process-line.kind-bound { color: #64748b; font-weight: 500; }
+.stream-process-line.kind-tool { color: #64748b; font-weight: 500; }
+.stream-process-line.kind-plan { color: #64748b; font-weight: 500; }
+.stream-process-line.kind-patch { color: #64748b; font-weight: 500; }
+.stream-process-line.kind-think { color: #94a3b8; }
+.stream-process-line.kind-live { color: #94a3b8; }
+.stream-process-line.kind-out { color: #94a3b8; }
+.stream-process-line.kind-meta { color: #94a3b8; }
+.stream-process-line.kind-warn { color: #d97706; }
+.stream-process-line.kind-err { color: #ef4444; font-weight: 500; }
+.stream-process-line.kind-info { color: #6366f1; }
+.stream-process-icon {
+ width: 13px;
+ height: 13px;
+ margin-top: 2px;
+}
+.stream-process-text {
+ min-width: 0;
+ flex: 1 1 auto;
+}
/* Expandable tool-result row: cursor hint + subtle underline on hover.
Used for CLI tool-event(result) rows whose full output spilled to
@@ -4143,8 +4524,13 @@ body.model-not-configured .main-content { flex-direction: column; }
.workspace-menu-check {
flex-shrink: 0;
- font-size: 15px;
color: var(--text);
+ display: inline-flex;
+ align-items: center;
+}
+.workspace-check-icon {
+ width: 15px;
+ height: 15px;
}
.workspace-menu-sep {
@@ -4360,6 +4746,10 @@ body.model-not-configured .main-content { flex-direction: column; }
font-size: 56px;
line-height: 1;
}
+.ctx-viewer-binary-icon .chat-file-kind-icon {
+ width: 56px;
+ height: 56px;
+}
.ctx-viewer-binary-name {
font-size: 14px;
font-weight: 500;
@@ -4702,6 +5092,10 @@ body.model-not-configured .main-content { flex-direction: column; }
opacity: 0.45;
cursor: not-allowed;
}
+.ctx-editor-svg-icon {
+ width: 15px;
+ height: 15px;
+}
.ctx-editor-toolbar-sep {
width: 1px;
height: 18px;
@@ -4709,7 +5103,16 @@ body.model-not-configured .main-content { flex-direction: column; }
margin: 0 4px;
}
.ctx-editor-toolbar-spacer { flex: 1; }
-.ctx-editor-toggle { font-size: 12px; }
+.ctx-editor-toggle {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ font-size: 12px;
+}
+.ctx-editor-toggle-icon {
+ width: 14px;
+ height: 14px;
+}
.ctx-editor-body {
display: flex;
flex-direction: column;
@@ -5060,7 +5463,17 @@ body.model-not-configured .main-content { flex-direction: column; }
transition: box-shadow 0.15s, background 0.15s;
}
.plan-rail-header:hover { background: #f8fafc; box-shadow: 0 2px 6px rgba(15, 23, 42, 0.12); }
-.plan-rail-title { flex: 0 0 auto; }
+.plan-rail-title {
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+}
+.plan-rail-title .ui-icon {
+ width: 14px;
+ height: 14px;
+ color: var(--primary);
+}
.plan-rail-progress {
flex: 0 0 auto;
color: var(--text);
@@ -5113,7 +5526,22 @@ body.model-not-configured .main-content { flex-direction: column; }
align-items: baseline;
gap: 6px;
}
-.plan-rail-step-icon { font-size: 14px; line-height: 1; flex: 0 0 auto; }
+.plan-rail-step-icon {
+ line-height: 1;
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+}
+.plan-rail-svg-icon {
+ width: 15px;
+ height: 15px;
+}
+.plan-rail-step.is-pending .plan-rail-svg-icon { color: #64748b; }
+.plan-rail-step.is-in_progress .plan-rail-svg-icon { color: var(--primary); }
+.plan-rail-step.is-done .plan-rail-svg-icon { color: #16a34a; }
+.plan-rail-step.is-failed .plan-rail-svg-icon { color: var(--danger); }
+.plan-rail-step.is-skipped .plan-rail-svg-icon { color: #94a3b8; }
+.plan-rail-step.is-blocked .plan-rail-svg-icon { color: #d97706; }
.plan-rail-step-num {
font-variant-numeric: tabular-nums;
opacity: 0.6;
@@ -5126,12 +5554,20 @@ body.model-not-configured .main-content { flex-direction: column; }
line-height: 1.4;
}
.plan-rail-step-transient {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
font-size: 12px;
color: var(--text);
opacity: 0.7;
white-space: nowrap;
flex: 0 0 auto;
}
+.plan-rail-transient-icon {
+ width: 12px;
+ height: 12px;
+ color: #7c3aed;
+}
/* Assignee on its own line, indented under the title text (icon + num
take ~32px). Smaller font, primary color, single line with ellipsis. */
.plan-rail-step-meta {
@@ -5158,12 +5594,12 @@ body.model-not-configured .main-content { flex-direction: column; }
padding-top: 4px;
}
-/* Per-status accents — only on the title to avoid icon recoloring (the
- emoji carries its own color). */
+/* Per-status accents — only on the title. Icons carry status color via
+ .plan-rail-svg-icon rules above. */
.plan-rail-step.is-done .plan-rail-step-title { opacity: 0.65; text-decoration: line-through; text-decoration-color: rgba(0,0,0,0.2); }
.plan-rail-step.is-skipped .plan-rail-step-title { opacity: 0.55; }
.plan-rail-step.is-failed .plan-rail-step-title { color: var(--danger); }
-.plan-rail-step.is-blocked .plan-rail-step-title { color: var(--text); /* neutral — the 📝 icon already conveys "awaiting input" */ }
+.plan-rail-step.is-blocked .plan-rail-step-title { color: var(--text); }
.plan-rail-step.is-in_progress .plan-rail-step-title { color: var(--primary); font-weight: 500; }
/* Detail-page action button row (shared across skills / agents / contexts).
@@ -5710,6 +6146,14 @@ body.model-not-configured .main-content { flex-direction: column; }
border-radius: 8px;
margin-bottom: 0;
}
+.agents-chat-input-area .chat-send-btn .send-icon {
+ width: 16px;
+ height: 16px;
+}
+.agents-chat-input-area .chat-send-btn .stop-icon {
+ width: 14px;
+ height: 14px;
+}
/* ═══ Settings panel ═══════════════════════════════════════════════════ */
@@ -5793,6 +6237,9 @@ body.model-not-configured .main-content { flex-direction: column; }
}
background: #0a0a0a;
color: #fff;
+}
+ background: #0a0a0a;
+ color: #fff;
}
font-size: 14px;
color: var(--ink, #0a0a0a);
@@ -5843,6 +6290,8 @@ body.model-not-configured .main-content { flex-direction: column; }
color: #b91c1c;
font-size: 12px;
white-space: pre-wrap;
+}
+ color: #b91c1c;
}
margin-top: 12px;
padding: 12px 14px;
@@ -6102,8 +6551,17 @@ body.model-not-configured .main-content { flex-direction: column; }
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
}
.ai-select-label.placeholder { color: var(--text-muted, #9ca3af); }
+.ai-select-label > span:last-child,
+.ai-select-item-label > span:last-child {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
.ai-select-caret {
flex: 0 0 auto;
color: #6b7280;
@@ -6146,8 +6604,19 @@ body.model-not-configured .main-content { flex-direction: column; }
.ai-select-item-label {
font-size: 13px;
color: #111827;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
}
.ai-select-item.active .ai-select-item-label { color: var(--primary, #2563eb); font-weight: 500; }
+.ai-select-option-icon {
+ display: inline-flex;
+ color: #d97706;
+}
+.ai-select-svg-icon {
+ width: 14px;
+ height: 14px;
+}
.ai-select-item-hint {
font-size: 11px;
color: var(--text-muted, #6b7280);
@@ -7570,17 +8039,3 @@ 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; }
-
-/* Per-agent connector toggle row inside the agent detail page */
-.agent-connector-row {
- display: grid;
- grid-template-columns: auto auto 1fr auto;
- gap: 10px;
- align-items: center;
- padding: 8px 0;
- font-size: 13px;
- border-bottom: 1px solid #f3f4f6;
- cursor: pointer;
-}
-.agent-connector-name { color: var(--text); }
-.agent-connector-id { font-family: ui-monospace, monospace; font-size: 11px; }
diff --git a/test/main/features/agents.test.ts b/test/main/features/agents.test.ts
index 7462d9e8..7c04e30b 100644
--- a/test/main/features/agents.test.ts
+++ b/test/main/features/agents.test.ts
@@ -59,7 +59,7 @@ function writeCustomAgent(agentId: string, fields: Partial<Record<string, any>>
const data: Record<string, any> = {
agent_id: agentId,
name: fields.name ?? agentId,
- description: fields.description ?? '',
+ description: fields.description ?? 'Test agent',
workflow: fields.workflow ?? '',
created_at: '2026-04-18T10:00:00',
updated_at: '2026-04-18T10:00:00',
@@ -567,18 +567,18 @@ describe('agents › createCustomAgent', () => {
it('defaults empty name to the localized "Untitled agent" fallback', async () => {
const a = await loadAgents();
- const agent = await a.createCustomAgent();
+ const agent = await a.createCustomAgent({ description: 'desc' });
expect(agent?.name).toBe('Untitled agent');
});
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.
- for (const bad of ['指挥官', '总指挥', 'commander', ' Commander ', '指 挥 官']) {
+ for (const bad of ['指挥官', '总指挥', 'コマンダー', '司令官', 'commander', ' Commander ', '指 挥 官', 'コ マ ン ダ ー']) {
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: '副指挥官' })).resolves.toBeTruthy();
+ await expect(a.createCustomAgent({ name: '副指挥官', description: 'desc' })).resolves.toBeTruthy();
});
});
@@ -1010,7 +1010,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' });
+ await a.createCustomAgent({ name: 'New', description: 'desc' });
const list = await a.listAgents();
expect(list).toHaveLength(1);
expect(list[0].name).toBe('New');
@@ -1018,7 +1018,7 @@ describe('agents › list cache invalidation', () => {
it('reflects updates immediately', async () => {
const a = await loadAgents();
- const agent = await a.createCustomAgent({ name: 'V1' });
+ const agent = await a.createCustomAgent({ name: 'V1', description: 'desc' });
await a.updateCustomAgent(agent!.agent_id, { name: 'V2' });
const list = await a.listAgents();
expect(list[0].name).toBe('V2');
diff --git a/test/main/features/auth.test.ts b/test/main/features/auth.test.ts
index fd248fd8..042b1824 100644
--- a/test/main/features/auth.test.ts
+++ b/test/main/features/auth.test.ts
@@ -333,12 +333,13 @@ describe('auth › entries (priority list)', () => {
// Remove credential p2 directly via removeCredential; since that cascades,
// it also drops e1. To simulate a dangling entry without cascade, reach
// into the json file.
- const fs = await import('node:fs');
const pathMod = await import('../../../src/main/paths');
+ const cryptoVault = await import('../../../src/main/util/crypto-vault');
const storePath = pathMod.userAuthProfilesFile(TEST_UID);
- const store = JSON.parse(fs.readFileSync(storePath, 'utf-8'));
+ const raw = fs.readFileSync(storePath, 'utf-8');
+ const store = JSON.parse(cryptoVault.decrypt(TEST_UID, raw));
delete store.profiles[p2.profileId];
- fs.writeFileSync(storePath, JSON.stringify(store));
+ fs.writeFileSync(storePath, cryptoVault.encrypt(TEST_UID, JSON.stringify(store)));
const pick = await a.pickChatEntry();
expect(pick).not.toBeNull();
diff --git a/test/main/features/config.test.ts b/test/main/features/config.test.ts
index d27ad44b..de5be359 100644
--- a/test/main/features/config.test.ts
+++ b/test/main/features/config.test.ts
@@ -79,10 +79,17 @@ describe('features/config › initLanguage', () => {
expect(appConfig.readConfig().language).toBe('zh');
});
- it('falls back to en for non-zh locales on first boot', async () => {
+ it('detects ja-* on first boot and persists', async () => {
+ const { appConfig, i18n } = await load();
+ expect(appConfig.initLanguage('ja-JP')).toBe('ja');
+ expect(i18n.getCurrentLang()).toBe('ja');
+ expect(appConfig.readConfig().language).toBe('ja');
+ });
+
+ it('falls back to en for unsupported locales on first boot', async () => {
const paths = await import('../../../src/main/paths');
const prefPath = paths.userPreferencesFile(TEST_UID);
- for (const locale of ['en-US', 'ja-JP', 'fr-FR', '']) {
+ for (const locale of ['en-US', 'fr-FR', '']) {
fs.rmSync(prefPath, { force: true });
vi.resetModules();
const users = await import('../../../src/main/features/users');
@@ -105,9 +112,9 @@ describe('features/config › initLanguage', () => {
describe('features/config › setLanguage', () => {
it('persists + updates in-memory current lang', async () => {
const { appConfig, i18n } = await load();
- appConfig.setLanguage('zh');
- expect(i18n.getCurrentLang()).toBe('zh');
- expect(appConfig.readConfig().language).toBe('zh');
+ appConfig.setLanguage('ja');
+ expect(i18n.getCurrentLang()).toBe('ja');
+ expect(appConfig.readConfig().language).toBe('ja');
});
it('rejects unsupported languages', async () => {
diff --git a/test/main/features/connectors/google-stdio-adapters.test.ts b/test/main/features/connectors/google-stdio-adapters.test.ts
new file mode 100644
index 00000000..449d3a15
--- /dev/null
+++ b/test/main/features/connectors/google-stdio-adapters.test.ts
@@ -0,0 +1,149 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createRequire } from 'node:module';
+import * as path from 'node:path';
+
+const requireCjs = createRequire(import.meta.url);
+
+type Adapter = {
+ TOOLS: Array<{ name: string }>;
+ callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>;
+};
+
+function loadAdapter(file: string): Adapter {
+ const full = path.join(process.cwd(), 'bin', file);
+ delete requireCjs.cache[full];
+ return requireCjs(full) as Adapter;
+}
+
+function jsonResponse(body: unknown, status = 200): { ok: boolean; status: number; text: () => Promise<string> } {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ text: async () => JSON.stringify(body),
+ };
+}
+
+function mockFetchOnce(body: unknown, status = 200): ReturnType<typeof vi.fn> {
+ const fetchMock = vi.fn(async () => jsonResponse(body, status));
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+}
+
+describe('Google stdio REST adapters', () => {
+ beforeEach(() => {
+ process.env.GOOGLE_ACCESS_TOKEN = 'test-access-token';
+ });
+
+ afterEach(() => {
+ delete process.env.GOOGLE_ACCESS_TOKEN;
+ vi.unstubAllGlobals();
+ });
+
+ it('exports tool metadata without starting the stdio server', () => {
+ for (const file of [
+ 'gmail-mcp-server.cjs',
+ 'gcal-mcp-server.cjs',
+ 'gdocs-mcp-server.cjs',
+ 'gsheets-mcp-server.cjs',
+ 'gtasks-mcp-server.cjs',
+ 'google-workspace-mcp-server.cjs',
+ ]) {
+ const adapter = loadAdapter(file);
+ expect(adapter.TOOLS.length).toBeGreaterThan(0);
+ expect(typeof adapter.callTool).toBe('function');
+ }
+ });
+
+ it('google workspace adapter aggregates service tools without starting the stdio server', () => {
+ const adapter = loadAdapter('google-workspace-mcp-server.cjs');
+ const names = adapter.TOOLS.map((t) => t.name);
+
+ expect(new Set(names).size).toBe(names.length);
+ expect(names).toContain('send_message');
+ expect(names).toContain('list_events');
+ expect(names).toContain('get_document');
+ expect(names).toContain('read_sheet');
+ expect(names).toContain('list_tasks');
+ });
+
+ it('gmail list_labels maps labels and sends the bearer token', async () => {
+ const fetchMock = mockFetchOnce({ labels: [{ id: 'INBOX', name: 'Inbox', type: 'system' }] });
+ const adapter = loadAdapter('gmail-mcp-server.cjs');
+
+ await expect(adapter.callTool('list_labels', {})).resolves.toEqual({
+ labels: [{ id: 'INBOX', name: 'Inbox', type: 'system' }],
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://gmail.googleapis.com/gmail/v1/users/me/labels',
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: 'Bearer test-access-token' }),
+ }),
+ );
+ });
+
+ it('calendar list_calendars maps calendarList items', async () => {
+ mockFetchOnce({ items: [{ id: 'primary', summary: 'Work', primary: true, accessRole: 'owner', timeZone: 'UTC' }] });
+ const adapter = loadAdapter('gcal-mcp-server.cjs');
+
+ await expect(adapter.callTool('list_calendars', {})).resolves.toEqual({
+ calendars: [{ id: 'primary', summary: 'Work', primary: true, accessRole: 'owner', timeZone: 'UTC' }],
+ });
+ });
+
+ it('docs create_document posts a title and returns document metadata', async () => {
+ const fetchMock = mockFetchOnce({ documentId: 'doc-1', title: 'Spec' });
+ const adapter = loadAdapter('gdocs-mcp-server.cjs');
+
+ await expect(adapter.callTool('create_document', { title: 'Spec' })).resolves.toEqual({
+ documentId: 'doc-1',
+ title: 'Spec',
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://docs.googleapis.com/v1/documents',
+ expect.objectContaining({
+ method: 'POST',
+ body: JSON.stringify({ title: 'Spec' }),
+ }),
+ );
+ });
+
+ it('sheets read_sheet encodes range and preserves values', async () => {
+ const fetchMock = mockFetchOnce({ range: 'Sheet1!A1:B2', majorDimension: 'ROWS', values: [['A', 'B']] });
+ const adapter = loadAdapter('gsheets-mcp-server.cjs');
+
+ await expect(adapter.callTool('read_sheet', { spreadsheetId: 'sheet 1', range: 'Sheet1!A1:B2' })).resolves.toEqual({
+ range: 'Sheet1!A1:B2',
+ majorDimension: 'ROWS',
+ values: [['A', 'B']],
+ });
+ expect(fetchMock.mock.calls[0][0]).toBe(
+ 'https://sheets.googleapis.com/v4/spreadsheets/sheet%201/values/Sheet1!A1%3AB2?valueRenderOption=FORMATTED_VALUE',
+ );
+ });
+
+ it('tasks list_tasklists maps task list summaries', async () => {
+ mockFetchOnce({ items: [{ id: 'tl-1', title: 'Today', updated: '2026-05-15T00:00:00Z' }] });
+ const adapter = loadAdapter('gtasks-mcp-server.cjs');
+
+ await expect(adapter.callTool('list_tasklists', {})).resolves.toEqual({
+ tasklists: [{ id: 'tl-1', title: 'Today', updated: '2026-05-15T00:00:00Z' }],
+ });
+ });
+
+ it('surfaces provider error messages with service and status', async () => {
+ const cases: Array<[string, string, string, Record<string, unknown>]> = [
+ ['gmail-mcp-server.cjs', 'Gmail API 403: denied', 'list_labels', {}],
+ ['gcal-mcp-server.cjs', 'Calendar API 403: denied', 'list_calendars', {}],
+ ['gdocs-mcp-server.cjs', 'Docs API 403: denied', 'create_document', { title: 'Spec' }],
+ ['gsheets-mcp-server.cjs', 'Sheets API 403: denied', 'read_sheet', { spreadsheetId: 's1', range: 'A1' }],
+ ['gtasks-mcp-server.cjs', 'Tasks API 403: denied', 'list_tasklists', {}],
+ ];
+
+ for (const [file, message, tool, args] of cases) {
+ mockFetchOnce({ error: { message: 'denied' } }, 403);
+ const adapter = loadAdapter(file);
+ await expect(adapter.callTool(tool, args)).rejects.toThrow(message);
+ vi.unstubAllGlobals();
+ }
+ });
+});
diff --git a/test/main/features/expert_signals/event.test.ts b/test/main/features/expert_signals/event.test.ts
deleted file mode 100644
index cb6b80d7..00000000
--- a/test/main/features/expert_signals/event.test.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- buildRetrySignal,
- buildSkipSignal,
- buildFormLeftBlankSignals,
- buildToolFailureSignal,
-} 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);
- });
-});
diff --git a/test/main/features/expert_signals/silence.test.ts b/test/main/features/expert_signals/silence.test.ts
deleted file mode 100644
index 396c047e..00000000
--- a/test/main/features/expert_signals/silence.test.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-import * as fs from 'node:fs';
-import * as os from 'node:os';
-import * as path from 'node:path';
-
-// 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/storage.test.ts b/test/main/features/expert_signals/storage.test.ts
deleted file mode 100644
index be18cb10..00000000
--- a/test/main/features/expert_signals/storage.test.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-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
deleted file mode 100644
index 4e06598b..00000000
--- a/test/main/features/expert_signals/text.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-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/group_chat/plan-recovery.test.ts b/test/main/features/group_chat/plan-recovery.test.ts
index 810cea04..0d2a8216 100644
--- a/test/main/features/group_chat/plan-recovery.test.ts
+++ b/test/main/features/group_chat/plan-recovery.test.ts
@@ -123,18 +123,53 @@ describe('plan recovery › retryStep', () => {
expect(fresh?.steps[0].transient_attempts).toBeUndefined();
});
- it('rejects when the step is not in failed state', async () => {
+ it('rejects terminal states that are not retry results', async () => {
const cid = newCid();
await seedPlan(TEST_UID, cid, {
steps: [{ title: 'Step 1', assignee: A_NAME, wait_for: [] }],
});
- // Fresh setPlan leaves status='pending'.
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ await plan.updateStep(TEST_UID, cid, 1, 'skipped', { failure_reason: 'user skipped it' });
+
const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
const r = await planExecutor.retryStep(TEST_UID, cid, 1);
expect(r.ok).toBe(false);
expect(r.error).toMatch(/not in failed state/);
});
+ it('treats repeated retry after recovery starts as idempotent', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [
+ { title: 'Step 1', assignee: A_NAME, wait_for: [] },
+ { title: 'Step 2', assignee: A_NAME },
+ { title: 'Step 3', assignee: A_NAME },
+ { title: 'Step 4', assignee: A_NAME },
+ ],
+ });
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ await plan.updateStep(TEST_UID, cid, 1, 'in_progress');
+ await plan.updateStep(TEST_UID, cid, 2, 'pending');
+ await plan.updateStep(TEST_UID, cid, 3, 'blocked');
+ await plan.updateStep(TEST_UID, cid, 4, 'done');
+
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ const inProgress = await planExecutor.retryStep(TEST_UID, cid, 1);
+ const pending = await planExecutor.retryStep(TEST_UID, cid, 2);
+ const blocked = await planExecutor.retryStep(TEST_UID, cid, 3);
+ const done = await planExecutor.retryStep(TEST_UID, cid, 4);
+ expect(inProgress.ok).toBe(true);
+ expect(pending.ok).toBe(true);
+ expect(blocked.ok).toBe(true);
+ expect(done.ok).toBe(true);
+
+ const fresh = await plan.readPlan(TEST_UID, cid);
+ expect(fresh?.steps[0].status).toBe('in_progress');
+ expect(fresh?.steps[1].status).toBe('pending');
+ expect(fresh?.steps[2].status).toBe('blocked');
+ expect(fresh?.steps[3].status).toBe('done');
+ });
+
it('cascade-unblocks downstream skipped via `aborted by step N failure` reason', async () => {
const cid = newCid();
await seedPlan(TEST_UID, cid, {
diff --git a/test/main/features/group_chat/plan_executor.test.ts b/test/main/features/group_chat/plan_executor.test.ts
index 2c072299..7c9cbdc7 100644
--- a/test/main/features/group_chat/plan_executor.test.ts
+++ b/test/main/features/group_chat/plan_executor.test.ts
@@ -7,7 +7,7 @@
* 1. Sequential pipeline + variable substitution between steps
* 2. Parallel fork (same parallel_group) + synthesis step waiting on all
* 3. Failure policy: abort_plan / continue / ask_commander
- * 4. user-assignee step blocks until user enqueues
+ * 4. user-assignee step renders a form, blocks until submit, then resumes
* 5. Auto plan_update on agent reply (no LLM plan_update tool call)
*/
@@ -104,6 +104,22 @@ async function readJsonl(uid: string, cid: string): Promise<any[]> {
return fs.readFileSync(file, 'utf-8').split('\n').filter(Boolean).map((l) => JSON.parse(l));
}
+async function waitForPlan(
+ uid: string,
+ cid: string,
+ predicate: (snapshot: any) => boolean,
+ timeoutMs = 5000,
+): Promise<any> {
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ const start = Date.now();
+ while (Date.now() - start < timeoutMs) {
+ const snapshot = await plan.readPlan(uid, cid);
+ if (snapshot && predicate(snapshot)) return snapshot;
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ throw new Error(`plan did not reach expected state within ${timeoutMs}ms`);
+}
+
// ── Helpers to assemble a plan_set tool-call inside a commander turn ─────
//
// The LLM mock yields `{type:'tool_use', name, input}` events to invoke a
@@ -333,10 +349,11 @@ describe('plan_executor › failure policies', () => {
// ─────────────────────────────────────────────────────────────────────────
describe('plan_executor › user-assignee step', () => {
- it('user step dispatches a question to user, plan waits, then continues on user reply', async () => {
+ it('user step dispatches a form to user, plan waits, then continues on form submit without waking commander', 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 groupChat = await import('../../../../src/main/features/group_chat');
_setScript(state.buildGmemberSessionId(cid, A_ID), [
{ type: 'final', text: '收到 user 的补充:' },
@@ -371,16 +388,71 @@ describe('plan_executor › user-assignee step', () => {
const question = lines.find((l) => l.from === 'commander' && l.to.includes('user'));
expect(question).toBeTruthy();
expect(question.text).toContain('Python');
+ expect(question.form).toMatchObject({
+ agent_id: 'user',
+ plan_step_index: 1,
+ submitted: false,
+ fields: [
+ expect.objectContaining({
+ id: 'response',
+ label: '问 user 用什么语言',
+ type: 'textarea',
+ required: true,
+ }),
+ ],
+ });
- // User answers.
- await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'TypeScript' });
+ // A regular chat message is allowed to start a commander discussion,
+ // but it must not be mistaken for the pending user-form answer.
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: '我不清楚啊,要讨论下' });
await waitForQuiescent(TEST_UID, cid, 5000);
snapshot = await plan.readPlan(TEST_UID, cid);
+ expect(snapshot?.steps[0].status).toBe('in_progress');
+ expect(snapshot?.steps[1].status).toBe('pending');
+
+ lines = await readJsonl(TEST_UID, cid);
+ expect(lines.find((l) => l.from === 'commander' && l.to.includes(A_ID))).toBeUndefined();
+ const stillWaitingQuestion = lines.find((l) => l.id === question.id);
+ expect(stillWaitingQuestion?.form.submitted).toBe(false);
+
+ // User answers through the rendered form. The facade returns a replay
+ // payload addressed to @user; after the bus strips that mention, the
+ // message stays user-visible but does not wake commander as a side turn.
+ const submit = await groupChat.markFormSubmittedAndDispatch({
+ userId: TEST_UID,
+ cid,
+ msgId: question.id,
+ formId: question.form.form_id,
+ values: { response: 'TypeScript' },
+ });
+ expect(submit.ok).toBe(true);
+ expect(submit.submission?.agent_id).toBe('user');
+ expect(submit.submission?.text).toContain('@user');
+ expect(submit.submission?.text).toContain('agent-input-submission');
+
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: submit.submission!.text });
+ snapshot = await waitForPlan(
+ TEST_UID,
+ cid,
+ (p) => p.steps[0].status === 'done' && p.steps[1].status === 'done',
+ 5000,
+ );
+ await waitForQuiescent(TEST_UID, cid, 5000);
+
expect(snapshot?.steps[0].status).toBe('done'); // user replied → step 1 closed
expect(snapshot?.steps[1].status).toBe('done'); // A then ran with substituted user answer
lines = await readJsonl(TEST_UID, cid);
+ const updatedQuestion = lines.find((l) => l.id === question.id);
+ expect(updatedQuestion?.form.submitted).toBe(true);
+ expect(updatedQuestion?.form.values).toEqual({ response: 'TypeScript' });
+
+ const userReplay = lines.find((l) => l.from === 'user' && l.text.includes('agent-input-submission'));
+ expect(userReplay).toBeTruthy();
+ expect(userReplay.to).toEqual(['user']);
+ expect(userReplay.text).not.toContain('@user');
+
const dispatchToA = lines.find((l) => l.from === 'commander' && l.to.includes(A_ID));
expect(dispatchToA).toBeTruthy();
expect(dispatchToA.text).toContain('TypeScript'); // {{step_1.output_summary}} got user's reply
@@ -473,77 +545,3 @@ describe('plan_executor › auto plan_update', () => {
expect(finalPlan?.completed_signaled).toBe(true); // single-step plan terminal → signal fired
}, 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/window_state.test.ts b/test/main/features/window_state.test.ts
new file mode 100644
index 00000000..288f898a
--- /dev/null
+++ b/test/main/features/window_state.test.ts
@@ -0,0 +1,106 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+const electronMock = vi.hoisted(() => ({
+ screen: {
+ getAllDisplays: vi.fn(),
+ getPrimaryDisplay: vi.fn(),
+ },
+}));
+
+vi.mock('electron', () => ({
+ screen: electronMock.screen,
+}));
+
+let tmpDir: string;
+let prevWs: string | undefined;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-window-state-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ electronMock.screen.getAllDisplays.mockReturnValue([
+ { workArea: { x: 0, y: 0, width: 1440, height: 900 } },
+ ]);
+ electronMock.screen.getPrimaryDisplay.mockReturnValue({
+ workArea: { x: 0, y: 0, width: 1440, height: 900 },
+ });
+ vi.resetModules();
+});
+
+afterEach(() => {
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ vi.clearAllMocks();
+});
+
+async function load() {
+ const paths = await import('../../../src/main/paths');
+ const state = await import('../../../src/main/features/window_state');
+ return { paths, state };
+}
+
+describe('features/window_state', () => {
+ it('uses the default bounds when no saved state exists', async () => {
+ const { state } = await load();
+
+ expect(state.restoreWindowState()).toEqual({
+ bounds: { width: 1280, height: 800 },
+ isMaximized: false,
+ });
+ });
+
+ it('restores a visible saved position and size', async () => {
+ const { paths, state } = await load();
+ fs.writeFileSync(paths.WINDOW_STATE_FILE, JSON.stringify({
+ x: 80,
+ y: 60,
+ width: 1100,
+ height: 720,
+ isMaximized: true,
+ }));
+
+ expect(state.restoreWindowState()).toEqual({
+ bounds: { x: 80, y: 60, width: 1100, height: 720 },
+ isMaximized: true,
+ });
+ });
+
+ it('keeps the saved size but drops an off-screen position', async () => {
+ const { paths, state } = await load();
+ fs.writeFileSync(paths.WINDOW_STATE_FILE, JSON.stringify({
+ x: 9000,
+ y: 9000,
+ width: 1000,
+ height: 700,
+ }));
+
+ expect(state.restoreWindowState()).toEqual({
+ bounds: { width: 1000, height: 700 },
+ isMaximized: false,
+ });
+ });
+
+ it('persists normal bounds for a maximized window', async () => {
+ const { paths, state } = await load();
+ const win = {
+ getBounds: vi.fn(() => ({ x: 0, y: 0, width: 1440, height: 900 })),
+ getNormalBounds: vi.fn(() => ({ x: 100, y: 80, width: 1180, height: 760 })),
+ isDestroyed: vi.fn(() => false),
+ isMaximized: vi.fn(() => true),
+ isMinimized: vi.fn(() => false),
+ };
+
+ state.saveWindowStateNow(win as never);
+
+ expect(JSON.parse(fs.readFileSync(paths.WINDOW_STATE_FILE, 'utf8'))).toEqual({
+ x: 100,
+ y: 80,
+ width: 1180,
+ height: 760,
+ isMaximized: true,
+ });
+ });
+});
diff --git a/test/main/i18n.test.ts b/test/main/i18n.test.ts
index d501dade..3dee6fae 100644
--- a/test/main/i18n.test.ts
+++ b/test/main/i18n.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'vitest';
import {
t, setCurrentLang, getCurrentLang,
- detectSystemLang, isLang, _resetCacheForTests,
+ acceptLanguageHeader, detectSystemLang, descriptionLang, isLang, _resetCacheForTests,
} from '../../src/main/i18n';
beforeEach(() => {
@@ -16,17 +16,24 @@ describe('i18n › detectSystemLang', () => {
}
});
- it('falls back to en for non-zh / malformed / empty', () => {
- for (const v of ['en-US', 'ja-JP', 'fr', '', null, undefined, 42]) {
+ it('maps ja* locales to ja', () => {
+ for (const v of ['ja', 'ja-JP']) {
+ expect(detectSystemLang(v)).toBe('ja');
+ }
+ });
+
+ it('falls back to en for non-supported / malformed / empty', () => {
+ for (const v of ['en-US', 'fr', '', null, undefined, 42]) {
expect(detectSystemLang(v)).toBe('en');
}
});
});
describe('i18n › isLang', () => {
- it('accepts exactly zh and en', () => {
+ it('accepts supported language codes', () => {
expect(isLang('zh')).toBe(true);
expect(isLang('en')).toBe(true);
+ expect(isLang('ja')).toBe(true);
expect(isLang('ZH')).toBe(false);
expect(isLang('fr')).toBe(false);
expect(isLang('')).toBe(false);
@@ -40,6 +47,8 @@ describe('i18n › t() lookup', () => {
expect(t('errors.not_utf8')).toBe('文本类文件必须是 UTF-8 编码');
setCurrentLang('en');
expect(t('errors.not_utf8')).toBe('Text files must be UTF-8 encoded');
+ setCurrentLang('ja');
+ expect(t('errors.not_utf8')).toBe('テキストファイルは UTF-8 エンコードである必要があります');
});
it('falls back to en when key missing in current lang', () => {
@@ -72,6 +81,22 @@ describe('i18n › t() lookup', () => {
it('per-call lang override takes precedence over current', () => {
setCurrentLang('en');
expect(t('errors.not_utf8', undefined, 'zh')).toBe('文本类文件必须是 UTF-8 编码');
+ expect(t('errors.not_utf8', undefined, 'ja')).toBe('テキストファイルは UTF-8 エンコードである必要があります');
expect(getCurrentLang()).toBe('en'); // override does not mutate state
});
});
+
+describe('i18n › descriptionLang', () => {
+ it('uses English descriptions for non-Chinese UI languages', () => {
+ expect(descriptionLang('zh')).toBe('zh');
+ expect(descriptionLang('en')).toBe('en');
+ expect(descriptionLang('ja')).toBe('en');
+ });
+});
+
+describe('i18n › acceptLanguageHeader', () => {
+ it('prefers the active UI locale for HTTP language negotiation', () => {
+ expect(acceptLanguageHeader('ja').startsWith('ja-JP')).toBe(true);
+ expect(acceptLanguageHeader('zh').startsWith('zh-CN')).toBe(true);
+ });
+});
diff --git a/test/main/model/core-agent/chat-history-tools.test.ts b/test/main/model/core-agent/chat-history-tools.test.ts
new file mode 100644
index 00000000..7d4fd237
--- /dev/null
+++ b/test/main/model/core-agent/chat-history-tools.test.ts
@@ -0,0 +1,176 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+let tmpDir: string;
+let prevWs: string | undefined;
+const TEST_UID = 'chattools';
+
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-chattools-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ vi.resetModules();
+ const users = await import('../../../../src/main/features/users');
+ users.activateUser(TEST_UID);
+});
+
+afterEach(() => {
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+function ctxFor(state: Record<string, unknown> = {}) {
+ return { state } as unknown as { state: Record<string, unknown> };
+}
+
+function writeConversation(cid: string, title: string, messages: unknown[]): void {
+ const dir = path.join(tmpDir, TEST_UID, 'cloud', 'chats');
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, `${cid}.jsonl`), messages.map((m) => JSON.stringify(m)).join('\n') + '\n');
+ const indexFile = path.join(dir, '_index.json');
+ let existing: any[] = [];
+ try {
+ const parsed = JSON.parse(fs.readFileSync(indexFile, 'utf8'));
+ existing = Array.isArray(parsed) ? parsed : [];
+ } catch { /* first conversation */ }
+ const next = existing.filter((c) => c?.conversation_id !== cid);
+ next.push({
+ conversation_id: cid,
+ title,
+ kind: 'normal',
+ agent_id: '',
+ skill_id: '',
+ session_id: `gconv-${cid}`,
+ created_at: '2026-01-01T00:00:00',
+ updated_at: '2026-01-01T00:00:00',
+ });
+ fs.writeFileSync(indexFile, JSON.stringify(next));
+}
+
+function firstHitCid(content: string): string {
+ const match = content.match(/- cid=([^ ]+)/);
+ return match ? match[1] : '';
+}
+
+describe('chat-history-tools › chat_search', () => {
+ it('finds current group-chat message text and returns cid/msg metadata', async () => {
+ writeConversation('cgroup', 'Planning chat', [
+ { id: 'm0', ts: '2026-01-01T00:00:00Z', from: 'user', to: ['commander'], mentions: [], text: 'remember the nebula migration decision' },
+ ]);
+ const { createChatHistoryTools } = await import('../../../../src/main/model/core-agent/chat-history-tools');
+ const [chatSearch] = createChatHistoryTools({ userId: TEST_UID });
+ const result = await chatSearch.execute({ query: 'nebula', k: 3 }, ctxFor());
+ expect(result.isError).toBeFalsy();
+ expect(result.content).toMatch(/cid=cgroup/);
+ expect(result.content).toMatch(/msg=0/);
+ expect(result.content).toMatch(/Planning chat/);
+ expect(result.content).toMatch(/nebula migration/);
+ });
+
+ it('rejects empty query', async () => {
+ const { createChatHistoryTools } = await import('../../../../src/main/model/core-agent/chat-history-tools');
+ const [chatSearch] = createChatHistoryTools({ userId: TEST_UID });
+ const result = await chatSearch.execute({ query: ' ' }, ctxFor());
+ expect(result.isError).toBe(true);
+ expect(result.content).toMatch(/required/);
+ });
+
+ it('prefers the current conversation when relevance ties', async () => {
+ writeConversation('cold', 'Older current chat', [
+ { id: 'm0', ts: '2026-01-01T00:00:00Z', from: 'user', to: ['commander'], mentions: [], text: 'priorityword same body' },
+ ]);
+ writeConversation('hot', 'Newer other chat', [
+ { id: 'm0', ts: '2026-02-01T00:00:00Z', from: 'user', to: ['commander'], mentions: [], text: 'priorityword same body' },
+ ]);
+ const { createChatHistoryTools } = await import('../../../../src/main/model/core-agent/chat-history-tools');
+ const [chatSearch] = createChatHistoryTools({ userId: TEST_UID, currentCid: 'cold' });
+ const result = await chatSearch.execute({ query: 'priorityword', k: 2 }, ctxFor());
+ expect(result.isError).toBeFalsy();
+ expect(firstHitCid(result.content)).toBe('cold');
+ expect(result.content).toMatch(/cid=cold .*current=true/);
+ });
+
+ it('prefers the current conversation when relevance is within 0.1', async () => {
+ const { rankChatHitsForTest } = await import('../../../../src/main/model/core-agent/chat-history-tools');
+ const ranked = rankChatHitsForTest([
+ { kind: 'chat', cid: 'other', msg_index: 0, conv_title: 'Other', role: 'user', time: '2026-02-01T00:00:00Z', snippet: 'slightly higher', score: 1.05 },
+ { kind: 'chat', cid: 'current', msg_index: 0, conv_title: 'Current', role: 'user', time: '2026-01-01T00:00:00Z', snippet: 'slightly lower', score: 1.0 },
+ ], 'current');
+ expect(ranked[0].cid).toBe('current');
+ });
+
+ it('uses recency as the tie-breaker after relevance and current conversation', async () => {
+ writeConversation('old', 'Old chat', [
+ { id: 'm0', ts: '2026-01-01T00:00:00Z', from: 'user', to: ['commander'], mentions: [], text: 'recencyword same body' },
+ ]);
+ writeConversation('new', 'New chat', [
+ { id: 'm0', ts: '2026-02-01T00:00:00Z', from: 'user', to: ['commander'], mentions: [], text: 'recencyword same body' },
+ ]);
+ const { createChatHistoryTools } = await import('../../../../src/main/model/core-agent/chat-history-tools');
+ const [chatSearch] = createChatHistoryTools({ userId: TEST_UID });
+ const result = await chatSearch.execute({ query: 'recencyword', k: 2 }, ctxFor());
+ expect(result.isError).toBeFalsy();
+ expect(firstHitCid(result.content)).toBe('new');
+ });
+});
+
+describe('chat-history-tools › chat_read', () => {
+ it('returns a window around the requested message index', async () => {
+ writeConversation('cread', 'Read chat', [
+ { id: 'm0', ts: '2026-01-01T00:00:00Z', from: 'user', to: ['commander'], mentions: [], text: 'first note' },
+ { id: 'm1', ts: '2026-01-01T00:01:00Z', from: 'commander', to: ['user'], mentions: [], text: 'middle answer' },
+ { id: 'm2', ts: '2026-01-01T00:02:00Z', from: 'user', to: ['commander'], mentions: [], text: 'last followup' },
+ ]);
+ const { createChatHistoryTools } = await import('../../../../src/main/model/core-agent/chat-history-tools');
+ const [, chatRead] = createChatHistoryTools({ userId: TEST_UID });
+ const result = await chatRead.execute({ cid: 'cread', msg_index: 1, window: 1 }, ctxFor());
+ expect(result.isError).toBeFalsy();
+ expect(result.content).toMatch(/<chat-history cid="cread"/);
+ expect(result.content).toMatch(/msgs 0\.\.2 \(hit=1\)/);
+ expect(result.content).toMatch(/first note/);
+ expect(result.content).toMatch(/middle answer/);
+ expect(result.content).toMatch(/last followup/);
+ });
+
+ it('returns latest messages when msg_index is omitted', async () => {
+ writeConversation('clatest', 'Latest chat', [
+ { id: 'm0', ts: '2026-01-01T00:00:00Z', from: 'user', to: ['commander'], mentions: [], text: 'old' },
+ { id: 'm1', ts: '2026-01-01T00:01:00Z', from: 'commander', to: ['user'], mentions: [], text: 'newer' },
+ ]);
+ const { createChatHistoryTools } = await import('../../../../src/main/model/core-agent/chat-history-tools');
+ const [, chatRead] = createChatHistoryTools({ userId: TEST_UID });
+ const result = await chatRead.execute({ cid: 'clatest', limit: 1 }, ctxFor());
+ expect(result.isError).toBeFalsy();
+ expect(result.content).not.toMatch(/old/);
+ expect(result.content).toMatch(/newer/);
+ });
+
+ it('rejects unsafe conversation ids', async () => {
+ const { createChatHistoryTools } = await import('../../../../src/main/model/core-agent/chat-history-tools');
+ const [, chatRead] = createChatHistoryTools({ userId: TEST_UID });
+ const result = await chatRead.execute({ cid: '../nope' }, ctxFor());
+ expect(result.isError).toBe(true);
+ expect(result.content).toMatch(/valid `cid`/);
+ });
+
+ it('rejects out-of-range message indexes', async () => {
+ writeConversation('crange', 'Range chat', [
+ { id: 'm0', ts: '2026-01-01T00:00:00Z', from: 'user', to: ['commander'], mentions: [], text: 'only message' },
+ ]);
+ const { createChatHistoryTools } = await import('../../../../src/main/model/core-agent/chat-history-tools');
+ const [, chatRead] = createChatHistoryTools({ userId: TEST_UID });
+ const result = await chatRead.execute({ cid: 'crange', msg_index: 4 }, ctxFor());
+ expect(result.isError).toBe(true);
+ expect(result.content).toMatch(/out of range/);
+ });
+});
+
+describe('chat-history-tools › shape', () => {
+ it('createChatHistoryTools returns search + read tools', async () => {
+ const { createChatHistoryTools } = await import('../../../../src/main/model/core-agent/chat-history-tools');
+ const tools = createChatHistoryTools({ userId: TEST_UID });
+ expect(tools.map((t) => t.name)).toEqual(['chat_search', 'chat_read']);
+ });
+});
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 73cd86d0..410e4360 100644
--- a/test/main/model/core-agent/connector-meta-tools.test.ts
+++ b/test/main/model/core-agent/connector-meta-tools.test.ts
@@ -97,6 +97,14 @@ const GITHUB_TOOLS: ToolSchema[] = [
},
];
+const GOOGLE_WORKSPACE_TOOLS: ToolSchema[] = [
+ { name: 'send_message', description: '[Gmail] Send Gmail.', input_schema: { type: 'object', properties: {} } },
+ { name: 'list_events', description: '[Calendar] List calendar events.', input_schema: { type: 'object', properties: {} } },
+ { name: 'get_document', description: '[Docs] Read Google Docs.', input_schema: { type: 'object', properties: {} } },
+ { name: 'read_sheet', description: '[Sheets] Read Google Sheets.', input_schema: { type: 'object', properties: {} } },
+ { name: 'list_tasks', description: '[Tasks] List Google Tasks.', input_schema: { type: 'object', properties: {} } },
+];
+
const UID = 'u-meta-001';
beforeEach(() => {
@@ -392,6 +400,64 @@ describe('list_connector_tools', () => {
expect(r.isError).toBe(true);
expect(r.content).toContain('E_CONNECTOR_NOT_VISIBLE');
});
+
+ it('dedupes Google Workspace tools when the matching single-service connector is also visible', async () => {
+ fixtures.instances = [
+ makeInstance({ id: 'google-workspace', display_name: 'Google Workspace', tools: GOOGLE_WORKSPACE_TOOLS }),
+ makeInstance({
+ id: 'gmail',
+ display_name: 'Gmail',
+ tools: [
+ { name: 'send_message', description: 'Send Gmail.', input_schema: { type: 'object', properties: {} } },
+ ],
+ }),
+ ];
+ const { createConnectorMetaTools } = await loadModule();
+ const [listTools] = await createConnectorMetaTools({ userId: UID });
+
+ const workspace = await runTool(listTools, { connector_id: 'google-workspace' });
+ expect(workspace.isError).toBeFalsy();
+ expect(workspace.content).not.toContain('### send_message');
+ expect(workspace.content).toContain('### list_events');
+
+ const gmail = await runTool(listTools, { connector_id: 'gmail' });
+ expect(gmail.isError).toBeFalsy();
+ expect(gmail.content).toContain('### send_message');
+ });
+
+ it('keeps Google Workspace Gmail tools when Gmail is not visible separately', async () => {
+ fixtures.instances = [
+ makeInstance({ id: 'google-workspace', display_name: 'Google Workspace', tools: GOOGLE_WORKSPACE_TOOLS }),
+ ];
+ const { createConnectorMetaTools } = await loadModule();
+ const [listTools] = await createConnectorMetaTools({ userId: UID });
+ const r = await runTool(listTools, { connector_id: 'google-workspace' });
+
+ expect(r.isError).toBeFalsy();
+ expect(r.content).toContain('### send_message');
+ expect(r.content).toContain('### list_events');
+ });
+
+ it('hides Google Workspace entirely when all of its service tools are shadowed by single-service connectors', async () => {
+ fixtures.instances = [
+ makeInstance({ id: 'google-workspace', display_name: 'Google Workspace', tools: GOOGLE_WORKSPACE_TOOLS }),
+ makeInstance({ id: 'gmail', tools: [{ name: 'send_message', description: '', input_schema: {} }] }),
+ makeInstance({ id: 'gcal', tools: [{ name: 'list_events', description: '', input_schema: {} }] }),
+ makeInstance({ id: 'gdocs', tools: [{ name: 'get_document', description: '', input_schema: {} }] }),
+ makeInstance({ id: 'gsheets', tools: [{ name: 'read_sheet', description: '', input_schema: {} }] }),
+ makeInstance({ id: 'gtasks', tools: [{ name: 'list_tasks', description: '', input_schema: {} }] }),
+ ];
+ const { getConnectorPromptBlock, createConnectorMetaTools } = await loadModule();
+
+ const block = await getConnectorPromptBlock(UID, undefined);
+ expect(block).not.toContain('**google-workspace**');
+ expect(block).toContain('**gmail**');
+
+ const [listTools] = await createConnectorMetaTools({ userId: UID });
+ const r = await runTool(listTools, { connector_id: 'google-workspace' });
+ expect(r.isError).toBe(true);
+ expect(r.content).toContain('E_CONNECTOR_NOT_VISIBLE');
+ });
});
// ── call_connector_tool ─────────────────────────────────────────────────
diff --git a/test/main/model/core-agent/tool-catalog.test.ts b/test/main/model/core-agent/tool-catalog.test.ts
index 59c7b14a..90d5264f 100644
--- a/test/main/model/core-agent/tool-catalog.test.ts
+++ b/test/main/model/core-agent/tool-catalog.test.ts
@@ -8,14 +8,15 @@ import { createCrossSessionMemoryTool } from '../../../../src/core-agent/src/too
import { createMetacognitionTool } from '../../../../src/core-agent/src/tools/metacognition-tool';
import { createLocalTools, createFileTools } from '../../../../src/main/model/core-agent/local-tools';
import { createKbTools } from '../../../../src/main/model/core-agent/kb-tools';
+import { createChatHistoryTools } from '../../../../src/main/model/core-agent/chat-history-tools';
import { createImageGenTool } from '../../../../src/main/model/core-agent/image-gen-tool';
/**
- * 收集 runner.ts 在"全开"条件下(uid 已知 + metacognition env on + permission
- * granted + 有 cid)会注入到 AgentRunner 的工具 name 集合。
+ * Collect the tool names runner.ts injects under "everything available"
+ * conditions (uid known + metacognition enabled + permission granted + cid).
*
- * 不调 buildRunner(那会拽进 auth / session / network),直接调每个工厂——
- * runner.ts 也是一一调它们组装 allTools 的,源头一致。
+ * Avoid buildRunner here because that pulls in auth / session / network; call
+ * the same factories runner.ts uses to assemble allTools.
*/
function enumerateAllInjectedToolNames(): Set<string> {
const names = new Set<string>();
@@ -45,6 +46,7 @@ function enumerateAllInjectedToolNames(): Set<string> {
for (const t of createLocalTools({ userId: 'testuid', cid: 'testcid', onArtifactCreated: () => {} })) names.add(t.name);
for (const t of createFileTools({ userId: 'testuid', cid: 'testcid' })) names.add(t.name);
for (const t of createKbTools({ userId: 'testuid' })) names.add(t.name);
+ for (const t of createChatHistoryTools({ userId: 'testuid' })) names.add(t.name);
names.add(createImageGenTool({ userId: 'testuid', cid: 'testcid' }).name);
// Connector umbrella meta-tools: two fixed tools, only injected when ≥1 connector is visible
@@ -59,42 +61,42 @@ function enumerateAllInjectedToolNames(): Set<string> {
}
describe('tool-catalog', () => {
- it('TOOL_CATALOG 覆盖 runner 实际注入的所有工具 name(反漂移)', () => {
+ it('TOOL_CATALOG covers every tool name injected by runner (anti-drift)', () => {
const injected = enumerateAllInjectedToolNames();
const catalog = new Set(TOOL_CATALOG.map((e) => e.name));
const missing = [...injected].filter((n) => !catalog.has(n));
- expect(missing, `这些工具被注入但 TOOL_CATALOG 缺失:${missing.join(', ')}`).toEqual([]);
+ expect(missing, `Injected tools missing from TOOL_CATALOG: ${missing.join(', ')}`).toEqual([]);
});
- it('TOOL_CATALOG 没有重复 name', () => {
+ it('TOOL_CATALOG has no duplicate names', () => {
const names = TOOL_CATALOG.map((e) => e.name);
expect(names.length).toBe(new Set(names).size);
});
- it('空 names 输入 → 空块', () => {
+ it('empty names input returns an empty block', () => {
expect(getToolsSystemPromptBlock([])).toBe('');
});
- it('未知 name 不抛、被静默跳过', () => {
- // 已知 + 未知混合,应该只渲染已知那个,块非空
+ it('unknown names are skipped without throwing', () => {
+ // Known + unknown should render only the known tool and still return a block.
const out = getToolsSystemPromptBlock(['read_file', 'definitely_not_a_real_tool']);
expect(out).toContain('read_file');
expect(out).not.toContain('definitely_not_a_real_tool');
});
- it('全部 name 都未知 → 空块', () => {
+ it('all unknown names return an empty block', () => {
expect(getToolsSystemPromptBlock(['__nope_a__', '__nope_b__'])).toBe('');
});
- it('同样输入产生同样输出(KV cache 友好)', () => {
+ it('same input produces the same output for KV-cache stability', () => {
const names = ['read_file', 'bash', 'kb_search'];
const a = getToolsSystemPromptBlock(names);
const b = getToolsSystemPromptBlock([...names]);
expect(a).toBe(b);
});
- it('输出按 group 顺序分节,且只含命中分组', () => {
- // read_file (fs) + bash (shell) + kb_search (kb) → 三个分节按 fs/shell/kb 序
+ it('renders sections in group order and includes only matched groups', () => {
+ // read_file (fs) + bash (shell) + kb_search (kb) -> fs/shell/kb order.
const out = getToolsSystemPromptBlock(['kb_search', 'bash', 'read_file']);
const fsIdx = out.indexOf('### Files / workspace');
const shellIdx = out.indexOf('### Shell');
@@ -102,14 +104,14 @@ describe('tool-catalog', () => {
expect(fsIdx).toBeGreaterThan(-1);
expect(shellIdx).toBeGreaterThan(fsIdx);
expect(kbIdx).toBeGreaterThan(shellIdx);
- // 没命中的分组不出现
+ // Unmatched groups are omitted.
expect(out).not.toContain('### PDF');
expect(out).not.toContain('### Image');
});
- it('权限门工具有 local-execution permission 后缀', () => {
+ it('permission-gated tools include a local-execution permission suffix', () => {
const out = getToolsSystemPromptBlock(['bash', 'read_file']);
- // bash 有 permission='localExec',read_file 没有
+ // bash has permission='localExec'; read_file does not.
const bashLine = out.split('\n').find((l) => l.includes('**bash**'));
const readLine = out.split('\n').find((l) => l.includes('**read_file**'));
expect(bashLine).toContain('local-execution permission');
diff --git a/test/renderer/chat-file-viewer.test.ts b/test/renderer/chat-file-viewer.test.ts
index 2ac5256b..da5828a2 100644
--- a/test/renderer/chat-file-viewer.test.ts
+++ b/test/renderer/chat-file-viewer.test.ts
@@ -35,6 +35,7 @@ describe('chat-file-viewer › _kindOf', () => {
['app.ts', 'text'],
['style.css', 'text'],
['log.log', 'text'],
+ ['video.mp4', 'video'],
])('classifies "%s" as %s', (name, kind) => {
expect(_kindOf(name)).toBe(kind);
});
@@ -49,7 +50,6 @@ describe('chat-file-viewer › _kindOf', () => {
['doc.docx', 'unsupported'], // we deliberately don't preview docx in this round
['binary.exe', 'unsupported'],
['photo.heic', 'unsupported'], // image-ish but not in the allow-list
- ['video.mp4', 'unsupported'], // video isn't a viewer kind; main chat shows inline <video>
['no-extension', 'unsupported'],
['', 'unsupported'],
['file.', 'unsupported'],
diff --git a/test/renderer/utils-dashboard.test.ts b/test/renderer/utils-dashboard.test.ts
deleted file mode 100644
index e936d005..00000000
--- a/test/renderer/utils-dashboard.test.ts
+++ /dev/null
@@ -1,237 +0,0 @@
-// 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: 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);
- });
-});