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(cli-agents + chat preview + marketplace polish + KB layout)

wyt978c90f88e31
diff --git a/CLAUDE.md b/CLAUDE.md
index a52d7b5a..318591d3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -16,7 +16,7 @@ Single-process Electron desktop app: main = Node backend, renderer = vanilla HTM
- **Local CLI agents are the one explicit exception** — agents whose spec carries `runtime.kind === 'cli'` (claude code / codex / openclaw / opencode / hermes) are spawned as child processes by `features/local_agents/runner.ts`. **`features/local_agents/` is the sole `child_process.spawn` entry point for CLI dispatches**; `bus.ts` routes here, every other `features/*` module is forbidden from spawning these CLIs directly. **Why:** a single spawn entry guarantees uniform persistence (`<uid>/local/file_cache/local-agent-runs/<runId>/`), cancellation (AbortSignal → SIGTERM → 10s grace → SIGKILL), and 5-CLI fanout discipline — bypassing it leaks zombies and forks the run-history schema.
- Storage is JSON / JSONL primarily; sqlite is used in exactly one place — the KB vector store. **Why:** user data must stay readable, portable, and friendly to cloud sync (single file = single sync unit).
- **skill / agent / contexts are three first-class citizens**; multi-agent collaboration follows the §5 group-chat architecture, with **no more "main agent calls subagent over RPC"**.
-- npm dependency allow-list is in `PC/package.json` (key entries: `electron / pi-ai / better-sqlite3 / sqlite-vec / fastembed / onnxruntime-node / pdfjs-dist / pdf-lib / mammoth / jimp / adm-zip`). **New dependencies require a discussion first.**
+- npm dependency allow-list is in `PC/package.json` (key entries: `electron / pi-ai / better-sqlite3 / sqlite-vec / fastembed / onnxruntime-node / pdfjs-dist / pdf-lib / mammoth / jimp / adm-zip / cos-nodejs-sdk-v5`). **New dependencies require a discussion first.**
- Renderer-side third-party JS/CSS goes through static assets at `src/renderer/vendor/<name>/`; not via npm. **Why:** `require` is unavailable inside the contextBridge sandbox; routing through npm is actually a detour.
- **Cross-platform**: macOS + Windows are both primary (Linux is community-grade). New code prefers cross-platform implementations (Node stdlib); platform branches must be verified on real machines for each branch — getting one platform working is not enough.
- **Profile (region) routing**: `ORKAS_PROFILE` env selects which Orkas server region the PC talks to — `global` (default, `orkas.ai`) or `cn` (`orkas.work`). Mirrors Server `env/start/{dev_,}api_start.sh` (see Server CLAUDE.md §7). `run.sh` exports it from the first positional arg (`./run.sh cn`). Code that calls the Orkas API **must** route through `features/marketplace.ts::apiBase()` — never hard-code `orkas.ai` / `orkas.work`. Devs running against a local Server set `ORKAS_API_BASE_URL=http://127.0.0.1:8888/api` (overrides the profile lookup entirely). Telemetry / umami is intentionally NOT profile-gated (single-site analytics, see `renderer/modules/monitor.js` comment).
@@ -65,6 +65,7 @@ util/ Pure-function utilities (stdlib only or single third-party d
- `features/` → `storage` / `paths` / `prompts` / `model` / `util` / sibling features
- `model/core-agent/` → dynamic `import('#core-agent')`; locks via `util/locks`; **never read or write business data under data/** (only session jsonl). **Why:** the model layer is stateless; orchestration of business state lives only in features. The model layer touching business data = double-write = state desync.
- `features/local_agents/` is the **only feature module allowed to import `child_process`**. Other features must call `local_agents/runner.run(...)` for CLI dispatches; never spawn a coding CLI from anywhere else.
+- **CLI backends MUST answer `control_request` records on stdin** — claude code gates tool-use / hook permission through this side-channel even in `--permission-mode bypassPermissions` (MCP servers, user hooks). An unanswered request blocks the child forever waiting on stdin; the failure mode is a silent 20-minute hang ending in our wall-clock SIGTERM. The current handler in `claude.ts` writes a `behavior:'allow'` control_response and emits a `permission-request` event for the rail; if you change permission policy, keep the stdin write — never leave a control_request unanswered. Codex / opencode / ACP have their own out-of-band permission settings (`approvalPolicy`, `HERMES_YOLO_MODE`) and no equivalent stdin channel.
**Key model/core-agent constraints** (each *-tool.ts has a header comment with the implementation details):
- **Adding a new tool** = entry in `tool-catalog.ts::TOOL_CATALOG` (the anti-drift test relies on this) + register with the runner; system-prompt order is fixed `[systemPrompt → skillsBlock]` (KV-cache stable prefix first). **Tool descriptions go only through the SDK tool-use protocol's API tools field** (full description + JSON schema); **do not inject a "## Available tools" block into the prompt** — that's both duplication and a variable prefix that pollutes the cache.
@@ -120,7 +121,7 @@ PC/data/
│ ├── chat_artifacts/<cid>/<artifactId>/ LLM-generated interactive web-app bundles (`create_artifact`); served read-only via `chat-app://`; purged by cid on conv delete (see §5)
│ ├── saved_apps/<appId>/ User-kept copies of `create_artifact` apps ("My Apps" tab); conversation-independent; never auto-purged; opened via `shell.openPath` (file://) (see §5)
│ ├── sessions/<sid>.jsonl core-agent PersistentSession
- │ ├── contexts/ KB user-managed directory tree + .kb/vector.db (see §7)
+ │ ├── contexts/ KB user-managed directory tree (source files only; vector.db lives under local/contexts/.kb — see §7)
│ ├── memory/MEMORY.md + USER.md
│ ├── agents/<aid>/ Custom agent: agent.json (spec) + meta/ (metacognition) + skills/ (self-evolved SkillStore)
│ ├── skills/<sid>/ Custom skills (System A, scanned by SkillLoader)
@@ -140,14 +141,20 @@ PC/data/
**Hard constraints**:
1. **At top level**, only `users.json` / `logs/` / `<uid>/` are allowed; per-user data must land under `<uid>/{cloud,local}/`. There is no shipped global `builtin/` tree (retired with the marketplace cutover; one-shot migration in `util/migrate-marketplace.ts` moves any legacy `data/builtin/` into the active uid's cloud tree on first launch, then deletes it).
-2. **Platform agents / skills are marketplace-only**: published to the server via `marketplace_dev.upload*` (dev only), installed via `marketplace.installMarketplace*` to `<uid>/local/marketplace/{agents,skills}/<id>/`. The on-disk dir contains the same shape as a custom one (`agent.json` for agents, `SKILL.md` + script files for skills) plus a `_install.json` with `(version, published_at)` used by reconcile to detect drift. The cloud-synced manifest `<uid>/cloud/marketplace/installs.json` records `{id, version, published_at, url}` per entry; `marketplace_reconcile.reconcileInstalls(uid)` runs on startup, parallel-fetches anything missing from the local tree, and re-pulls when the manifest version disagrees with `_install.json`. **Why this split**: content is binary-blob / catalog-versioned and would tear cloud sync if every machine wrote the same bytes; per-machine local copy + tiny cloud-synced manifest = single source of truth at the manifest level, machine-private at the content level. The loaders scan `[<uid>/cloud/{agents,skills}/, <uid>/local/marketplace/{agents,skills}/]`; custom takes precedence over a platform install with the same id.
+2. **Platform agents / skills are marketplace-only**: published to the server via `marketplace_dev.upload*` (dev only), installed via `marketplace.installMarketplace*` to `<uid>/local/marketplace/{agents,skills}/<id>/`. The on-disk dir contains the same shape as a custom one (`agent.json` for agents, `SKILL.md` + script files for skills) plus a `_install.json` with `(version, published_at)` used by reconcile to detect drift. The cloud-synced manifest `<uid>/cloud/marketplace/installs.json` records `{id, version, published_at, url}` per entry; `marketplace_reconcile.reconcileInstalls(uid)` runs on startup, parallel-fetches anything missing from the local tree, and re-pulls when the manifest version disagrees with `_install.json`. Immediately before reconcile, `checkServerUpdatesForInstalls(uid)` sweeps every installed id against the server `/marketplace/{agents,skills}/list` endpoint and bumps the manifest's `(version, published_at)` when the server is newer — admin republishes propagate to every client on next startup without user action; offline boots swallow the network error and fall through to a normal reconcile against the stale manifest. **Why this split**: content is binary-blob / catalog-versioned and would tear cloud sync if every machine wrote the same bytes; per-machine local copy + tiny cloud-synced manifest = single source of truth at the manifest level, machine-private at the content level. The loaders scan `[<uid>/cloud/{agents,skills}/, <uid>/local/marketplace/{agents,skills}/]`; custom takes precedence over a platform install with the same id.
3. **Agent directory shape (per-agent asset aggregation)**: `<uid>/cloud/agents/<aid>/` contains `agent.json` (the sole UI display source — pure spec) + `meta/` (metacognition: COMPETENCE.md + LEARNING_STRATEGIES.md) + `skills/` (SkillStore self-evolved skills, visible only to this agent, not injected into the SkillLoader system-prompt block). Deleting an agent = `rm -rf <aid>/`, no cascade. See `docs/plans/agent-as-directory.md`. **Do not** revert to the old top-level `meta/` or `PC/skills/` (the SkillStore default cwd).
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 part of cloud sync**: on conflict take the newer mtime; the loser's startup `kb_indexer.reconcile(uid)` reconciles by sha1. **Journal mode is DELETE, not WAL** (avoiding `.db-wal` / `.db-shm` sidecar files that would themselves need syncing — empirically that tears).
-6. **`<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.
+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 = **OAuth `user_id`** (NOT the local 8-digit `uid`); per-machine path stays `<container>/data/<local_uid>/cloud/`, and `<oauth_user_id>/` is the cloud-side mirror. Why: 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 `<oauth_user_id>/cloud/*` keys; `features/sync/manifest.ts::commitManifest` (POST `/sync/manifest/commit`) is the **sole** writer of `<oauth_user_id>/manifest.json` (CAS + quota atomic on the Server side). PC's STS scope is `<oauth_user_id>/*` for read, `<oauth_user_id>/cloud/*` for write — `manifest.json` is read-only for PC by design.
+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.
+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.
**uid lifecycle** (`features/users.ts`): on startup, `initActiveUser()` reads or creates `users.json` (8-digit numeric uids); `activateUser(uid)` is responsible for skeleton mkdir + injecting `process.env.CORE_AGENT_AUTH_DIR` + clearing caches. All user-scoped features get the uid via `getActiveUserId()` (throws if not activated). One active uid at a time for now.
+**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`.
+
+**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.)
+
---
## 5. Conversation / session isolation (core security invariant)
@@ -224,11 +231,11 @@ The artifact card's header collapses into one `⋯` popover: **reload** / **open
## 6. Skills
-Sources = `<uid>/cloud/skills/` (custom, cloud-synced) + `<uid>/local/marketplace/skills/` (platform, per-machine; reconciled from the cloud-synced `<uid>/cloud/marketplace/installs.json` manifest — see §4 constraint 2). `SkillLoader` scans `[custom, platform]` and injects them into the system prompt; **custom takes precedence over a platform install with the same id**. The same per-machine + cloud-manifest split applies to agents (`<uid>/local/marketplace/agents/<id>/agent.json`). `category` / `version` live in the install manifest, never in `agent.json` / SKILL.md frontmatter for the platform copy; the on-disk spec shape is the same as a custom one.
+Sources = `<uid>/cloud/skills/` (custom, cloud-synced) + `<uid>/local/marketplace/skills/` (platform, per-machine; reconciled from the cloud-synced `<uid>/cloud/marketplace/installs.json` manifest — see §4 constraint 2). `SkillLoader` scans `[custom, platform]` and injects them into the system prompt; **custom takes precedence over a platform install with the same id**. The same per-machine + cloud-manifest split applies to agents (`<uid>/local/marketplace/agents/<id>/agent.json`). `category` is part of the spec itself (SKILL.md frontmatter / agent.json field) — same shape as custom; downstream readers (`listAgents` / `listSkills`) read it from one place. **Why:** earlier the dev upload tool didn't write category back into the spec, so platform installs lacked the field on disk; that's been fixed (`marketplace_dev.ts::uploadCustom*` rewrites the spec before zipping). `version` and `published_at` stay in `_install.json` + `installs.json` — they are install-state metadata, not spec content.
**Authoring rules are themselves platform skills** (installed from the marketplace under `agent-creator` / `skill-creator` ids): they carry the canonical authoring rules for `<agent>` and `<skill>` containers. The four chat prompts (`chat_commander.md` + the three inline edit chats) point at them via `read_file <ROOT>/agent-creator/SKILL.md`. When changing authoring semantics — field shapes, validation rules, similarity-check protocol, edit-loop, prose forbidden words — update **only** the matching `*-creator/SKILL.md` and republish through the marketplace upload flow; the chat prompts already reference it on demand. See §3 "Authoring rules live in builtin skills" for the cross-prompt sync convention.
-**Dev-mode only**: platform skills + agents become editable through the existing inline edit chat (the `source !== 'custom'` guard is lifted when `isDevEnv()`); the ⋯ menu also exposes "delete" and "promote to platform" entries. Writes target the local install dir (`<uid>/local/marketplace/{agents,skills}/<id>/`) only — there is no shipped src tree to dual-write into. Server-side publishing is a separate flow through `marketplace_dev.upload*`. Two-layer protection: (1) runtime `isDevEnv()` gate on every entry; (2) physical exclusion at packaging time via `package.json::build.files` `!src/main/features/*_dev.ts` + `!src/main/ipc/dev_handlers.ts` (the dev modules are never present in asar). The setup prompt for platform editing uses `i18n.ts::buildBuiltinEditingConstraint()` (English-only output except `description_zh`) instead of the user-language directive — see §3.
+**Dev-mode only**: platform skills + agents become editable through the existing inline edit chat (the `source !== 'custom'` guard is lifted when `false`); the ⋯ menu also exposes "delete" and "promote to platform" entries. Writes target the local install dir (`<uid>/local/marketplace/{agents,skills}/<id>/`) only — there is no shipped src tree to dual-write into. Server-side publishing is a separate flow through `marketplace_dev.upload*`. Two-layer protection: (1) runtime `false` gate on every entry; (2) physical exclusion at packaging time via `package.json::build.files` `!src/main/features/*_dev.ts` + `!src/main/ipc/dev_handlers.ts` (the dev modules are never present in asar). The setup prompt for platform editing uses `i18n.ts::buildBuiltinEditingConstraint()` (English-only output except `description_zh`) instead of the user-language directive — see §3.
**Platform skill / agent source files keep their primary text in English** (SKILL.md body / examples, and the system / persona / workflow of platform agent specs): they ship to a multilingual user base, the LLM auto-replies in the conversation language, and there is no need for a Chinese fallback in the source files; mixing in Chinese makes English-speaking users see half-translated content. Custom skills / agents are user-authored and have no language restriction.
@@ -263,11 +270,11 @@ Sources = `<uid>/cloud/skills/` (custom, cloud-synced) + `<uid>/local/marketplac
## 7. Knowledge base (contexts)
-`<uid>/cloud/contexts/` is the user-managed directory tree (mixed md/txt/pdf/docx/image, cloud-synced) + `.kb/vector.db` (derived vector store, also cloud-synced). See `features/{contexts, kb_indexer, vec_store, kb_vector}.ts`.
+`<uid>/cloud/contexts/` is the user-managed directory tree (mixed md/txt/pdf/docx/image, cloud-synced). The derived `vector.db` + its model config lock live at the machine-private mirror `<uid>/local/contexts/.kb/` — NOT cloud-synced (batch 2). See `features/{contexts, kb_indexer, vec_store, kb_vector}.ts` + `util/migrate-kb-to-local.ts` for the one-shot path migration.
**Key constraints**:
- **Embedder is fixed at `bge-small-zh-v1.5`, 512 dims**; switching models requires a full rebuild (`config.json` lock prevents accidental swaps). The model is ~95 MB and ships via the installer's `extraResources`, so zero download / zero network at runtime.
-- **Journal mode is DELETE, not WAL** (the `.db-wal/.db-shm` sidecar files would tear cloud sync — see §4).
+- **Journal mode is DELETE, not WAL** — kept for continuity with existing `kb_files` rows (the original "WAL would tear cloud sync" rationale is moot now that vector.db is machine-private, but switching brings no benefit).
- **No `worker_threads` for multiple ONNX sessions**: empirically the native layer SIGSEGVs (OpenMP threadpool + concurrent allocator init is a known dangerous combination); for true parallelism use `child_process`.
- The model side may use only `kb_search` / `kb_read` tools; **`cat` / `rg` access to `$contexts_dir/` is forbidden** (stated in `chat_core.md`).
- Chunk cap is `EMBED_MAX_CHARS=400` chars (matching the 512-token window); no overlap across segments to avoid topic pollution.
@@ -369,6 +376,16 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t
- Reintroduce an aggregate `projects/_index.json`. Project existence is the set of `projects/<pid>/project.json` files on disk; listing scans the directory. **Why:** an aggregate index re-creates the multi-device sync conflict surface this round was designed to avoid (every membership change becomes a multi-file transactional write), and once a server-mediated collab story lands, server-side sync of project directories is a directory-level operation — clients only ever scan. See `features/projects.ts` header.
- Apply the project agent/skill scope as a 5th `component_enabled` filter site. Project scope is an OUTER intersection plumbed through the existing render entry points (`buildAgentsIndexBlock` `allowedIds` / `getSystemPromptBlock` `allowlist`) — see §6.
+**Multi-device sync (plan: `PC/docs/plans/multi-device-sync.md`)**:
+- Write `<oauth_user_id>/manifest.json` from PC (any code path). The Server's `/sync/manifest/commit` is the **sole** writer; the CAS + size-delta quota check is server-side atomic. PC has STS scope `<oauth_user_id>/cloud/*` for writes — `manifest.json` is read-only for PC by design.
+- Use the local 8-digit `uid` for the COS prefix. Cloud paths are scoped by **OAuth `user_id`**, not by the local container uid (same OAuth account on two machines = same cloud prefix, different local uids).
+- Bypass `features/sync/transport.ts` for any object under `<oauth_user_id>/`. Anyone touching the sync engine's bucket must go through that module (STS caching, gzip whitelist, multipart upload, rename optimization all live there).
+- Re-introduce a `codec.ts` abstraction in `features/sync/` (batch 3 decision: v1 ships no application-layer encryption; pre-emptive abstraction adds reading cost without value). v2 E2EE work is a clean re-introduction, not a re-edit.
+- Set `Content-Encoding: gzip` on uploads — `cos-nodejs-sdk-v5` auto-decompresses on GET when that header is present, defeating the BYO-encoding contract (the goal is COS never decompresses). Use the custom `x-cos-meta-compressed: gzip` metadata + `Content-Type: application/gzip` per `transport.ts`.
+- Treat manifest entry `size` as plaintext bytes — `size` is the **actual COS-stored byte count (compressed if compressed)** (batch 8). Quota tracking lives in `user_sync_usage.bytes` on the Server, also compressed.
+- Add a new sync trigger pathway that doesn't go through the `DirtyBus` debounce. The five canonical triggers are: startup (post-marketplace reconcile), debounce-fired dirty event, manual ("立即同步" button), periodic 5-minute 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 lives in `engine.ts::GLOBAL_FLOOR_MS`; manual + before-quit bypass it intentionally — periodic respects it (a recent pass for any reason defers the next tick).
+- Wire a `dirty` event in a feature without calling `syncFeature.markDirty(domain, 'cloud/<rel>')` (and never with `'local/...'`, which would corrupt the local index).
+
**Artifacts (`chat-app://`)**:
- Serve artifact bytes from anywhere but `chat_artifacts/<cid>/<artifactId>/` via the `chat-app://` handler; let `create_artifact` write outside the current cid's artifact pool. Every request goes through `chatArtifacts.resolveArtifactFilePath` (safe-cid / safe-artifactId / safe-relpath + `path.relative` traversal guard + served-extension allowlist) — see §5.
- Expose `window.orkas` / IPC / any privileged handle into the artifact iframe. The only artifact→app channel is the validated `postMessage` contract; the iframe is sandboxed (`allow-scripts allow-same-origin allow-forms`, cross-origin to the renderer) and never gets a host handle.
diff --git a/docs/plans/multi-device-sync.md b/docs/plans/multi-device-sync.md
new file mode 100644
index 00000000..3fbef8f9
--- /dev/null
+++ b/docs/plans/multi-device-sync.md
@@ -0,0 +1,576 @@
+# 多设备同步(multi-device-sync)— 方案
+
+> 状态:草稿,按批次确认中。
+> 跨项目:PC(Electron 主进程 + renderer)+ Server(FastAPI + COS)。
+> 验收后按 CLAUDE.md「Plan first」约定删除本文件。
+
+---
+
+## 0. 决议日志(按批次)
+
+### 批次 1(COS 访问通道) — ✅ 已决议
+- **方案 B:STS 直传**。PC 调 `/sync/sts` 拿 1h 临时凭据后直发 COS;manifest commit 与配额计账仍由 Server 端点(保 CAS 原子)。
+- **新依赖** `cos-nodejs-sdk-v5` 加入 `PC/package.json` 的 allow-list(要在 PC/CLAUDE.md §1 同步)。
+- **marketplace 上传保持 server-proxy**,不迁 STS 直传。Why:dev-only 频次极低、server 居中做 id 分配 + spec 重写、ACL public-read 维度与同步 private 不同,迁移收益负值。
+
+### 批次 8(传输优化与增量同步) — ✅ 已决议
+- **单文件 gzip**(BYO encoding 模式):PC 两端自己加解压;COS 完全不感知压缩、永远不解压;不设 `Content-Encoding` 头(避免 SDK 自动解压);扩展名白名单 + 明文 > 4 KB 阈值;路径不加 `.gz` 后缀(COS path 与本地一对一镜像);sha 算明文,`size` 算压缩后字节(与配额对齐)。
+- **不做 bundle zip**:会破坏 manifest per-file diff 模型。
+- **配额按实际 COS 占用计**(压缩后字节,不是明文)。Why:资源被限制的应该按真实占用算;不耦合压缩策略;用户得到压缩率高的文件类型的隐性福利。
+- **大文件 multipart + 续传**:> 5 MB 自动 multipart;状态进 `local/sync/state.json::pending_uploads[]`,断点续传,upload_id 7 天过期。
+- **批量删除走 DeleteMultipleObjects**(≤ 1000 / 批)。
+- **Rename 优化 v1 做**:local_index 维护 `sha → [paths]` 反查;命中时本地 `fs.copyFile` 或远端 `PutObjectCopy`,避免重复传输。
+- **不做 byte-level dedup**(rsync 风格):复杂度跳一档,COS 不原生支持,业界主流不暴露。
+- **活跃 jsonl 整文件重传**作为 v1 已知开销接受,靠 debounce 缓解;v1.x 看带宽用量决定是否做分片。
+- **增量分三层**:manifest ETag(L1)→ 文件 sha diff(L2)→ multipart part 续传(L3)。
+
+### 批次 7(业界对照后修订) — ✅ 已决议
+- **同 message_id 双侧编辑也留底**(append-only 假设的盲区):原 plan "按 mtime 取较晚胜出" 会**默默丢失败者修改**。修订为:新 id 双侧追加直接 union;**同 id 双侧编辑 = 冲突**,败者那一条 message 写入 `local/sync/conflicts/<ts>-<rel_path>.jsonl`(仅含被覆盖的那条),走与可变 JSON 同款的恢复 UX。Why:业界(Dropbox / Obsidian / git)面对这种场景都不会默默丢——我们对外宣称"自动合并 jsonl",必须在覆盖发生时给用户保留路径。
+- **冲突留底保留期改为 profile 配置项** `sync_conflict_retention_days`(默认 30 天)。Why:Obsidian Sync 付费档最高保留 1 年,30 天硬编码偏短;改成 profile 字段后,未来按会员等级可调到 90 / 180 / 365 天(与配额分级同设计模式)。
+
+### 批次 5(实施保障) — ✅ 已决议
+- **冲突合并器单测必做**(按 PC/CLAUDE.md §9 "Hard rule for LLM-output text munging" 同标准):set A 真实命中 + set B 似是而非不命中;走 `npm test`,绝不用 `npx vitest`(会留下 sqlite ABI 烂摊子)。
+- CLAUDE.md / strip-rules 三处改动表述按 §9 草稿落地(vector.db 反转 / 新增 §N sync 引擎 / OrkasOpen strip 名单)。
+
+### 批次 6(设置页结构 + 通知策略,追加) — ✅ 已决议
+- **设置页 4 tabs**(用户指定):
+ | Tab | i18n key | 内容 |
+ |---|---|---|
+ | 账号 | `settings.tab.account` | Account 卡片(登录 / 退出 / profile) |
+ | 数据 | `settings.tab.data` | **Sync 卡片**(含状态 / 进度 / 配额 / 冲突 / 隐私说明)+ Data root + Clear all conversations |
+ | 通用 | `settings.tab.general` | Language / Commander avatar / Local Execution / Metacognition |
+ | 配置 | `settings.tab.credentials` (en="Credentials") | Models & credentials + Search API Key + Image API Key |
+- **Sync 归"数据"tab**:sync 是云端数据管理;与本地 data root / clear-convs 一起归口,用户不用在多处找"我的数据在哪、占多大、怎么清"。
+- **完全去 toast**。所有需用户知晓的事件靠:
+ 1. 侧边栏 settings 按钮右上角圆点(红 = error / login_required / quota_full;橙 = warning / quota_near_full / conflict_pending / 连续失败 ≥ 3 次)
+ 2. 进入设置页时,对应 tab 标题也带圆点(导航到具体 tab)
+ 3. 卡片内部展开详情
+- **连续失败阈值 N=3**(单次网络抖动不告警)。
+- **v1 不做 in-flow ribbon**(编辑器内联提示);接受"用户被覆盖时当下不知道"的弱点,靠圆点 + 进设置看到。v1.x 视反馈再决。
+- **OrkasOpen 看到 3 tabs**:账号 tab 整体 strip(与 `#settings-account-group` 同进退),数据 tab 内 sync 卡片 strip(gate `typeof window.orkas?.sync !== 'undefined'`),OrkasOpen 数据 tab 只剩 data root + clear convs。
+
+### 批次 4(用户体验:配额 + 冲突 UX) — ✅ 已决议
+- **默认配额 5 GB / user**。Why:附件全同步场景下 1 GB 易爆、10 GB+ COS 成本走高;5 GB 覆盖 80% 用户。**未来按会员等级分档**——Orkas DB 表 `user_sync_usage` 的 `quota` 字段 per-row 可配,配额来源链路:默认值(profile 配置)→ 会员等级表(v1.x 加) → user override(管理员后台)。
+- **超配额规则按 size delta 判定**(不是粗暴拒所有 push):
+ - manifest commit 计算 push 集的 net size delta(新增 - 删除 - 修改前后差)
+ - `delta ≤ 0` → **允许**(删除 / 等大修改 / 缩小修改都放行;用户腾空间的路径不能被堵)
+ - `delta > 0 && used + delta > quota` → **拒绝**,返回 `{ok:false, error:"QUOTA_EXCEEDED", delta, used, quota}`
+ - **pull 永远允许**(不增加占用;断了用户进入"什么都看不到"死锁)
+ - **manifest 自身大小**计入 used,但 tombstones 不计(30 天后自清)
+- **配额满时 UI 引导**:设置页 sync 卡片满额时展开「占用 Top 10」列表(大到小,显示 path 摘要 + size + mtime),每行带「删除」按钮 → 走正常 delete + 墓碑流程。**v1 必做**——否则用户没释放路径。
+- **冲突 UX = C + 可恢复**(用户提出的闭环):
+ - 写冲突时本机旧版本写入 `local/sync/conflicts/<ts>-<rel_path>`
+ - **toast 提示**:"`agent.json` 已被另一台设备的修改覆盖。[查看历史]"
+ - 设置页 sync 卡片下有可折叠「冲突记录」列表(最近 30 天),每条带两个按钮:
+ - **「恢复此版本」**:把 conflicts/ 里的旧内容覆盖回 cloud/ 路径 + `_v+1` + 标 dirty → 下次 sync 这版本胜出推到其他设备。点击前弹二次确认:"这会撤销你在本机自冲突以来的修改,并把旧版本推到其他设备,确认?"
+ - **「忽略并删除留底」**:清掉 conflicts/ 那条记录
+ - **conflicts/ 默认保留 30 天**,改成 profile 配置项 `sync_conflict_retention_days`(批次 7 修订);后续按会员等级可调到 90 / 180 / 365 天;到期自动清;用户也可在列表里手动清。
+
+### 批次 3(隐私 / 加密) — ✅ 已决议
+- **v1 不做应用层加密**。安全模型 = **STS + private bucket + COS SSE-COS(免费透明)**。Why:STS scope 锁死已挡住绝大多数现实威胁(外部攻击者 / 其他用户 / 网络中间人);应用层加密的增量只在「COS / Orkas 内部威胁 + 执法调取」,v1 不投这块工程复杂度(密钥管理占 80% 成本)。
+- **取消 codec.ts 抽象层**:无 v1 实现 → 抽象阅读成本反成负担。manifest 直接存**明文 sha256**,便于校验 / 去重 / 排障。v2 真要上 E2EE 时单独立项做(届时会破坏性变更数据格式,已写入 §10 风险)。
+- **UI 设置页 sync 卡片**显示一行说明:"数据通过加密通道(HTTPS)上传到私有云存储,仅你的账号可访问"。**不写**"端到端加密"——诚实表达能力边界。
+
+### 批次 2(同步范围) — ✅ 已决议
+- **vector.db 不同步**(方案 B)。云端只放 `contexts/` 源文件;各设备本地 `kb_indexer.reconcile` 自行 rebuild 索引。**必须改 PC/CLAUDE.md §4 constraint 5**(当前规则相反)。Why:改一篇文档触发几百 MB db 全量上传不可持续;索引按定义可重建。
+- **附件三家全同步**:`chat_attachments/`、`chat_artifacts/`、`saved_apps/` 均纳入 v1 同步集。无 size 阈值、无懒拉。Why:体验一致性优先,"chats 同步了但附件缺"会让对话残缺。**代价**:单条 4K 视频可能 GB 级,几台设备并发上传会快速吃配额——批次 4 决配额时要正视这点;engine 需支持 COS 分块上传(`cos-nodejs-sdk-v5` SDK 原生支持,对 > 5MB 文件用 multipart)。
+- **workspace.json 不同步**(沿用 PC/CLAUDE.md §4 既有归类)。Why:路径在异机无效;用户对"在哪台机器干什么"有直觉边界。
+
+### 术语澄清(贯穿全文)
+- **OAuth `user_id`**:登录后 server 返回,写入 `<local_uid>/local/config/account.json::user_id`,**COS 前缀就用它**。
+- **本地 `uid`**:8-digit 数字、每台机器独立生成(`features/users.ts::initActiveUser`),仅用于本地容器路径 `<container>/data/<uid>/`,不上云、不做 COS scope。
+- **device_id**:sync engine 首次启动时生成的 UUID,存 `<local_uid>/local/sync/state.json::device_id`,仅用于 manifest 里 `last_writer_device_id` 排障字段(不是安全凭据,与 account.json 无关)。
+
+**Why**:同一 OAuth 账号在不同机器上有不同本地 `uid`,云端必须按 OAuth `user_id` 聚合数据,否则跨机看不到同一份云端内容。
+
+---
+
+## 1. Motivation
+
+用户在登录态下使用 Orkas,希望本地数据(聊天、agent/skill 自定义、KB 源文件、preferences 等)在多设备间自动同步:
+- 第二台设备登录同一账号 → 自动拉取已有数据
+- 在 A 设备修改 → B 设备下次启动或运行中能看到
+- 设置页有「立即同步」按钮 + 上次同步时间
+- 显示当前云端占用,为后续配额限制铺路
+
+现状利好:
+- `<uid>/cloud/` vs `<uid>/local/` 切分早已落到 PC/CLAUDE.md §4,「哪些该同步」结构上已经回答
+- Server 端 COS(`qcloud_cos` + private bucket + `temp/` lifecycle)已就绪
+- `marketplace_reconcile.ts` 提供了"manifest → 本地状态"心智模型可复用
+- IPC、启动 hook、settings 页面 Data 段位均有干净的扩展点
+
+## 2. 设计目标 / 非目标
+
+**目标**
+- 跨设备最终一致:所有 `cloud/` 下数据可在合理时间内对齐
+- 私有性:bucket 全 private;STS scope 按 OAuth `user_id` 锁死;启用 COS SSE-COS;`session_id` / API key 永不上云
+- 频控 + 实时兼顾:按域 debounce + 退出/进入后台强制 flush
+- 启动主动同步、运行中按需 push、配额可观察
+- OrkasOpen 构建中**整套 sync 必须被 strip 掉**(与 `features/account/` 同进退,遵 PC/CLAUDE.md §4 + §11 strip-rules 约定)
+
+**非目标(v1 不做)**
+- 应用层加密(含 codec 抽象层;v2 真做 E2EE 时单独立项)
+- 实时多端协作(v1 最终一致 + LWW + 提示,不做 CRDT)
+- 按域选择性同步 UI(数据模型留位,UI v2)
+- 付费配额 / 配额升级
+
+## 3. Components
+
+### 3.1 COS 端布局
+
+单一 private bucket,按 **OAuth `user_id`** 前缀强隔离(不是本地 uid,原因见 §0 术语):
+
+```
+orkas-user-data/<oauth_user_id>/
+ manifest.json # 真值索引(见 §4.1)
+ cloud/chats/<cid>.jsonl
+ cloud/chats/<cid>/{members,state,plan,visibility/}
+ cloud/chats/{skill,agent}/<id>/chat.jsonl
+ cloud/chat_attachments/<cid>/<file>
+ cloud/chat_artifacts/<cid>/<artifactId>/<files...>
+ cloud/saved_apps/<appId>/<files...>
+ cloud/sessions/<sid>.jsonl
+ cloud/contexts/... # KB 源文件;vector.db 策略待批次 2 决(§7.2,CLAUDE.md §4 当前规则与方案有冲突)
+ cloud/memory/{MEMORY.md, USER.md}
+ cloud/agents/<aid>/{agent.json, meta/, skills/}
+ cloud/skills/<sid>/...
+ cloud/projects/<pid>/{project.json, bindings.json}
+ cloud/marketplace/installs.json
+ cloud/config/{preferences.json, component-enabled.json}
+ tombstones/<rel_path> # 删除墓碑,30 天后清理
+```
+
+- pretty-path 镜像本地 `cloud/` 一对一(便于排障,不做 content-addressed dedup)
+- ACL:bucket 全 private;对象 inherit
+- Bucket lifecycle:`tombstones/` 30 天自动清;老版本对象不保留多版本(v1 不做时间机器)
+- COS server-side encryption 启用(free)
+
+### 3.2 本地端布局(machine-private,不上云)
+
+```
+<container>/data/<local_uid>/local/sync/
+ index.json # 上次同步成功时的快照:{rel_path: {sha256, size, mtime_ms, _v}}
+ state.json # {device_id, last_sync_ts, last_pulled_generation, in_progress, pending_uploads[]}
+ conflicts/<ts>-<rel_path> # 被覆盖的可变 JSON 整文件留底
+ conflicts/<ts>-<rel_path>.jsonl # append-only 同 id 编辑冲突,仅含被覆盖那条 message(批次 7 决议)
+ preferences.json # 按域开关(v1 仅初始化默认值,UI v2 加)
+```
+
+`device_id` 在首次启动 sync engine 时生成(UUID v4),写入 state.json 后不变;用于 manifest `last_writer_device_id` 字段,不参与鉴权。
+
+### 3.3 模块拆分
+
+**PC 端(新增 `PC/src/main/features/sync/`)**
+- `engine.ts` — 调度、debounce 表、startup/quit hook、运行中 dirty 事件订阅
+- `manifest.ts` — manifest 拉取 / diff / 三集计算(pull/push/delete)
+- `transport.ts` — STS 获取 + COS SDK 调用封装(PUT/GET/DELETE/HEAD;大文件走 multipart)
+- `local_index.ts` — `local/sync/index.json` 维护、本地文件 sha 缓存
+- `dirty_bus.ts` — 各 feature 写入后 emit 的事件总线,按域 debounce
+- `merge/` — 按数据形态划分的冲突合并器:`jsonl_append.ts`、`mutable_json.ts`、`binary.ts`
+
+**Server 端(新增 `Server/api/sync.py` + `Server/biz/sync/`)**
+- 所有 sync 端点都过现有 `utils/auth.py::check_login`(`user_id` + `session_id` 头部,SessionMgr 滑动续期)。**绝不接受请求参数里传入的 `user_id`**——scope 推导只能来自校验后的 session。
+- `POST /sync/sts` — 颁发 1h COS 临时凭据,scope 锁死 `<oauth_user_id>/*`
+- `POST /sync/manifest/commit` — 唯一的 manifest 写入口;CAS(按 generation);同时算账更新 usage
+- `GET /sync/usage` — 返回 `{used_bytes, quota_bytes, last_sync_ts}`
+- `Server/biz/sync/quota.py` — 配额计账与软硬阈值判定
+- DB 新表 `user_sync_usage(user_id PK, bytes BIGINT, quota BIGINT, updated_at)`(PK 用 OAuth `user_id`,与现有 account 体系对齐)
+
+### 3.4 IPC 接口(新增)
+
+| Channel | 类型 | Payload | 返回/事件 |
+|---|---|---|---|
+| `sync.runNow` | invoke | `{}` | `{ok, error}`;进度通过 push 事件 |
+| `sync.status` | invoke | `{}` | `{state, last_sync_ts, last_error, progress}` |
+| `sync.usage` | invoke | `{}` | `{used_bytes, quota_bytes}` |
+| `sync.progress` | push event | — | `{state, current, total, current_path}` |
+| `sync.subscribeStatus` | stream | `{}` | yields status changes |
+
+新 features → IPC 的方向遵守 PC/CLAUDE.md §3(ipc → features,不反向)。
+
+## 4. 关键机制
+
+### 4.1 Manifest 格式
+
+```jsonc
+{
+ "manifest_v": 1,
+ "generation": 42, // 单调递增,CAS 用
+ "last_writer_device_id": "...",
+ "last_writer_ts_ms": 1731600000000,
+ "entries": {
+ "cloud/chats/abc.jsonl": {
+ "sha256": "...", // 明文内容的 sha(不是压缩后字节)
+ "size": 12345, // **实际存到 COS 的字节数**——压了就是压缩后;配额按此累加(批次 8 决议)
+ "mtime_ms": 1731599000000,
+ "_v": 7, // 文件级单调版本(每次本地写入 +1)
+ "schema_v": 1,
+ "compressed": "gzip" // null | "gzip"(批次 8 决议)
+ },
+ "...": { ... }
+ },
+ "tombstones": {
+ "cloud/chats/deleted.jsonl": { "deleted_at_ms": 1731500000000, "_v": 9 }
+ }
+}
+```
+
+**generation 作为主时序**(不信任客户端 mtime;mtime 仅作辅助二级排序)。
+
+### 4.2 单次 sync 流程
+
+```
+1. GET manifest.json (带 If-None-Match / ETag),未变跳到 5
+2. diff(remote.entries, local_index)
+ ├─ need_pull: remote 新 / 本地缺
+ ├─ need_push: 本地新 / remote 缺
+ ├─ need_delete_local: tombstones 中有,本地存在
+ └─ need_delete_remote: 本地有删除标记,remote 仍存在
+3. 串行 delete local(清本地被墓碑标记的文件)
+4. 并发 pull → 并发 push(受 max-concurrency 限制,单文件失败独立重试)
+5. POST /sync/manifest/commit (带 base_generation = 拉到的 generation)
+ ├─ 成功 → 写 local/sync/index.json + state.json
+ └─ CAS 冲突 → goto 1,重试 1 次后退避到下个周期
+```
+
+### 4.3 冲突解决(按数据形态分类)
+
+| 数据形态 | 策略 |
+|---|---|
+| `chats/*.jsonl`、`sessions/*.jsonl`(append-only) | 新 id 双侧追加直接 union;**同 id 双侧编辑 = 冲突**(批次 7 决议):较晚 mtime/_v 胜出,败者那一条 message 写入 `local/sync/conflicts/<ts>-<rel_path>.jsonl`(仅含被覆盖那条),同样进设置页"冲突记录"列表 + 「恢复此版本」按钮 |
+| `preferences.json` / `agent.json` / `project.json`(可变 JSON) | 文件内嵌 `_v`;双侧都 > base = 冲突,LWW(_v 大者胜,并列时 generation 大者),老版本写入 `local/sync/conflicts/<ts>-<rel_path>` 留底 30 天,toast + 设置页「冲突记录」列表(含「恢复此版本」按钮 → 把 conflicts/ 内容覆盖回去 + `_v+1` + 标 dirty,二次确认)|
+| 附件(二进制) | 按 sha256 内容寻址,永不冲突(同 path 不同 sha 视作可变 JSON 同策略) |
+| `marketplace/installs.json` | 视作可变 JSON;本地 reconcile 再消费 |
+
+### 4.4 Schema 防降级
+
+每个可变 JSON 顶层带 `_schema_v`。pull 阶段若 `remote.schema_v > local_known_v` → **拒绝覆盖本地**,UI 提示「其他设备运行的版本较新,请升级」。push 阶段不会发生(本设备只能写自己已知的 schema)。
+
+### 4.5 频控
+
+- **运行中**:feature 写入后 emit `dirty(domain, rel_path)` → `dirty_bus` 按 domain 启动 debounce 计时器
+- **域级 debounce 默认**:
+ - `preferences` 2s
+ - `chats` / `sessions` / `memory` 5s
+ - `agents` / `skills` / `projects` 10s
+ - `chat_artifacts` / `saved_apps` 10s(小 bundle,与 agents 同档)
+ - `chat_attachments` 30s(大文件域,含视频;分块上传单独并发上限)
+ - `contexts`(KB 源) 15s
+- **到点合并**:所有过期 timer 合并成一次 sync pass(同一窗口内多次 dirty 只触发一次 sync)
+- **强制 flush 触发**:app `before-quit`、用户点「立即同步」、startup
+- **全局 floor**:两次自动 sync 间至少 30s(防异常风暴)
+
+### 4.6 启动同步 hook
+
+`PC/src/main/index.ts` 在现有 `marketplaceReconcile` 之后追加:
+
+```ts
+setImmediate(() => syncFeature.syncNow(uid).catch(err => logger.error('sync.startup', err)));
+```
+
+fire-and-forget,与现有 KB/search/marketplace reconcile 同列。UI 通过 push 事件感知进度。
+
+### 4.7 COS 访问通道:STS 直传(批次 1 已决议)
+
+- 新依赖:`cos-nodejs-sdk-v5`(已确认加入 PC/package.json allow-list)
+- 流程:PC → `POST /sync/sts`(带 `user_id` + `session_id` 头部,走现有 `check_login`)→ Server 从 SessionMgr 校验得到的 `user_id` 构造 scope 严格锁死 `<oauth_user_id>/*` 的临时凭据(1h)→ PC 用 SDK 直接 PUT/GET/DELETE
+- **安全核心**:scope 来源**只能**是 SessionMgr 校验后的 `user_id`,**禁止**信任请求参数里传入的 uid / user_id
+- Server 只保留三件事:发 STS、守 manifest CAS commit、配额计账
+- manifest.json 的 PUT/DELETE **必须**走 Server 端点(保证 CAS 与计账的原子性),其余对象 PC 直发
+- **marketplace 上传维持 server-proxy**(批次 1 已决议;与 sync 通道分离)
+
+### 4.8 配额(批次 4 已决议)
+
+- DB:`user_sync_usage(user_id PK, bytes BIGINT, quota BIGINT, updated_at)`;PK 是 OAuth `user_id`
+- 默认 `quota = 5 GB`(从 profile `sync_quota_default_bytes` 读,可 per-row override,未来对接会员等级)
+- 每次 `commit` 计算 push 集的 net size delta = `sum(add) - sum(del) - sum(modify_size_diff)`
+- **判定规则**(批次 4 决议):
+ - `delta ≤ 0` → 允许(删除 / 等大修改 / 缩小修改放行)
+ - `delta > 0 && used + delta > quota` → 拒绝,返回 `{ok:false, error:"QUOTA_EXCEEDED", delta, used, quota}`
+ - `0 < delta && used + delta ≤ quota` → 允许并更新 `used`
+- **pull 永远允许**,不查配额
+- 软提醒 80% → manifest commit 成功响应附带 `warn: "QUOTA_NEAR_FULL"`,PC 端进侧边栏 dot(无 toast,批次 6 决议)
+- manifest.json 自身大小计入 `used`;tombstones 不计(30 天后自清)
+- **`used` 和 entries 的 `size` 都按"实际存到 COS 的字节"算**(压缩后字节,不是明文大小)——批次 8 决议。Why:资源被限制的东西(COS 存储)应该按实际占用计;不耦合压缩策略;用户压缩率高的文件类型隐性"白嫖"是合理福利
+- 设置页:配额满时展开「占用 Top 10」列表 + 每行「删除」按钮(v1 必做)
+
+### 4.9 设置页 UI 重构(4 tabs,批次 6 决议)
+
+**整体改造**:把现有滚动式 `#panel-settings` 拆成 4 tab 容器。tab 切换视觉复用 `.marketplace-tabs` / `.marketplace-tab` 原语(`index.html:368` 已有;遵 PC/CLAUDE.md 「Reuse UI components」)。
+
+**4 tabs**(中文标签按用户指定顺序):
+
+| Tab | i18n key | 包含的卡片(已有 + 新) |
+|---|---|---|
+| 账号 | `settings.tab.account` | Account(既有 `#settings-account-group`) |
+| 数据 | `settings.tab.data` | **Sync 卡片(新)** + Data root(既有)+ Clear all conversations(既有)|
+| 通用 | `settings.tab.general` | Language / Commander avatar / Local Execution / Metacognition(全部既有) |
+| 配置 | `settings.tab.credentials` (en="Credentials") | Models & credentials + Search API Key + Image API Key(既有 sections 合并) |
+
+**触点**:
+- `index.html#panel-settings`:包 `.settings-tabs` + 4 个 `.settings-tab-pane`;现有 4 个 `.settings-section-head` 改造成 tab pane(账号 tab 内不需 section-head 因为只有一个卡片)
+- 新增 CSS:复用 `.marketplace-tabs` 配色 / 间距;新 `.has-dot::after` 圆点
+- `modules/settings.js`:tab 切换逻辑 + **按 tab 懒加载**(不要进设置页就刷全部状态——现 `loadSettings()` 并行刷 7+ 个状态是浪费)
+- i18n key 新增 `settings.tab.{account,data,general,credentials}`
+
+#### Sync 卡片内容(数据 tab 内部,从上到下)
+
+1. **整体状态徽章** + **上次同步时间**("5 分钟前",hover 显示绝对 UTC)+ **「立即同步」按钮**(loading 态由 `sync.progress` push 驱动)
+2. **配额条** `12.4 MB / 5 GB`(≥ 80% 黄、≥ 95% 红)
+3. **同步中实时刷新**:阶段(pull / push / commit)+ 进度(`上传 3/8 · 下载 1/5`)+ 当前文件路径(截断显示)
+4. **异常态展开**:
+ - error → 错误详情 + "查看日志"链接(打开 `data/logs/<today>.log`)
+ - quota_full → 「占用 Top 10」列表 + 每行「删除」(批次 4 决议)
+ - login_required → "重新登录" CTA
+5. **冲突记录**(可折叠面板,标题带计数 `冲突记录 (3)`):最近 30 天列表,每条 `时间 / path / [恢复此版本] [忽略]`(批次 4 决议)
+6. **隐私说明**:i18n key `settings.sync_privacy_note`,文案 "数据通过加密通道(HTTPS)上传到私有云存储,仅你的账号可访问"(批次 3 决议,**不写"端到端加密"**)
+
+#### 通知策略(批次 6 决议:完全去 toast)
+
+事件 → 圆点级别映射:
+
+| 事件 | 级别 | 显示在 |
+|---|---|---|
+| 同步中 / 成功 / 首次失败 | 无 | 卡片内 |
+| 同步连续失败 ≥ 3 次 | 橙 | 侧边栏 dot + 数据 tab dot |
+| 网络断开 | 无 | 卡片内 "⏸ 离线" |
+| 登录失效 | 红 | 侧边栏 dot + 账号 tab dot |
+| 配额 ≥ 80% | 橙 | 侧边栏 dot + 数据 tab dot |
+| 配额满(push 拒)| 红 | 侧边栏 dot + 数据 tab dot |
+| 新冲突写入 conflicts/ | 橙 | 侧边栏 dot + 数据 tab dot |
+
+实施:新 module `modules/sidebar-status.js`——订阅 `sync.subscribeStatus` + `account:changed` push,聚合后决定侧边栏 settings 按钮的 dot 颜色(红 > 橙 > 无)。
+
+**v1 已知弱点**:用户在 agent / project 编辑页改了内容、被另一设备覆盖——当下没 toast 提示,要等他看到圆点进设置才发现。v1 接受这个 trade-off;v1.x 视反馈再加内联 ribbon「此版本已被其他设备覆盖 · [还原]」。
+
+#### OrkasOpen 行为
+
+- **账号 tab 整体 strip**(与 `#settings-account-group` 同进退)
+- **数据 tab 内 sync 卡片 strip**(gate `typeof window.orkas?.sync !== 'undefined'`)
+- OrkasOpen 用户看到 **3 tabs**:数据(只剩 data root + clear convs)/ 通用 / 配置
+- `sidebar-status.js` 在 OrkasOpen 下整体无效(永远不 dot),可一并 strip
+
+#### 同步触发时机(汇总,批次 6 补全)
+
+| # | 时机 | 行为 |
+|---|---|---|
+| 1 | **应用启动** | `setImmediate` 触发首次 sync(pull-first),与 marketplace_reconcile 同列 |
+| 2 | **运行中写入** | features emit `dirty(domain, rel_path)` → 按域 debounce → 到点合并;两次自动 sync 间至少 30s |
+| 3 | **应用退出** `before-quit` | 强制 flush pending |
+| 4 | **用户点「立即同步」** | 立即触发 full sync,跳过 debounce |
+| 5 | **登入 OAuth** | init engine + 首次 full pull(新设备场景) |
+| 6 | **登出 / session 失效** | teardown engine,pending 保留 |
+| 7 | **切 OAuth user_id** | teardown 旧 → 清 `local/sync/` → 按新 user 重建 |
+| 8 | **从后台回前台**(browserWindow `focus` / `activate`) | 距上次成功 sync > 5min 时触发一次轻量 sync(HEAD manifest,generation 变了才走完整 sync) |
+| 9 | **网络恢复**(`navigator.onLine = true`) | 重试 pending_uploads(指数退避:30s / 1min / 2min / 5min 封顶) |
+| 10 | **配额释放后**(用户删大文件) | 通过 #2 dirty 路径自然重试(删除的 commit 刷新 used,下个 push 不再 QUOTA_EXCEEDED)|
+
+### 4.10 删除 / 登录态变化
+
+- 任何 `cloud/` 下删除操作必须经 sync engine 记墓碑(features 层直接 unlink 是 bug;要在 §6 里硬约束)
+- **登录/登出/账号切换**——监听 `account:changed` push 事件:
+ - 登入(首次拿到 OAuth `user_id`):初始化 sync engine、生成或读取 `device_id`、调度首次 full pull
+ - 登出 / session 失效:立即 teardown engine、停所有 in-flight、`local/sync/state.json` 保留(便于下次同账号登入续传),但 `pending_uploads` 不再触发
+ - 切到另一个 OAuth `user_id`:先 teardown 旧 engine → 清 `local/sync/`(不同 OAuth user 的本地索引不能复用)→ 按新 user_id 初始化
+- **本地切 active uid**(`features/users.ts::activateUser` 切 8-digit uid,常见场景:同机两个本地 profile):teardown 当前 engine,新 uid 启动后再走「初始化 or 续传」分支
+- **未登录态下不启动 sync**(无 OAuth user_id 没有云端 scope;UI 侧 sync 卡片显示"登录以启用",登录后再启)
+
+### 4.11 传输优化与增量同步(批次 8 决议)
+
+#### 压缩(单文件 gzip,BYO encoding 模式)
+
+- **谁压**:PC 端 upload 前自己 gzip,download 后自己解;COS 完全不感知压缩、永远不解压
+- **协议层**:上传**不设** `Content-Encoding: gzip` 头(否则 cos-nodejs-sdk-v5 会自动解压,PC 端拿不到压缩字节);Content-Type 设 `application/gzip`;附加自定义元数据 `x-cos-meta-compressed: gzip` 给 COS 控制台一个可见提示
+- **白名单**(按扩展名匹配):`.jsonl`、`.json`、`.md`、`.txt`、`.csv`、`.log`
+- **大小阈值**:明文 > 4 KB 才压(更小的压缩 metadata 开销不划算)
+- **黑名单**(永不压):`.jpg / .jpeg / .png / .webp / .gif / .mp4 / .webm / .mov / .pdf / .docx / .xlsx / .pptx / .zip / .gz / .br`
+- **sha256 算明文**(跨设备一致性可靠;gzip 输出受压缩级别 / 库版本影响不完全确定)
+- **`size` 算压缩后字节**(COS 实际占用,与配额对齐 —— 批次 8 决议)
+- **路径不加 `.gz` 后缀**(COS path 与本地 rel_path 一对一镜像,压缩状态由 manifest `compressed` 字段标)
+
+#### 不做 bundle 压缩
+不把目录打 zip 上传(如把整个 `agents/<aid>/` 打包)。Why:破坏 manifest per-file diff 模型——改一个文件要重打整 bundle 重传,增量同步退化成 bundle 级。
+
+#### 大文件 multipart 上传 + 续传
+- > 5 MB 文件自动走 cos-nodejs-sdk-v5 的 multipart API(SDK 内置)
+- **续传状态**进 `local/sync/state.json::pending_uploads[]`,每条 `{rel_path, sha256, upload_id, part_etags[], completed_parts, total_parts}`
+- 中断(网络 / 应用退出 / 配额暂时满)→ 下次 sync 从 `completed_parts` 之后继续;超过 7 天的 upload_id 视作失效,从头来过
+- 并发:chat_attachments 域单独限并发 2(避免一台机器猛传堵住整个 sync pass),其他域并发 5
+
+#### 批量操作
+- **删除**走 COS `DeleteMultipleObjects`,每批 ≤ 1000 个对象(COS API 上限)
+- 多文件 push 用 SDK 内置 sliced upload,复用 HTTPS 连接
+
+#### Rename 优化(v1 必做)
+- `local_index.ts` 同时维护 `path → entry` 和 `sha → [paths]` 两个索引
+- diff 阶段:
+ - `need_pull` 文件的 sha 已存在本地另一 path → 本地 `fs.copyFile` 即可,**不下载**
+ - `need_push` 文件的 sha 已存在远端另一 path → 调 `PutObjectCopy`(COS 服务端内部 copy,**不消耗 PC 上下行带宽**)+ 之后正常 delete old
+- 典型场景:用户重命名 agent / 移动 contexts 文档
+
+#### 不做 byte-level / chunk-level dedup
+- rsync 风格 rolling hash 实现复杂、COS 不原生支持、对小文件无收益,业界(Dropbox / Obsidian / OneDrive)也都不暴露
+- 整文件级粒度 + multipart 续传 + rename 优化 = 已经覆盖 v1 需要的场景
+
+#### 增量同步分三层(汇总)
+
+| 层 | 机制 | 何时跳过传输 |
+|---|---|---|
+| **L1 manifest 级** | `GET manifest.json` 带 `If-None-Match: <last_etag>` | 304 → 跳过整次 sync |
+| **L2 文件级** | manifest.entries 与 local_index 的 sha 对比 | sha 相同 → 跳过该文件传输 |
+| **L3 multipart 级** | 大文件分块上传 + 续传状态 | 已完成的 part 跳过 |
+
+#### 活跃 jsonl 整文件重传(已知开销)
+- 一条 chat jsonl 每加一条 message → 整文件 dirty → 整文件重传
+- 缓解:域级 debounce(chats 5s)把窗口内多次写并成一次传
+- v1 接受这个开销;写入 §10 风险,v1.x 看带宽用量再决定要不要做 jsonl 分片(按 message_id 范围分文件)
+
+## 5. 同步集合(明确清单)
+
+**✅ 同步(`cloud/` 下,批次 2 决议)**
+- chats(jsonl + members/state/plan + visibility/)
+- chats/{skill,agent}/<id>/chat.jsonl(编辑会话)
+- chat_attachments(全量同步,含视频 / PDF 等大文件;> 5MB 走 COS multipart 上传)
+- chat_artifacts(全量同步,硬上限 ≤ 1MB / bundle ≤ 20 文件,体量受 PC/CLAUDE.md §5 约束)
+- saved_apps(全量同步)
+- sessions
+- contexts **仅源文件**(vector.db 不同步,各设备本地 rebuild via `kb_indexer.reconcile`)
+- memory/{MEMORY.md, USER.md}
+- agents(含 meta/ + skills/,整目录)
+- skills、projects
+- marketplace/installs.json(仅清单,本地 reconcile 拉真包)
+- config/preferences.json、config/component-enabled.json
+
+**❌ 不同步(`local/` 下)**
+- config/account.json(OAuth `user_id` + `session_id` + `user_info`,machine-private)
+- config/auth-profiles.json(LLM API keys)
+- config/permissions.json、reflection-state.json、web-search-cache.json
+- biz/marketplace.json(24h TTL 缓存)
+- local/marketplace/{agents,skills}/(reconcile 时按清单从 COS 拉)
+- cache/<bucket>/(user-clearable 缓存伞)
+- search/(派生索引)
+- file_cache/、tool-results/(按 PC/CLAUDE.md §4 constraint 6 即将迁入 cache/)
+- workspace.json(机器私有,路径异机无效;批次 2 已决议)
+- test/(dev-only LLM 归档)
+- **顶层** `users.json`、`logs/`(machine-private,与 OAuth 账号无关)
+
+**`cloud/` 内 v1 跳过同步**:vector.db(只同步 `contexts/` 源文件)
+
+## 6. Change list
+
+### PC 端
+- `PC/src/main/features/sync/` 新建(engine / manifest / transport / codec / local_index / dirty_bus / merge/)
+- `PC/src/main/index.ts` 增加 startup hook + before-quit flush
+- `PC/src/main/ipc/index.ts` 注册 `sync.runNow` / `sync.status` / `sync.usage` / stream
+- `PC/src/main/features/marketplace.ts::apiBase()` 复用(同步 API 也通过它)
+- `PC/src/main/features/users.ts` 切账号路径调用 `syncFeature.teardown()`
+- 各 cloud 写入方 feature(chats、agents、skills、projects、preferences)写完后 emit `dirty()`:
+ - `features/chats/*` 收尾处
+ - `features/agents.ts` / `features/skills.ts`
+ - `features/projects/*`
+ - `features/app_config.ts`(preferences 写入处)
+ - `features/marketplace.ts`(installs.json 写入处)
+- 各 cloud 删除方 feature 改走 `syncFeature.markDeleted(rel_path)` 而不是直接 unlink
+- `PC/src/renderer/modules/settings.js` **重构成 4 tab**(账号 / 数据 / 通用 / 配置),按 tab 懒加载状态;数据 tab 内新增 sync 卡片(gate `typeof window.orkas?.sync !== 'undefined'`)
+- `PC/src/renderer/index.html#panel-settings` 整体改造:`.settings-tabs` + 4 个 `.settings-tab-pane`
+- `PC/src/renderer/styles.css`(或对应文件):复用 `.marketplace-tabs` 视觉,新增 `.has-dot::after` 圆点
+- 新模块 `PC/src/renderer/modules/sidebar-status.js`:聚合 sync + account 状态决定侧边栏 dot
+- `PC/src/renderer/locales/{zh,en}.json` 加 sync 相关字串(key 前缀 `settings.sync_*`)+ 4 个 tab 标签 key(`settings.tab.{account,data,general,credentials}`)
+- `PC/package.json` 新增 `cos-nodejs-sdk-v5`(批次 1 已确认)
+- `features/account/` 订阅点:监听 OAuth 登录/登出/切账号,分别触发 sync engine 的 init / teardown / reset
+- `OpenSource/SyncCode/strip-rules.json` 增加整套 sync 的剥离规则(见 §9)
+
+### Server 端
+- `Server/api/sync.py` 新建(sts / manifest commit / usage 三端点)
+- `Server/biz/sync/quota.py` 新建(计账 + 阈值)
+- `Server/biz/sync/sts.py` 新建(COS STS 临时凭据签发,scope 强约束)
+- `Server/utils/store/file_store.py` 复用 / 扩展(不动现有接口)
+- DB migration:新表 `user_sync_usage`
+- `Server/conf/cn.conf` 增加 `sync_quota_default_bytes`、`sync_sts_duration_seconds`、`sync_conflict_retention_days`(批次 7 决议)
+
+### Profile / 部署
+- COS bucket lifecycle 规则:`tombstones/*` 30d 过期
+- COS bucket policy:默认 private(已有)
+- CAM 子账号 / 角色:sync STS 所用主账号需有 sts:GetFederationToken 权限
+
+## 7. 待决策项(按批次推进)
+
+> ✅ = 已决议(见 §0 决议日志);🟡 = 当前 / 下一批;⚪ = 待批次。
+
+- ✅ **批次 1** — STS 直传 / 新依赖 / marketplace 通道分离(见 §0)
+- ✅ **批次 2** — vector.db 不同步 / 附件三家全同步 / workspace.json 不同步(见 §0)
+- ✅ **批次 3** — v1 不做应用层加密,靠 STS + private + SSE-COS;取消 codec 抽象;UI 加诚实隐私说明(见 §0)
+- ✅ **批次 4** — 配额 5 GB(按 size delta 判定)/ 配额满时 Top 10 释放 UI / 冲突 UX = toast + 历史列表 + 可恢复(见 §0)
+- 🟡 **批次 5 — 实施保障**
+ - 7.9 **冲突合并器单测**:jsonl append / mutable json 合并器是「文本处理 / 解析」类代码,按 PC/CLAUDE.md §9 "Hard rule for LLM-output text munging" 必须配 fixture 单测(set A 真实命中 + set B 似是而非不命中)。
+ - 7.10 **CLAUDE.md 同步**:本方案落地后需同步以下条目(见 §9),先确认表述。
+
+## 8. Verification
+
+实施后需通过:
+- **单测**:
+ - `merge/jsonl_append.ts` — 双侧追加新 id 消息(union)、**双侧改同 id(冲突 → 留底 + 较晚胜出)**、空文件 / 末行无换行 fixture(批次 7 决议要求覆盖留底分支)
+ - `merge/mutable_json.ts` — 双侧 _v 同 / 异、schema_v 倒置拒绝覆盖、墓碑场景
+ - `manifest.ts` — diff 三集计算、CAS 冲突重试、**rename 检测**(sha 反查命中本地 copy / 远端 PutObjectCopy 分支,批次 8)
+ - `transport.ts` — gzip 白名单 / 阈值 / 黑名单决策、压缩字节与明文 sha 一致性(批次 8)
+ - `dirty_bus.ts` — debounce 合并、强制 flush 优先
+- **集成测**:
+ - 起两个临时数据根(模拟 A/B 设备),共享同一伪 COS(local fs mock)
+ - 场景:单边写入 → 另一边 pull、双边并发 → CAS 冲突、删除 → 墓碑 → 另一边删本地
+ - 配额硬阻断场景
+- **手工验证**:
+ - 真实双设备 Mac + Win 同账号登录,跑一遍:聊天、改 agent、删聊天、配额接近上限
+ - 验证 `session_id` / API key / `account.json` 内容**永远没**出现在云端任何对象里(list bucket + grep STS 直传日志)
+ - OrkasOpen 构建:sync 模块整体被 strip 干净(不存在 `features/sync/`、preload 无 `sync` 命名空间、settings 页无 sync 卡片)
+- **回归**:
+ - 现有 KB reconcile、marketplace reconcile、search reconcile 行为不变
+ - dev 包与 packaged 包行为一致(CLAUDE.md「OrkasOpen has no dev-vs-prod behavior split」)
+
+## 9. CLAUDE.md / strip-rules 同步项
+
+实施后需同步:
+
+### PC/CLAUDE.md
+- §1 npm allow-list 增加 `cos-nodejs-sdk-v5`
+- §4「数据同步域」修订:
+ - **COS 前缀 = OAuth `user_id`**(不是本地 8-digit `uid`);本地 `<container>/data/<uid>/cloud/` ↔ 云端 `orkas-user-data/<oauth_user_id>/cloud/` 一对一镜像
+ - vector.db 策略改写——**待批次 2 决议**:若决「不同步」,需明确撤销当前 constraint 5 的 "KB vector store is part of cloud sync",改成「只同步 `contexts/` 源文件,vector.db 每设备本地 rebuild via `kb_indexer.reconcile`」
+ - `cloud/` 下任何删除**必须**经 `syncFeature.markDeleted(rel_path)`,禁止 features 层直接 unlink(否则会被其他设备复活)
+- 新增「§N sync 引擎」一节:
+ - manifest 是云端真值,generation 单调;客户端 mtime 仅辅助
+ - `local/sync/` 结构 + 永不上云
+ - 按域 debounce 表(防止有人到处加 dirty 调用而不知道频控位置)
+ - schema_v 防降级语义
+ - device_id 在 sync engine 首启时生成,存 `state.json`,仅作排障字段
+- §9「Don't do」追加:禁止在 sync engine 外读写 manifest.json;禁止把 OAuth `user_id` 当作本地路径段;禁止用 8-digit 本地 uid 做 COS scope
+
+### Server/CLAUDE.md
+- §3 追加:`/sync/*` 全部端点必须经 `utils/auth.py::check_login`;STS scope **只能**从 SessionMgr 校验后的 `user_id` 推导,禁止信请求参数
+- `/sync/manifest/commit` 是 manifest 唯一写入口,CAS + 配额计账原子
+
+### OrkasOpen strip-rules(`OpenSource/SyncCode/strip-rules.json`)
+- 与 `features/account/` 同进退——整个 `features/sync/` 目录、`ipc/sync.ts`(若拆出)、`renderer/modules/sync*.js`、`renderer/modules/sidebar-status.js`、`renderer/locales/{zh,en}.json` 里 `settings.sync_*` 键、`#settings-sync-group` 块、`window.orkas.sync` 命名空间——全部加入 strip 名单
+- 数据 tab 内的 sync 卡片用 `typeof window.orkas?.sync !== 'undefined'` gate(与 `marketplace_dev` 的 `typeof openMarketplaceUpload === 'function'` 同模式),避免 sync strip 后还要手改 renderer
+- 账号 tab:与既有 `#settings-account-group` 的 strip 同步——账号 tab 整体在 OrkasOpen 不显示(4 tabs → 3 tabs);tab 切换 JS 要能优雅跳过被 strip 的 tab(不报错不空白)
+- 新依赖 `cos-nodejs-sdk-v5` 仅在主仓使用;OrkasOpen 不安装(package.json 同步流程会自然过滤)
+
+### 日志 / 遥测(PC/CLAUDE.md §10)
+- sync engine 使用 `createLogger('sync')` + 子 scope(`sync:engine` / `sync:transport` / `sync:manifest` / `sync:merge`)
+- 关键节点 `log.info`(startup 同步开始 / 单次 sync 起止 / 文件数 / 用时 ms)
+- 失败必 `log.warn`(可恢复,如网络抖动)或 `log.error`(不变量违例,如 CAS 反复冲突)
+- Umami 事件可记 `sync_started` / `sync_completed` / `sync_failed`(data 只放计数与耗时,**绝不**含 path / cid / 文件内容)
+
+## 10. 风险与未尽事项
+
+- **首登耗时**:新设备首次同步可能下载几百 MB ~ 数 GB 附件 + 本地 rebuild KB 索引;需要 UI 明确分段进度(聊天文本 / 附件 / KB rebuild)而非"卡住"假象
+- **附件大小爆炸(批次 2 已知风险)**:附件三家全同步,单条视频可能 GB 级。配额(批次 4)必须早设硬上限;engine 必须支持 multipart 续传、并对 chat_attachments 用更窄的并发(避免一台机器猛上传把整个 sync 堵住);超配额时 push 端点返回 `QUOTA_EXCEEDED`,UI 引导用户「删大附件」或「升级配额(未来)」
+- **CAS 雪崩**:极端场景多个设备同时频繁 commit → 退避策略要好;v1 简单线性退避 + 拉抖动
+- **活跃 jsonl 整文件重传**(批次 8 已知开销):当前没做 jsonl 尾部分片协议(COS 无原生 append),每次新消息整文件重传。靠域级 debounce(chats 5s)缓解。v1.x 若带宽问题严重,考虑按 message_id 范围分片(如 1000 条一片),新片不影响旧片
+- **压缩库版本漂移**:不同 Node 版本的 zlib 输出可能略有差异(同明文压出来字节级不同)→ sha 必须算明文(已锁),否则跨设备验证会假阳性。Node 自带 zlib 跨版本相对稳定,可接受
+- **device_id 与隐私**:manifest 暴露 `last_writer_device_id` 给同账号其他设备;这是同账号自己的设备,可接受,但不要把它写进日志/上报
+- **时区与"上次同步时间"显示**:用 UTC 存,渲染层按 OS locale 显示,沿用现有 i18n
+- **多 active user(CLAUDE.md 说"framework-ready but not yet shipped")**:v1 仍按单 active user 设计,但 sync engine 实例按 OAuth `user_id` 创建/销毁,避免后续重写
+- **session 过期 → 同步中断**:`/sync/sts` 返回 401 → engine 暂停、UI 提示重新登录、`pending_uploads` 保留待恢复
+- **本地 uid ↔ OAuth user_id 多对一**:同一 OAuth 账号在两台机器各有独立本地 uid;teardown 时清的是 `<local_uid>/local/sync/`,不会误删另一台
+- **未登录态写入**:登录前的本地修改在登入后能否一次性 push 上去——v1 行为是「能」(首次 sync 把当前 `cloud/` 内容当作待 push),但要在 UI 上明示「首次同步可能将本机数据视为云端真值」,避免新设备误用旧机操作
+- **v2 加密带破坏性变更(批次 3 决议遗留)**:若 v2 要上 E2EE,所有现存对象需重新加密 + manifest 字段扩 `cipher/iv`;老客户端拉到密文版本将无法解读。届时必须:(a) 锁老版本不能再写、(b) 服务端做全量重密迁移、(c) 提供"丢失密钥 = 丢失数据"的明示同意 UX。**v1 不预埋 codec 抽象的代价就是 v2 这一刀;预估收益(v1 简化)> 成本(v2 一次性迁移)**。
diff --git a/package-lock.json b/package-lock.json
index d708c2d4..c7836bf1 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -3195,6 +3195,39 @@
"node": ">= 14"
}
},
+ "node_modules/ajv": {
+ "version": "7.2.4",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-7.2.4.tgz",
+ "integrity": "sha512-nBeQgg/ZZA3u3SYxyaDvpvDtgZ/EZPF547ARgZBrG9Bhu1vKDwAIjtIf+sDtJUKa2zOcEbmRLBRSyMraS/Oy1A==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.1",
+ "json-schema-traverse": "^1.0.0",
+ "require-from-string": "^2.0.2",
+ "uri-js": "^4.2.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/ajv-formats": {
+ "version": "1.6.1",
+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-1.6.1.tgz",
+ "integrity": "sha512-4CjkH20If1lhR5CGtqkrVg3bbOtFEG80X9v6jDOIUhbzzbB+UzPBGy8GQhUNVZ0yvMHdMpawCOcy5ydGMsagGQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ajv": "^7.0.0"
+ },
+ "peerDependencies": {
+ "ajv": "^7.0.0"
+ },
+ "peerDependenciesMeta": {
+ "ajv": {
+ "optional": true
+ }
+ }
+ },
"node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
@@ -3226,6 +3259,24 @@
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
"license": "BSD-3-Clause"
},
+ "node_modules/asn1": {
+ "version": "0.2.6",
+ "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
+ "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": "~2.1.0"
+ }
+ },
+ "node_modules/assert-plus": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz",
+ "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8"
+ }
+ },
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -3253,6 +3304,21 @@
"tslib": "^2.4.0"
}
},
+ "node_modules/asynckit": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
+ "license": "MIT"
+ },
+ "node_modules/atomically": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/atomically/-/atomically-1.7.0.tgz",
+ "integrity": "sha512-Xcz9l0z7y9yQ9rdDaxlmaI4uJHf/T8g9hOEzJcsEqX2SjCj4J20uK7+ldkDHMbpJDK76wF7xEIgxc/vSlsfw5w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.12.0"
+ }
+ },
"node_modules/await-to-js": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/await-to-js/-/await-to-js-3.0.0.tgz",
@@ -3262,6 +3328,21 @@
"node": ">=6.0.0"
}
},
+ "node_modules/aws-sign2": {
+ "version": "0.7.0",
+ "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz",
+ "integrity": "sha512-08kcGqnYf/YmjoRhfxyu+CLxBjUtHLXLXX/vUfx9l2LYzG3c1m61nrpyFUZI6zeS+Li/wWMMidD9KgrqtGq3mA==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/aws4": {
+ "version": "1.13.2",
+ "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz",
+ "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==",
+ "license": "MIT"
+ },
"node_modules/base64-js": {
"version": "1.5.1",
"funding": [
@@ -3287,6 +3368,15 @@
"node": ">=10.0.0"
}
},
+ "node_modules/bcrypt-pbkdf": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
+ "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "tweetnacl": "^0.14.3"
+ }
+ },
"node_modules/better-sqlite3": {
"version": "12.9.0",
"hasInstallScript": true,
@@ -3401,6 +3491,12 @@
"node": ">=8"
}
},
+ "node_modules/caseless": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz",
+ "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==",
+ "license": "Apache-2.0"
+ },
"node_modules/chai": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
@@ -3449,6 +3545,55 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/combined-stream": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+ "license": "MIT",
+ "dependencies": {
+ "delayed-stream": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/conf": {
+ "version": "9.0.2",
+ "resolved": "https://registry.npmjs.org/conf/-/conf-9.0.2.tgz",
+ "integrity": "sha512-rLSiilO85qHgaTBIIHQpsv8z+NnVfZq3cKuYNCXN1AOqPzced0GWZEe/A517VldRLyQYXUMyV+vszavE2jSAqw==",
+ "license": "MIT",
+ "dependencies": {
+ "ajv": "^7.0.3",
+ "ajv-formats": "^1.5.1",
+ "atomically": "^1.7.0",
+ "debounce-fn": "^4.0.0",
+ "dot-prop": "^6.0.1",
+ "env-paths": "^2.2.0",
+ "json-schema-typed": "^7.0.3",
+ "make-dir": "^3.1.0",
+ "onetime": "^5.1.2",
+ "pkg-up": "^3.1.0",
+ "semver": "^7.3.4"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/conf/node_modules/semver": {
+ "version": "7.8.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz",
+ "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/convert-source-map": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
@@ -3461,6 +3606,63 @@
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
"license": "MIT"
+ },
+ "version": "2.15.4",
+ "integrity": "sha512-TP/iYTvKKKhRK89on9SRfSMGEw/9SFAAU8EC1kdT5Fmpx7dAwaCNM2+R2H1TSYoQt+03rwOs8QEfNkX8GOHjHQ==",
+ "license": "ISC",
+ "dependencies": {
+ "conf": "^9.0.0",
+ "fast-xml-parser": "4.2.5",
+ "mime-types": "^2.1.24",
+ "request": "^2.88.2"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "version": "4.2.5",
+ "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.2.5.tgz",
+ "integrity": "sha512-B9/wizE4WngqQftFPmdaMYlXoJlJOYxGQOanC77fq9k8+Z0v5dDSVh+3glErdIROP//s/jgb7ZuxKfB8nVyo0g==",
+ "funding": [
+ {
+ "type": "paypal",
+ "url": "https://paypal.me/naturalintelligence"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/NaturalIntelligence"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "strnum": "^1.0.5"
+ },
+ "bin": {
+ "fxparser": "src/cli/cli.js"
+ }
+ },
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz",
+ "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/NaturalIntelligence"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/dashdash": {
+ "version": "1.14.1",
+ "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz",
+ "integrity": "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==",
+ "license": "MIT",
+ "dependencies": {
+ "assert-plus": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=0.10"
+ }
},
"node_modules/data-uri-to-buffer": {
"version": "4.0.1",
@@ -3469,6 +3671,21 @@
"node": ">= 12"
}
},
+ "node_modules/debounce-fn": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/debounce-fn/-/debounce-fn-4.0.0.tgz",
+ "integrity": "sha512-8pYCQiL9Xdcg0UPSD3d+0KMlOjp+KGU5EPwYddgzQ7DATsg4fuUDjQtsYLmWjnk2obnNHgV3vE2Y4jejSOJVBQ==",
+ "license": "MIT",
+ "dependencies": {
+ "mimic-fn": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/debug": {
"version": "4.4.3",
"license": "MIT",
@@ -3564,6 +3781,15 @@
"node": ">= 14"
}
},
+ "node_modules/delayed-stream": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
"node_modules/detect-libc": {
"version": "2.1.2",
"license": "Apache-2.0",
@@ -3581,6 +3807,21 @@
"integrity": "sha512-98l0sW87ZT58pU4i61wa2OHwxbiYSbuxsCBozaVnYX2iCnr3bLM3fIes1/ej7h1YdOKuKt/MLs706TVnALA65w==",
"license": "BSD-2-Clause"
},
+ "node_modules/dot-prop": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-6.0.1.tgz",
+ "integrity": "sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA==",
+ "license": "MIT",
+ "dependencies": {
+ "is-obj": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/duck": {
"version": "0.1.12",
"resolved": "https://registry.npmjs.org/duck/-/duck-0.1.12.tgz",
@@ -3590,6 +3831,16 @@
"underscore": "^1.13.1"
}
},
+ "node_modules/ecc-jsbn": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz",
+ "integrity": "sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==",
+ "license": "MIT",
+ "dependencies": {
+ "jsbn": "~0.1.0",
+ "safer-buffer": "^2.1.0"
+ }
+ },
"node_modules/ecdsa-sig-formatter": {
"version": "1.0.11",
"license": "Apache-2.0",
@@ -3647,7 +3898,6 @@
},
"node_modules/env-paths": {
"version": "2.2.1",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -3817,6 +4067,27 @@
"@types/yauzl": "^2.9.1"
}
},
+ "node_modules/extsprintf": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz",
+ "integrity": "sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==",
+ "engines": [
+ "node >=0.6.0"
+ ],
+ "license": "MIT"
+ },
+ "node_modules/fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "license": "MIT"
+ },
+ "node_modules/fast-json-stable-stringify": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
+ "license": "MIT"
+ },
"node_modules/fast-xml-builder": {
"version": "1.1.5",
"funding": [
@@ -4008,6 +4279,41 @@
"version": "1.0.0",
"license": "MIT"
},
+ "node_modules/find-up": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz",
+ "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==",
+ "license": "MIT",
+ "dependencies": {
+ "locate-path": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/forever-agent": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz",
+ "integrity": "sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/form-data": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz",
+ "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==",
+ "license": "MIT",
+ "dependencies": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.6",
+ "mime-types": "^2.1.12"
+ },
+ "engines": {
+ "node": ">= 0.12"
+ }
+ },
"node_modules/formdata-polyfill": {
"version": "4.0.10",
"license": "MIT",
@@ -4137,6 +4443,15 @@
"node": ">= 14"
}
},
+ "node_modules/getpass": {
+ "version": "0.1.7",
+ "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz",
+ "integrity": "sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==",
+ "license": "MIT",
+ "dependencies": {
+ "assert-plus": "^1.0.0"
+ }
+ },
"node_modules/gifwrap": {
"version": "0.10.1",
"resolved": "https://registry.npmjs.org/gifwrap/-/gifwrap-0.10.1.tgz",
@@ -4251,6 +4566,51 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/har-schema": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz",
+ "integrity": "sha512-Oqluz6zhGX8cyRaTQlFMPw80bSJVG2x/cFb8ZPhUILGgHka9SsokCCOQgpveePerqidZOrT14ipqfJb7ILcW5Q==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/har-validator": {
+ "version": "5.1.5",
+ "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz",
+ "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==",
+ "deprecated": "this library is no longer supported",
+ "license": "MIT",
+ "dependencies": {
+ "ajv": "^6.12.3",
+ "har-schema": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/har-validator/node_modules/ajv": {
+ "version": "6.15.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
+ "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/har-validator/node_modules/json-schema-traverse": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
+ "license": "MIT"
+ },
"node_modules/has-property-descriptors": {
"version": "1.0.2",
"license": "MIT",
@@ -4277,6 +4637,21 @@
"node": ">= 14"
}
},
+ "node_modules/http-signature": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz",
+ "integrity": "sha512-CAbnr6Rz4CYQkLYUtSNXxQPUH2gK8f3iWexVlsnMeD+GjlsQ0Xsy1cOX+mN3dtxYomRy21CiOzU8Uhw6OwncEQ==",
+ "license": "MIT",
+ "dependencies": {
+ "assert-plus": "^1.0.0",
+ "jsprim": "^1.2.2",
+ "sshpk": "^1.7.0"
+ },
+ "engines": {
+ "node": ">=0.8",
+ "npm": ">=1.3.7"
+ }
+ },
"node_modules/http2-wrapper": {
"version": "1.0.3",
"dev": true,
@@ -4364,12 +4739,33 @@
"node": ">=8"
}
},
+ "node_modules/is-obj": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz",
+ "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/is-typedarray": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",
+ "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==",
+ "license": "MIT"
+ },
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
"license": "MIT"
},
+ "node_modules/isstream": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz",
+ "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==",
+ "license": "MIT"
+ },
"node_modules/jimp": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/jimp/-/jimp-1.6.1.tgz",
@@ -4414,6 +4810,12 @@
"integrity": "sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==",
"license": "BSD-3-Clause"
},
+ "node_modules/jsbn": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz",
+ "integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==",
+ "license": "MIT"
+ },
"node_modules/json-bigint": {
"version": "1.0.0",
"license": "MIT",
@@ -4426,6 +4828,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/json-schema": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",
+ "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==",
+ "license": "(AFL-2.1 OR BSD-3-Clause)"
+ },
"node_modules/json-schema-to-ts": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
@@ -4439,6 +4847,18 @@
"node": ">=16"
}
},
+ "node_modules/json-schema-traverse": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+ "license": "MIT"
+ },
+ "node_modules/json-schema-typed": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-7.0.3.tgz",
+ "integrity": "sha512-7DE8mpG+/fVw+dTpjbxnx47TaMnDfOI1jwft9g1VybltZCduyRQPJPvc+zzKY9WPHxhPWczyFuYa6I8Mw4iU5A==",
+ "license": "BSD-2-Clause"
+ },
"node_modules/json-stringify-safe": {
"version": "5.0.1",
"license": "ISC"
@@ -4451,6 +4871,21 @@
"graceful-fs": "^4.1.6"
}
},
+ "node_modules/jsprim": {
+ "version": "1.4.2",
+ "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz",
+ "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==",
+ "license": "MIT",
+ "dependencies": {
+ "assert-plus": "1.0.0",
+ "extsprintf": "1.3.0",
+ "json-schema": "0.4.0",
+ "verror": "1.10.0"
+ },
+ "engines": {
+ "node": ">=0.6.0"
+ }
+ },
"node_modules/jszip": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz",
@@ -4788,6 +5223,19 @@
"url": "https://opencollective.com/parcel"
}
},
+ "node_modules/locate-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz",
+ "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==",
+ "license": "MIT",
+ "dependencies": {
+ "p-locate": "^3.0.0",
+ "path-exists": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/long": {
"version": "5.3.2",
"license": "Apache-2.0"
@@ -4828,6 +5276,21 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
+ "node_modules/make-dir": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
+ "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/mammoth": {
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/mammoth/-/mammoth-1.12.0.tgz",
@@ -4874,6 +5337,36 @@
"node": ">=10.0.0"
}
},
+ "node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mimic-fn": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-3.1.0.tgz",
+ "integrity": "sha512-Ysbi9uYW9hFyfrThdDEQuykN4Ey6BuwPD2kpI5ES/nFTDn/98yxYNLZJcgUAKPT/mcrLLKaGzJR9YVxJrIdASQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/mimic-response": {
"version": "1.0.1",
"dev": true,
@@ -5044,6 +5537,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/oauth-sign": {
+ "version": "0.9.0",
+ "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz",
+ "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/object-keys": {
"version": "1.1.1",
"license": "MIT",
@@ -5073,6 +5575,30 @@
"wrappy": "1"
}
},
+ "node_modules/onetime": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
+ "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",
+ "license": "MIT",
+ "dependencies": {
+ "mimic-fn": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/onetime/node_modules/mimic-fn": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
+ "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/onnxruntime-common": {
"version": "1.24.3",
"resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.24.3.tgz",
@@ -5129,6 +5655,33 @@
"node": ">=8"
}
},
+ "node_modules/p-limit": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
+ "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
+ "license": "MIT",
+ "dependencies": {
+ "p-try": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/p-locate": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz",
+ "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==",
+ "license": "MIT",
+ "dependencies": {
+ "p-limit": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/p-retry": {
"version": "4.6.2",
"license": "MIT",
@@ -5140,6 +5693,15 @@
"node": ">=8"
}
},
+ "node_modules/p-try": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
+ "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/pac-proxy-agent": {
"version": "7.2.0",
"license": "MIT",
@@ -5200,6 +5762,15 @@
"version": "0.1.7",
"license": "MIT"
},
+ "node_modules/path-exists": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz",
+ "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/path-expression-matcher": {
"version": "1.5.0",
"funding": [
@@ -5247,6 +5818,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/performance-now": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
+ "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==",
+ "license": "MIT"
+ },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -5288,6 +5865,18 @@
"node": ">=12.13.0"
}
},
+ "node_modules/pkg-up": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-3.1.0.tgz",
+ "integrity": "sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA==",
+ "license": "MIT",
+ "dependencies": {
+ "find-up": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/pngjs": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz",
@@ -5406,6 +5995,18 @@
"version": "1.1.0",
"license": "MIT"
},
+ "node_modules/psl": {
+ "version": "1.15.0",
+ "resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",
+ "integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==",
+ "license": "MIT",
+ "dependencies": {
+ "punycode": "^2.3.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/lupomontero"
+ }
+ },
"node_modules/pump": {
"version": "3.0.4",
"license": "MIT",
@@ -5414,6 +6015,24 @@
"once": "^1.3.1"
}
},
+ "node_modules/punycode": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/qs": {
+ "version": "6.5.5",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.5.tgz",
+ "integrity": "sha512-mzR4sElr1bfCaPJe7m8ilJ6ZXdDaGoObcYR0ZHSsktM/Lt21MVHj5De30GQH2eiZ1qGRTO7LCAzQsUeXTNexWQ==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
"node_modules/quick-lru": {
"version": "5.1.1",
"dev": true,
@@ -5450,6 +6069,47 @@
"node": ">= 6"
}
},
+ "node_modules/request": {
+ "version": "2.88.2",
+ "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz",
+ "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==",
+ "deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "aws-sign2": "~0.7.0",
+ "aws4": "^1.8.0",
+ "caseless": "~0.12.0",
+ "combined-stream": "~1.0.6",
+ "extend": "~3.0.2",
+ "forever-agent": "~0.6.1",
+ "form-data": "~2.3.2",
+ "har-validator": "~5.1.3",
+ "http-signature": "~1.2.0",
+ "is-typedarray": "~1.0.0",
+ "isstream": "~0.1.2",
+ "json-stringify-safe": "~5.0.1",
+ "mime-types": "~2.1.19",
+ "oauth-sign": "~0.9.0",
+ "performance-now": "^2.1.0",
+ "qs": "~6.5.2",
+ "safe-buffer": "^5.1.2",
+ "tough-cookie": "~2.5.0",
+ "tunnel-agent": "^0.6.0",
+ "uuid": "^3.3.2"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/require-from-string": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/resolve-alpn": {
"version": "1.2.1",
"dev": true,
@@ -5547,6 +6207,12 @@
],
"license": "MIT"
},
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "license": "MIT"
+ },
"node_modules/sax": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz",
@@ -5558,7 +6224,6 @@
},
"node_modules/semver": {
"version": "6.3.1",
- "dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -5774,6 +6439,31 @@
"win32"
]
},
+ "node_modules/sshpk": {
+ "version": "1.18.0",
+ "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.18.0.tgz",
+ "integrity": "sha512-2p2KJZTSqQ/I3+HX42EpYOa2l3f8Erv8MWKsy2I9uf4wA7yFIkXRffYdsx86y6z4vHtV8u7g+pPlr8/4ouAxsQ==",
+ "license": "MIT",
+ "dependencies": {
+ "asn1": "~0.2.3",
+ "assert-plus": "^1.0.0",
+ "bcrypt-pbkdf": "^1.0.0",
+ "dashdash": "^1.12.0",
+ "ecc-jsbn": "~0.1.1",
+ "getpass": "^0.1.1",
+ "jsbn": "~0.1.0",
+ "safer-buffer": "^2.0.2",
+ "tweetnacl": "~0.14.0"
+ },
+ "bin": {
+ "sshpk-conv": "bin/sshpk-conv",
+ "sshpk-sign": "bin/sshpk-sign",
+ "sshpk-verify": "bin/sshpk-verify"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/stackback": {
"version": "0.0.2",
"dev": true,
@@ -5965,6 +6655,19 @@
"url": "https://github.com/sponsors/Borewit"
}
},
+ "node_modules/tough-cookie": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz",
+ "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "psl": "^1.1.28",
+ "punycode": "^2.1.1"
+ },
+ "engines": {
+ "node": ">=0.8"
+ }
+ },
"node_modules/ts-algebra": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
@@ -6002,6 +6705,12 @@
"node": "*"
}
},
+ "node_modules/tweetnacl": {
+ "version": "0.14.5",
+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
+ "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
+ "license": "Unlicense"
+ },
"node_modules/type-fest": {
"version": "0.13.1",
"license": "(MIT OR CC0-1.0)",
@@ -6068,6 +6777,15 @@
"node": ">= 4.0.0"
}
},
+ "node_modules/uri-js": {
+ "version": "4.4.1",
+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "punycode": "^2.1.0"
+ }
+ },
"node_modules/utif2": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/utif2/-/utif2-4.1.0.tgz",
@@ -6081,6 +6799,36 @@
"version": "1.0.2",
"license": "MIT"
},
+ "node_modules/uuid": {
+ "version": "3.4.0",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz",
+ "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==",
+ "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",
+ "license": "MIT",
+ "bin": {
+ "uuid": "bin/uuid"
+ }
+ },
+ "node_modules/verror": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz",
+ "integrity": "sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==",
+ "engines": [
+ "node >=0.6.0"
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "assert-plus": "^1.0.0",
+ "core-util-is": "1.0.2",
+ "extsprintf": "^1.2.0"
+ }
+ },
+ "node_modules/verror/node_modules/core-util-is": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
+ "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==",
+ "license": "MIT"
+ },
"node_modules/vite": {
"version": "8.0.9",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.0.9.tgz",
diff --git a/src/core-agent/src/providers/pi-provider.ts b/src/core-agent/src/providers/pi-provider.ts
index fbdec431..0a70cfe2 100644
--- a/src/core-agent/src/providers/pi-provider.ts
+++ b/src/core-agent/src/providers/pi-provider.ts
@@ -23,6 +23,8 @@ import type {
KnownProvider,
} from "@mariozechner/pi-ai";
+import * as crypto from "node:crypto";
+
import type { Message, MessageContent, StreamEvent, StopReason, Usage } from "../shared/types.js";
import { AuthError, ProviderError, RateLimitError, ContextOverflowError } from "../shared/errors.js";
import { createLogger } from "../shared/logger.js";
@@ -30,6 +32,26 @@ import type { CompletionParams, CompletionResult, LLMProvider, ToolDefinition }
const log = createLogger("pi-provider");
+/**
+ * Clamp a session id to a provider-safe cache key. OpenAI / Codex / Azure
+ * enforce `prompt_cache_key.length ≤ 64`; pi-ai forwards `options.sessionId`
+ * verbatim to that field. With the dev-mode OAuth flow `reconcileDevUid()`
+ * can install a 36-char GUID uid, after which `<uid>-gmember-<cid>-<aid>`
+ * is 70 chars and OpenAI 400s the request.
+ *
+ * Inputs that fit pass through unchanged so existing 8-digit-uid sessions
+ * keep their readable cache key (and existing cache buckets). Longer ones
+ * collapse to `<prefix>-<sha1hex>` = 22 + 1 + 40 = 63 chars — deterministic
+ * (same session ⇒ same key ⇒ cache still hits) and keeps a recognizable
+ * head for log diagnosis. */
+const MAX_CACHE_KEY_LEN = 64;
+function cacheSafeSessionId(s: string | undefined): string | undefined {
+ if (!s) return s;
+ if (s.length <= MAX_CACHE_KEY_LEN) return s;
+ const hash = crypto.createHash("sha1").update(s).digest("hex");
+ return `${s.slice(0, 22)}-${hash}`;
+}
+
// ─── Type conversion helpers ──────────────────────────────────────────────
/** Convert our internal Message[] to pi-ai Context. */
@@ -340,6 +362,7 @@ export function createPiProvider(config: {
const model = resolveModel(providerId, params.model, resolvedModel, config.baseUrl);
const context = buildPiContext(params.messages, params.systemPrompt, params.tools, model);
const reasoning = effectiveReasoning(params.reasoning);
+ const sessionId = cacheSafeSessionId(params.sessionId);
log.debug(`complete ${providerId}/${model.id}`);
@@ -354,7 +377,7 @@ export function createPiProvider(config: {
temperature: params.temperature,
reasoning,
cacheRetention: params.cacheRetention,
- sessionId: params.sessionId,
+ sessionId,
...(config.onPayload ? { onPayload: config.onPayload as any } : {}),
});
} else {
@@ -364,7 +387,7 @@ export function createPiProvider(config: {
maxTokens: params.maxTokens,
temperature: params.temperature,
cacheRetention: params.cacheRetention,
- sessionId: params.sessionId,
+ sessionId,
...(config.onPayload ? { onPayload: config.onPayload as any } : {}),
});
}
@@ -391,6 +414,7 @@ export function createPiProvider(config: {
const model = resolveModel(providerId, params.model, resolvedModel, config.baseUrl);
const context = buildPiContext(params.messages, params.systemPrompt, params.tools, model);
const reasoning = effectiveReasoning(params.reasoning);
+ const sessionId = cacheSafeSessionId(params.sessionId);
log.debug(`stream ${providerId}/${model.id}`);
@@ -403,7 +427,7 @@ export function createPiProvider(config: {
temperature: params.temperature,
reasoning,
cacheRetention: params.cacheRetention,
- sessionId: params.sessionId,
+ sessionId,
...(config.onPayload ? { onPayload: config.onPayload as any } : {}),
})
: piStream(model, context, {
@@ -412,7 +436,7 @@ export function createPiProvider(config: {
maxTokens: params.maxTokens,
temperature: params.temperature,
cacheRetention: params.cacheRetention,
- sessionId: params.sessionId,
+ sessionId,
...(config.onPayload ? { onPayload: config.onPayload as any } : {}),
});
diff --git a/src/main/features/agents.ts b/src/main/features/agents.ts
index fcbad791..b2bc38da 100644
--- a/src/main/features/agents.ts
+++ b/src/main/features/agents.ts
@@ -778,7 +778,8 @@ export interface UpdateAgentFields {
* Authored by the create modal + edit UI, not the LLM edit prompt. */
runtime?: AgentRuntime | null;
/** Marketplace category code. Empty string drops the field; omitted = untouched.
- * Authored by the create / edit dialog dropdown, NOT the agent-edit LLM. */
+ * Authored by the create / edit dialog dropdown OR by the agent-edit LLM via the
+ * `<category>` sub-tag (validated against `AGENT_CATEGORY_CODES` in `_parseAgentBlock`). */
category?: string;
}
@@ -1102,6 +1103,13 @@ export async function deleteCustomAgent(agentId: string): Promise<boolean> {
const AGENT_CONTAINER_RE = /<agent>([\s\S]*?)<\/agent>/g;
const AGENT_CHILD_RE = (tag: string) => new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`);
+/** Marketplace category codes — kept in sync with
+ * `Server/biz/marketplace/marketplace_mgr.py::DEFAULT_CATEGORIES`. Single source of truth
+ * for `<category>` validation in `<agent>` container parsing. */
+export const AGENT_CATEGORY_CODES: ReadonlySet<string> = new Set([
+ 'education', 'ecommerce', 'rnd', 'writing', 'data', 'general',
+]);
+
export interface ExtractedFields {
/** Parsed from `<agent_id>` inside `<agent>`. Present → commander wants to
* patch this existing custom agent (main-chat edit flow); absent → create
@@ -1125,6 +1133,11 @@ export interface ExtractedFields {
* `false` (case-insensitive); anything else → key omitted (leave the
* existing flag untouched). */
interactive?: boolean;
+ /** Parsed from `<category>` inside `<agent>`. Body must be one of
+ * `AGENT_CATEGORY_CODES`; invalid value → key omitted (existing field
+ * preserved). New agents without a category fall through to whatever
+ * `createCustomAgent` decides (empty string today). */
+ category?: string;
}
function _parseAgentBlock(inner: string): ExtractedFields {
@@ -1191,6 +1204,13 @@ function _parseAgentBlock(inner: string): ExtractedFields {
else if (v === 'false') fields.interactive = false;
// Any other body → leave key omitted; previous flag survives.
}
+ const catM = inner.match(AGENT_CHILD_RE('category'));
+ if (catM) {
+ const v = catM[1].trim().toLowerCase();
+ // Validate against the known code set. Unknown values are dropped silently — the existing
+ // category field on the agent is preserved (don't let an LLM hallucinated code blank it).
+ if (AGENT_CATEGORY_CODES.has(v)) fields.category = v;
+ }
return fields;
}
@@ -1566,6 +1586,7 @@ export async function createAgentFromBlocks(fields: ExtractedFields): Promise<Ag
const created = await createCustomAgent({
name, description, description_zh, description_en, workflow,
...(typeof fields.interactive === 'boolean' ? { interactive: fields.interactive } : {}),
+ ...(typeof fields.category === 'string' ? { category: fields.category } : {}),
});
if (!created) return null;
// Fold optional skill_list + inputs in via updateCustomAgent so the
diff --git a/src/main/features/chat_attachments.ts b/src/main/features/chat_attachments.ts
index 8a31ab3b..0038ad49 100644
--- a/src/main/features/chat_attachments.ts
+++ b/src/main/features/chat_attachments.ts
@@ -378,8 +378,43 @@ export function resolveLocalMediaPath(
return { ok: true, absPath: normalized, kind: VIDEO_EXTS.has(ext) ? 'video' : 'image' };
}
-/** MIME lookup for the chat-media:// protocol handler. Covers images + videos
- * (the only kinds the handler streams — text/pdf/docx are read via IPC). */
+/**
+ * Sibling of `resolveLocalMediaPath` for files that aren't media but still
+ * need to be streamed through `chat-media://local/<abs>` so the renderer can
+ * preview them in-app (PDF via Chromium's PDFium, HTML via a sandboxed
+ * iframe). Same threat model: extension allow-list, no directory allow-list.
+ *
+ * No size cap — these are served via `serveFileRange`, so Chromium streams
+ * the bytes directly into the iframe (or PDF viewer) without ever touching
+ * the JS heap. Worst case of a huge file is a few seconds of busy GPU
+ * process while the user dismisses the overlay.
+ */
+const PREVIEW_DOC_EXTS: ReadonlySet<string> = new Set(['.pdf', '.html', '.htm']);
+
+export function resolveLocalPreviewPath(
+ absPath: string,
+): { ok: true; absPath: string; kind: 'pdf' | 'html' } | { ok: false; code: 'bad_input' | 'not_found'; error: string } {
+ if (typeof absPath !== 'string' || !absPath) {
+ return { ok: false, code: 'bad_input', error: 'path required' };
+ }
+ if (!path.isAbsolute(absPath)) {
+ return { ok: false, code: 'bad_input', error: 'path must be absolute' };
+ }
+ const normalized = path.resolve(absPath);
+ const ext = path.extname(normalized).toLowerCase();
+ if (!PREVIEW_DOC_EXTS.has(ext)) {
+ return { ok: false, code: 'bad_input', error: `unsupported extension: ${ext || '(none)'}` };
+ }
+ let stat: fs.Stats;
+ try { stat = fs.statSync(normalized); }
+ catch { return { ok: false, code: 'not_found', error: 'not found' }; }
+ if (!stat.isFile()) return { ok: false, code: 'not_found', error: 'not a file' };
+ return { ok: true, absPath: normalized, kind: ext === '.pdf' ? 'pdf' : 'html' };
+}
+
+/** MIME lookup for the chat-media:// protocol handler. Covers images, videos,
+ * and the in-app preview docs served via `resolveLocalPreviewPath` (pdf /
+ * html). Text/markdown go through the `produced.readText` IPC instead. */
export function mediaMimeFor(name: string): string {
const ext = path.extname(name).toLowerCase();
if (ext === '.png') return 'image/png';
@@ -391,6 +426,8 @@ export function mediaMimeFor(name: string): string {
if (ext === '.mov') return 'video/quicktime';
if (ext === '.m4v') return 'video/x-m4v';
if (ext === '.ogv') return 'video/ogg';
+ if (ext === '.pdf') return 'application/pdf';
+ if (ext === '.html' || ext === '.htm') return 'text/html';
return 'application/octet-stream';
}
@@ -541,6 +578,12 @@ export async function buildAttachmentManifest(
const buf = fs.readFileSync(abs);
const compressed = await toCompressedGrayJpeg(buf, { maxDim: 1024, quality: 70, grayscale: true });
images.push({ data: compressed.buf.toString('base64'), mediaType: 'image/jpeg' });
+ // Also list the image in the manifest so the LLM has a text-side
+ // hint (filename + abs path) tying its inline-attached vision input
+ // to the user's intent ("this image is 证书.jpg"). `attached="inline"`
+ // tells the LLM bytes are already on this turn — see chat_commander.md
+ // attachments section — so it doesn't waste a read_file round-trip.
+ entries.push(`<file name="${escapeAttr(nm)}" path="${escapeAttr(abs)}" kind="image" attached="inline"/>`);
} catch (err) {
skipped.push({ name: nm, reason: t('attachments.skipped.compress_failed', { message: (err as Error).message }) });
}
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index 683e6b7b..07521724 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -103,7 +103,6 @@ export async function listConversations(userId: string): Promise<Conversation[]>
// this window (Cmd+R right after stop) and we say processing=false,
// it stops polling and never picks up the late abort message — user
// sees only their own msg, "everything I watched stream is gone".
- const dir = ensureUserDir(userId);
const out: Conversation[] = [];
for (const c of items) {
let processing = false;
@@ -114,25 +113,22 @@ export async function listConversations(userId: string): Promise<Conversation[]>
processing = s.status === 'running' || busBusy;
since = processing ? s.last_active_at : null;
} catch { /* missing state file = idle */ }
- // Last-activity timestamp for sidebar ordering. <cid>.jsonl mtime is
- // touched whenever the bus appends a message; falls back to the
- // index's updated_at / created_at when the file isn't there yet.
+ // Last-activity = max(updated_at, created_at). `updated_at` is bumped
+ // by `bumpConversationActivity` on every message append (group_chat/
+ // bus.ts::appendMain), so it tracks the real per-conversation timeline
+ // and survives sync (the _index.json array merge unions by id with
+ // updated_at tiebreak). We deliberately do NOT consult `<cid>.jsonl`
+ // mtime: sync rewrites mtime when pulling, and any file-system tool
+ // that touches the bytes (backup restore, IDE, tar, manual edit) would
+ // falsify the sort.
//
// CAREFUL: `nowIso()` returns local-time ISO without `Z` suffix
- // ("2026-05-07T15:00:00") while `mtime.toISOString()` is UTC with `Z`
- // ("2026-05-07T07:00:00.000Z"). String-comparing the two formats
- // ignores the timezone offset — at UTC+8 a local-time string compares
- // 8h "ahead" of the same instant in UTC, so updated_at would always
- // appear newer than mtime and the sidebar would order by creation
- // time instead of actual last activity. Compare on numeric ms and
- // emit a UTC ISO so the downstream sort can string-compare safely.
+ // ("2026-05-07T15:00:00") while ISO with `Z` is UTC. Compare on
+ // numeric ms and emit a UTC ISO so the downstream sort can
+ // string-compare safely across both shapes.
const updatedMs = c.updated_at ? new Date(c.updated_at).getTime() : 0;
const createdMs = c.created_at ? new Date(c.created_at).getTime() : 0;
- let lastActiveMs = Math.max(updatedMs || 0, createdMs || 0);
- try {
- const mtimeMs = fs.statSync(path.join(dir, `${c.conversation_id}.jsonl`)).mtime.getTime();
- if (mtimeMs > lastActiveMs) lastActiveMs = mtimeMs;
- } catch { /* missing jsonl — keep updated_at */ }
+ const lastActiveMs = Math.max(updatedMs || 0, createdMs || 0);
const lastActiveAt = lastActiveMs ? new Date(lastActiveMs).toISOString() : (c.updated_at || c.created_at || '');
out.push({ ...c, processing, processing_since: since, last_active_at: lastActiveAt });
}
@@ -148,6 +144,29 @@ export async function saveConversations(userId: string, items: Conversation[]):
await writeJson(path.join(ensureUserDir(userId), CONVERSATION_INDEX_NAME), cleaned);
}
+/** Stamp `updated_at` on the cid's index row to the timestamp of the message
+ * just written. Called by `group_chat/bus.ts::appendMain` after every
+ * `<cid>.jsonl` append. listConversations sorts by `updated_at` (rather than
+ * file mtime) so cross-device sync is well-behaved — manifest-merge of the
+ * index array is a union-by-id with `updated_at` tiebreak, so both devices
+ * converge on the actual last-activity time. No-op when the row doesn't
+ * exist (the conv may have been deleted between message-write and bump). */
+export async function bumpConversationActivity(userId: string, cid: string, tsIso: string): Promise<void> {
+ if (!cid || !tsIso) return;
+ const items = await _readRawConversations(userId);
+ let changed = false;
+ for (const c of items) {
+ if (c.conversation_id === cid) {
+ if (c.updated_at !== tsIso) {
+ c.updated_at = tsIso;
+ changed = true;
+ }
+ break;
+ }
+ }
+ if (changed) await saveConversations(userId, items);
+}
+
export async function getConversation(userId: string, cid: string): Promise<Conversation | null> {
if (!safeId(cid)) return null;
const list = await listConversations(userId);
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index c8e7c79c..6a5ff4a6 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -261,6 +261,16 @@ async function appendMain(uid: string, cid: string, msg: GroupMessage): Promise<
const file = mainJsonlFile(uid, cid);
fs.mkdirSync(path.dirname(file), { recursive: true });
await appendJsonlAtomic<GroupMessage>(file, msg);
+ // Stamp `updated_at` on this cid's _index.json row so the sidebar can sort
+ // by real last-activity time rather than file mtime (which sync clobbers
+ // when pulling from another device — see chats.ts::listConversations).
+ // Dynamic import to avoid the chats ↔ group_chat circular dep.
+ try {
+ const chats = await import('../chats');
+ await chats.bumpConversationActivity(uid, cid, msg.ts);
+ } catch (err) {
+ log.warn('bumpConversationActivity failed', { uid, cid, error: (err as Error)?.message });
+ }
}
// ── enqueue ──────────────────────────────────────────────────────────────
@@ -854,17 +864,19 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
}
// Attach a `<attachments>` manifest block listing user-uploaded files
- // (text / pdf / docx with absolute paths + kinds). Commander uses it to
- // route work; agent uses it to extract values for `inputs_schema`
- // (especially `type=file` fields). Without this the LLM only sees the
- // text body and can't know what files the user attached. Image bytes
- // aren't piped through here yet — that needs ChatOptions.images plumbing
- // and lands as a follow-up.
+ // (text / pdf / docx / image with absolute paths + kinds). Commander uses
+ // it to route work; agent uses it to extract values for `inputs_schema`
+ // (especially `type=file` fields). Image bytes ride alongside via
+ // ChatOptions.images so the vision model sees them on the same user turn
+ // — the manifest entry carries `attached="inline"` so the LLM doesn't
+ // waste a read_file round-trip re-fetching what it already has.
+ let turnImages: Array<{ data: string; mediaType: 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' }> = [];
if (item.attachments && item.attachments.length) {
try {
const { buildAttachmentManifest } = await import('../chat_attachments');
- const { manifest } = await buildAttachmentManifest(uid, cid, item.attachments);
+ const { manifest, images } = await buildAttachmentManifest(uid, cid, item.attachments);
if (manifest) messageText = `${manifest}\n${messageText}`;
+ if (images.length) turnImages = images;
} catch (err) {
log.warn(`attachments manifest build failed cid=${cid} actor=${actor.id}: ${(err as Error).message}`);
}
@@ -1089,6 +1101,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
cacheRetention: 'short',
abortSignal: w.abortController.signal,
readOnlyExtraRoots: [...skillRoots, ...agentRoots],
+ ...(turnImages.length ? { images: turnImages } : {}),
...(extraTools.length ? { extraTools } : {}),
...(skillList !== undefined ? { skillList } : {}),
// Skills are NOT project-scoped this round — every conversation sees
diff --git a/src/main/features/group_chat/conv_workspace.ts b/src/main/features/group_chat/conv_workspace.ts
index 2b5d06bc..e7b1add4 100644
--- a/src/main/features/group_chat/conv_workspace.ts
+++ b/src/main/features/group_chat/conv_workspace.ts
@@ -205,6 +205,9 @@ export async function getConversationWorkspacePath(uid: string, cid: string): Pr
// directory is NOT created here — see the function-level comment above.
const persisted = await setWorkspaceDirOnce(uid, cid, slug);
const finalSlug = persisted.workspace_dir || slug;
- log.info(`cid=${cid} workspace_dir=${finalSlug} (title="${title}", lazy-mkdir)`);
+ // Don't log the raw title — it's user-authored content (can include
+ // chat topic / names). The slug (after slugifyConvTitle) is the
+ // diagnostic signal we need.
+ log.info(`cid=${cid} workspace_dir=${finalSlug} title_len=${title.length} (lazy-mkdir)`);
return path.join(root, finalSlug);
}
diff --git a/src/main/features/kb_vector.ts b/src/main/features/kb_vector.ts
index 71ebcb98..7d05473e 100644
--- a/src/main/features/kb_vector.ts
+++ b/src/main/features/kb_vector.ts
@@ -26,10 +26,10 @@ export type KbSearchHit = vs.VecSearchHit;
export type KbSearchOpts = vs.VecSearchOpts;
function kbDbDir(uid: string): string {
- // userKbVectorDbPath returns `<uid>/cloud/contexts/.kb/vector.db`; vec_store
- // expects the containing directory so it can manage `vector.db` +
- // `config.json` side by side. `path.dirname` handles `/` and `\` correctly
- // on every platform.
+ // userKbVectorDbPath returns `<uid>/local/contexts/.kb/vector.db`
+ // (machine-private, NOT cloud-synced; multi-device-sync batch 2 +
+ // util/migrate-kb-to-local.ts). vec_store expects the containing
+ // directory so it can manage `vector.db` + `config.json` side by side.
return path.dirname(userKbVectorDbPath(uid));
}
diff --git a/src/main/features/local_agents/backends/_acp.ts b/src/main/features/local_agents/backends/_acp.ts
index c139b80e..bf27f11b 100644
--- a/src/main/features/local_agents/backends/_acp.ts
+++ b/src/main/features/local_agents/backends/_acp.ts
@@ -22,6 +22,7 @@ import {
spawnCli,
bindAbort,
LineSplitter,
+ levelOrInfo,
} from './base.js';
export interface AcpBackendDef {
@@ -108,7 +109,15 @@ export function makeAcpBackend(def: AcpBackendDef): LocalBackend {
const trimmed = line.trim();
if (!trimmed) return;
let env: any;
- try { env = JSON.parse(trimmed); } catch { return; }
+ try { env = JSON.parse(trimmed); }
+ catch {
+ // ACP wire is NDJSON; a non-JSON line means the CLI logged
+ // something straight to stdout (hermes occasionally does
+ // this on startup). Surface as raw-line so it appears in
+ // the process rail.
+ opts.onEvent({ type: 'raw-line', line: trimmed });
+ return;
+ }
handleAcpMessage(env, {
onSessionNew: id => {
sessionId = id;
@@ -148,7 +157,17 @@ export function makeAcpBackend(def: AcpBackendDef): LocalBackend {
try { child.stdin.end(); } catch { /* */ }
},
onUnknown: raw => {
- opts.onEvent({ type: 'tool-event', tool: 'acp', phase: 'use', input: raw, callId: '' });
+ // Previously surfaced as a fake `tool:'acp'` tool-event,
+ // which polluted the tools rail with category-error rows.
+ // Reroute to a log event so the rail's tool list stays
+ // honest and unknown ACP traffic still gets visibility.
+ const summary = JSON.stringify(raw).slice(0, 200);
+ opts.onEvent({
+ type: 'log',
+ level: 'info',
+ message: `acp: ${summary}`,
+ source: 'acp',
+ });
},
});
});
diff --git a/src/main/features/local_agents/backends/base.ts b/src/main/features/local_agents/backends/base.ts
index 8342cd6c..0dec1b4f 100644
--- a/src/main/features/local_agents/backends/base.ts
+++ b/src/main/features/local_agents/backends/base.ts
@@ -27,20 +27,28 @@ export type LocalEventType =
| 'tool-event'
| 'stderr-line'
| 'status'
+ | 'log'
+ | 'raw-line'
+ | 'permission-request'
+ | 'idle'
| 'done';
export interface LocalEvent {
type: LocalEventType;
/** Free-form payload — exact keys vary per type. Documented inline at
* each emit site; a minimal index:
- * process-info: { pid, cwd, cmd, args, sessionId? }
- * text-delta: { text }
- * thinking: { text }
- * tool-event: { tool, callId?, phase: 'use'|'result', input?, output? }
- * stderr-line: { line }
- * status: { status }
- * done: { status: 'completed'|'failed'|'cancelled'|'timeout'|
- * 'missing_cli', error?, durationMs?, sessionId? }
+ * process-info: { pid, cwd, cmd, args, sessionId? }
+ * text-delta: { text }
+ * thinking: { text }
+ * tool-event: { tool, callId?, phase: 'use'|'result', input?, output?, outputPath? }
+ * stderr-line: { line }
+ * status: { status, usage? } // usage carried for status:'usage' running counters
+ * log: { level: 'debug'|'info'|'warn'|'error', message, source? }
+ * raw-line: { line } // stdout line we couldn't parse as our protocol
+ * permission-request: { id, tool?, input?, autoDecided: 'allow'|'deny', reason }
+ * idle: { stalledMs } // runner-emitted heartbeat on prolonged silence
+ * done: { status: 'completed'|'failed'|'cancelled'|'timeout'|
+ * 'missing_cli', error?, durationMs?, sessionId?, usage? }
*/
[key: string]: unknown;
}
@@ -62,6 +70,13 @@ export interface BackendRunOptions {
/** Wall-clock cap. Backends should arm a timer and emit
* `done({status:'timeout'})` when it fires before the CLI exits. */
timeoutMs: number;
+ /** Per-backend idle threshold override (ms). Read by `runner.ts`'s
+ * idle-heartbeat to decide when to emit `{type:'idle'}` events. When
+ * unset the runner uses its own default (90 s; configurable via
+ * ORKAS_LOCAL_AGENT_IDLE_MS). Backends with no streaming (today:
+ * openclaw) should pass a smaller value so users get an early "still
+ * alive" pulse instead of staring at a blank rail for the full run. */
+ idleMs?: number;
}
export interface LocalBackend {
@@ -142,6 +157,20 @@ export class LineSplitter {
}
}
+/** Normalize a free-form log level string to our 4-tier scale. CLIs
+ * use various conventions (`debug` / `DEBUG` / `verbose` / `warning`
+ * / `err` / numeric); unknown values fold to `info`. Shared by every
+ * backend's `log`-event emit site so the renderer can rely on the
+ * 4-value enum. */
+export function levelOrInfo(raw: unknown): 'debug' | 'info' | 'warn' | 'error' {
+ if (typeof raw !== 'string') return 'info';
+ const s = raw.toLowerCase();
+ if (s === 'debug' || s === 'trace' || s === 'verbose') return 'debug';
+ if (s === 'warn' || s === 'warning') return 'warn';
+ if (s === 'error' || s === 'err' || s === 'fatal') return 'error';
+ return 'info';
+}
+
/**
* Wire abort + grace-kill behavior. Returns a cleanup function the
* caller must invoke after the child exits to detach listeners.
diff --git a/src/main/features/local_agents/backends/claude.ts b/src/main/features/local_agents/backends/claude.ts
index 5d7e92a9..bcddb726 100644
--- a/src/main/features/local_agents/backends/claude.ts
+++ b/src/main/features/local_agents/backends/claude.ts
@@ -22,6 +22,7 @@ import {
spawnCli,
bindAbort,
LineSplitter,
+ levelOrInfo,
} from './base.js';
const log = createLogger('local-agents:claude');
@@ -40,6 +41,13 @@ export const claudeBackend: LocalBackend = {
let resultText = '';
let resultStatus: 'completed' | 'failed' | undefined;
let resultError: string | undefined;
+ let resultUsage: Record<string, number | string> | undefined;
+ /** Running token tally accumulated from each `assistant` block's
+ * `message.usage` (mirrors multica's per-model map). The final
+ * `result.usage` claude itself emits is authoritative and overwrites
+ * this when the turn ends; in the meantime accUsage drives the
+ * live `status:'usage'` row. */
+ let accUsage: Record<string, number | string> | undefined;
// Tracks whether we've seen a real stream_event with text content
// — gates whether we can safely skip the assistant block's text
// (which would otherwise duplicate the streamed body). Old claude
@@ -63,8 +71,19 @@ export const claudeBackend: LocalBackend = {
}, opts.timeoutMs);
if (typeof timer.unref === 'function') timer.unref();
- // Build and send the single user message, then close stdin so
- // claude knows there's no follow-up turn coming.
+ // Build and send the single user message, but keep stdin OPEN —
+ // claude code's stream-json protocol uses stdin for two channels:
+ // 1. The user message that kicks off the turn (one and done).
+ // 2. `control_response` records replying to claude's
+ // `control_request` (tool-use permission, hook gates). Even
+ // with `--permission-mode bypassPermissions`, MCP tools / user
+ // hooks still gate via this channel and the process blocks
+ // waiting for a stdin response we never send if we close
+ // stdin here. That's the "silent hang for 20 minutes" symptom
+ // users report — fix by writing the prompt without `.end()`
+ // and closing stdin only once we see the terminal `result`
+ // record (handled below in mapClaudeEvent's 'result' branch
+ // via the closeStdin callback).
const inputLine = JSON.stringify({
type: 'user',
message: {
@@ -72,7 +91,34 @@ export const claudeBackend: LocalBackend = {
content: [{ type: 'text', text: opts.prompt }],
},
}) + '\n';
- child.stdin.end(inputLine);
+ child.stdin.write(inputLine);
+
+ /** Auto-allow control_request — claude code asks for tool-use /
+ * hook permission through this channel. We're a daemon-style
+ * dispatcher (no interactive UI yet for approval), so the only
+ * sane response is to allow and surface a permission-request
+ * event to the rail for visibility. Schema mirrors multica's
+ * daemon (`server/pkg/agent/claude.go::handleControlRequest`). */
+ const respondToControlRequest = (msg: any): void => {
+ const req = msg?.request || {};
+ const inputMap = (req.input && typeof req.input === 'object') ? req.input : {};
+ const response = {
+ type: 'control_response',
+ response: {
+ subtype: 'success',
+ request_id: msg.request_id,
+ response: {
+ behavior: 'allow',
+ updatedInput: inputMap,
+ },
+ },
+ };
+ try {
+ child.stdin.write(JSON.stringify(response) + '\n');
+ } catch (err) {
+ log.warn('claude control_response write failed', { error: (err as Error).message });
+ }
+ };
// stdout: line-buffered JSON parsing.
const splitter = new LineSplitter();
@@ -84,12 +130,52 @@ export const claudeBackend: LocalBackend = {
let obj: any;
try { obj = JSON.parse(trimmed); }
catch {
- // Pre-stream banner / debug noise — surface as text-delta
- // when nothing else has arrived yet so users still see why
- // the CLI is unhappy. After we have a session id, drop.
+ // Non-JSON stdout — two distinct paths:
+ // - Before sessionId: surface as text-delta so a pre-stream
+ // banner / startup error still lands in the user bubble
+ // even when the CLI never gets far enough to talk
+ // stream-json. This is the only signal the user has when
+ // the CLI itself failed to boot.
+ // - After sessionId: emit as raw-line. Banner, MCP startup
+ // warnings, --verbose debug noise — direct-terminal users
+ // see these every run; previously we dropped them
+ // silently after session_id was captured, which is the
+ // "Orkas shows less than the terminal" symptom users
+ // reported. Raw-line renders as a kind-meta row in the
+ // process rail.
if (!sessionId) opts.onEvent({ type: 'text-delta', text: trimmed + '\n' });
+ else opts.onEvent({ type: 'raw-line', line: trimmed });
return;
}
+ // Side-channel: control_request needs a stdin write back AND a
+ // rail event. Handled outside mapClaudeEvent so the mapper
+ // stays a pure translator (no I/O, easier to unit-test).
+ if (obj?.type === 'control_request') {
+ respondToControlRequest(obj);
+ opts.onEvent({
+ type: 'permission-request',
+ id: String(obj.request_id || ''),
+ tool: String(obj?.request?.tool_name || ''),
+ input: obj?.request?.input ?? {},
+ autoDecided: 'allow',
+ reason: 'bypass',
+ });
+ return;
+ }
+ // Side-channel: each `assistant` block carries a `message.usage`
+ // snapshot for that turn-piece. Multica accumulates these per
+ // model and reports a flat total at the end. We do the same
+ // accumulation AND additionally emit a streaming
+ // `status:'usage'` event so the rail shows a live token
+ // counter (matches the codex / opencode parity — claude only
+ // emits one usage record otherwise, at the terminal result).
+ if (obj?.type === 'assistant' && obj?.message?.usage) {
+ const inc = extractClaudeUsage({ usage: obj.message.usage, message: { model: obj.message.model } });
+ if (inc) {
+ accUsage = mergeUsage(accUsage, inc);
+ opts.onEvent({ type: 'status', status: 'usage', usage: accUsage });
+ }
+ }
const ev = mapClaudeEvent(obj, sessionId, partialState);
if (ev?.captureSession && obj.session_id) sessionId = String(obj.session_id);
if (ev?.event) opts.onEvent(ev.event);
@@ -97,6 +183,12 @@ export const claudeBackend: LocalBackend = {
resultStatus = ev.terminal.status;
resultText = ev.terminal.text;
resultError = ev.terminal.error;
+ resultUsage = ev.terminal.usage as typeof resultUsage;
+ // Terminal record received — close stdin so the CLI's
+ // post-result cleanup can exit (we kept it open through the
+ // run to handle control_request). EPIPE on this write is
+ // safe; base.ts's stdin.on('error') swallows it.
+ try { child.stdin.end(); } catch { /* already gone */ }
}
});
});
@@ -138,11 +230,13 @@ export const claudeBackend: LocalBackend = {
child.on('close', code => {
if (opts.signal.aborted) return finish('cancelled');
if (timedOut) return finish('timeout', { error: `claude exceeded ${opts.timeoutMs}ms`, stderrTail: tail.toString() });
- if (code === 0 && resultStatus === 'completed') return finish('completed', { output: resultText });
+ if (code === 0 && resultStatus === 'completed') {
+ return finish('completed', { output: resultText, usage: resultUsage });
+ }
// Non-zero exit OR result subtype indicated error — surface tail.
const err = resultError
|| (code !== 0 ? `claude exited with code ${code}` : 'claude reported error in result');
- finish('failed', { error: err, output: resultText, stderrTail: tail.toString() });
+ finish('failed', { error: err, output: resultText, stderrTail: tail.toString(), usage: resultUsage });
});
});
},
@@ -193,11 +287,36 @@ export function mapClaudeEvent(
partialState: { sawTextStreamEvent: boolean } = { sawTextStreamEvent: false },
):
| undefined
- | { event?: LocalEvent; captureSession?: boolean; terminal?: { status: 'completed' | 'failed'; text: string; error?: string } } {
+ | { event?: LocalEvent; captureSession?: boolean; terminal?: { status: 'completed' | 'failed'; text: string; error?: string; usage?: Record<string, number | string> } } {
if (!obj || typeof obj !== 'object') return undefined;
const type = obj.type;
if (type === 'system' && obj.subtype === 'init') {
- return { captureSession: true };
+ // Surface a running-status pulse alongside capturing the session
+ // id. Matches multica's parity: an explicit '▶ running' row tells
+ // the user the CLI handshake succeeded and we're now waiting on
+ // model output, distinct from the earlier '▶ /path/to/claude'
+ // spawn row.
+ return {
+ captureSession: true,
+ event: { type: 'status', status: 'running' },
+ };
+ }
+ if (type === 'log') {
+ // claude --verbose emits these for MCP / hook / tool-router
+ // internals. We used to drop them as an unknown type; they're
+ // exactly the "why is the CLI silent for 20s" signal users were
+ // missing.
+ const lvl = obj?.log?.level || obj?.level;
+ const msg = obj?.log?.message || obj?.message || '';
+ if (typeof msg !== 'string' || !msg) return undefined;
+ return {
+ event: {
+ type: 'log',
+ level: levelOrInfo(lvl),
+ message: msg,
+ source: 'claude',
+ },
+ };
}
if (type === 'stream_event') {
const inner = obj.event;
@@ -218,18 +337,16 @@ export function mapClaudeEvent(
return undefined;
}
if (innerType === 'content_block_start') {
- const cb = inner.content_block;
- if (cb?.type === 'tool_use') {
- return {
- event: {
- type: 'tool-event',
- tool: String(cb.name || 'unknown'),
- callId: String(cb.id || ''),
- phase: 'use',
- input: cb.input ?? {},
- },
- };
- }
+ // content_block_start for a tool_use ALWAYS has an empty `input`
+ // here — claude streams the actual input character-by-character
+ // through `input_json_delta` notifications and folds them at
+ // content_block_stop / in the assistant block. Emitting the
+ // start event surfaced as a confusing `■ Bash · 开始 · {}`
+ // duplicate of the proper `■ Bash · 开始 · {"command":...}` row
+ // the assistant block produces a few hundred ms later.
+ // Same reason `input_json_delta` is intentionally not rendered
+ // (see the content_block_delta branch above) — we wait for the
+ // assistant block to emit one row with the complete input.
return undefined;
}
return undefined;
@@ -293,10 +410,82 @@ export function mapClaudeEvent(
const ok = obj.subtype === 'success';
const text = typeof obj.result === 'string' ? obj.result : '';
const error = !ok && typeof obj.error === 'string' ? obj.error : undefined;
+ // Extract usage in the same shape multica daemon does
+ // (input_tokens / output_tokens / cache_read_input_tokens /
+ // cache_creation_input_tokens). Model lives on the message
+ // sibling sometimes; fall back to root `model` if present.
+ const usage = extractClaudeUsage(obj);
+ // Carry usage on the status event too so the rail can render
+ // "● result · in=N out=M cache=K" at turn end — claude only emits
+ // usage once (not streaming like codex/opencode), so without this
+ // the rail's last row is a bare `● result` and the user has no
+ // sense of how much the turn cost. The terminal record carries it
+ // alongside for the done event path.
return {
- event: { type: 'status', status: ok ? 'result' : 'error' },
- terminal: { status: ok ? 'completed' : 'failed', text, error },
+ event: {
+ type: 'status',
+ status: ok ? 'result' : 'error',
+ ...(usage ? { usage } : {}),
+ },
+ terminal: { status: ok ? 'completed' : 'failed', text, error, usage },
};
}
return undefined;
}
+
+/** Pull token-usage fields out of a claude-code `type:result` record
+ * into our normalized shape. Returns undefined when no recognizable
+ * numeric fields are present so the caller can omit the `usage` key
+ * rather than emit zeros. Exposed for unit testing.
+ *
+ * Reads from THREE root fields:
+ * - `usage.{input,output,cache_read,cache_creation}_input_tokens`
+ * - `total_cost_usd` (claude tracks the dollars itself)
+ * - `message.model` / `model` (string)
+ */
+export function extractClaudeUsage(obj: any): undefined | {
+ input?: number;
+ output?: number;
+ cacheRead?: number;
+ cacheCreate?: number;
+ cost?: number;
+ model?: string;
+} {
+ const u = obj?.usage;
+ const haveUsage = u && typeof u === 'object';
+ const out: Record<string, number | string> = {};
+ if (haveUsage) {
+ if (typeof u.input_tokens === 'number') out.input = u.input_tokens;
+ if (typeof u.output_tokens === 'number') out.output = u.output_tokens;
+ if (typeof u.cache_read_input_tokens === 'number') out.cacheRead = u.cache_read_input_tokens;
+ if (typeof u.cache_creation_input_tokens === 'number') out.cacheCreate = u.cache_creation_input_tokens;
+ }
+ if (typeof obj?.total_cost_usd === 'number' && Number.isFinite(obj.total_cost_usd)) {
+ out.cost = obj.total_cost_usd;
+ }
+ const model = obj?.message?.model || obj?.model;
+ if (typeof model === 'string' && model) out.model = model;
+ return Object.keys(out).length ? (out as any) : undefined;
+}
+
+/** Sum two normalized usage records numeric-field-wise. `model` follows
+ * last-write-wins (multi-model turns are rare but possible). Used by
+ * the claude backend to accumulate per-`assistant`-block snapshots
+ * into a running total — exposed via `status:'usage'` events so the
+ * rail shows a live token counter without waiting for the terminal
+ * result record. Mirrors multica's per-model usage map (we collapse
+ * to a single flat record since the rail only renders one usage row). */
+function mergeUsage(
+ acc: Record<string, number | string> | undefined,
+ inc: Record<string, number | string>,
+): Record<string, number | string> {
+ const out: Record<string, number | string> = { ...(acc || {}) };
+ for (const k of ['input', 'output', 'cacheRead', 'cacheCreate']) {
+ const a = typeof out[k] === 'number' ? (out[k] as number) : 0;
+ const i = typeof inc[k] === 'number' ? (inc[k] as number) : 0;
+ if (a || i) out[k] = a + i;
+ }
+ if (typeof inc.model === 'string' && inc.model) out.model = inc.model;
+ return out;
+}
+
diff --git a/src/main/features/local_agents/backends/codex.ts b/src/main/features/local_agents/backends/codex.ts
index b5a433dc..d14aa308 100644
--- a/src/main/features/local_agents/backends/codex.ts
+++ b/src/main/features/local_agents/backends/codex.ts
@@ -37,6 +37,18 @@ import {
LineSplitter,
} from './base.js';
+/** codex notifications that are pure metadata noise — we keep them
+ * visible only at level=debug. Everything outside this list AND
+ * outside the structured handlers above falls through to a level=info
+ * log event so users see what the binary is up to. usage notifications
+ * are intentionally OUT of this list because step 6 promotes them to
+ * a structured `status:'usage'` event with live counters. */
+const CODEX_DROP_TO_DEBUG = new Set<string>([
+ 'thread/started',
+ 'account/rateLimits/updated',
+ 'mcpServer/startupStatus/updated',
+]);
+
const log = createLogger('local-agents:codex');
export const codexBackend: LocalBackend = {
@@ -77,6 +89,10 @@ export const codexBackend: LocalBackend = {
const seenTurnIds = new Set<string>();
let collectedText = '';
let turnError: string | undefined;
+ // Latest usage snapshot from `thread/tokenUsage/updated` —
+ // each notification is a cumulative state (not an increment),
+ // so we just overwrite. Threaded into the done event below.
+ let lastUsage: Record<string, number | string> | undefined;
const sendLine = (msg: object) => {
try { child.stdin.write(JSON.stringify(msg) + '\n'); }
@@ -107,7 +123,15 @@ export const codexBackend: LocalBackend = {
const trimmed = line.trim();
if (!trimmed) return;
let env: any;
- try { env = JSON.parse(trimmed); } catch { return; }
+ try { env = JSON.parse(trimmed); }
+ catch {
+ // codex stdout is supposed to be pure JSON-RPC; a non-JSON
+ // line here means the binary logged something directly to
+ // stdout (rare, but diagnostic-worthy when it happens — we
+ // were swallowing these before).
+ opts.onEvent({ type: 'raw-line', line: trimmed });
+ return;
+ }
// Response (matches a pending request by id).
if (env && typeof env.id === 'number' && pending.has(env.id)) {
const p = pending.get(env.id)!;
@@ -253,6 +277,21 @@ export const codexBackend: LocalBackend = {
return;
}
+ // ── Token-usage streaming pulse ─────────────────────────────
+ // codex 0.125+ emits this notification through a turn whenever
+ // the cumulative token count advances. Strongest 'still alive'
+ // signal short of actual text — surface as a status:'usage'
+ // event the rail can render as a live counter row, and stash
+ // the latest value for the terminal done event.
+ if (method === 'thread/tokenUsage/updated') {
+ const u = extractCodexUsage(params);
+ if (u) {
+ lastUsage = u;
+ opts.onEvent({ type: 'status', status: 'usage', usage: u });
+ }
+ return;
+ }
+
// ── Legacy codex/event protocol (older codex builds) ─────────
if (method === 'codex/event' || method.startsWith('codex/event/')) {
const ev = (params && typeof params === 'object' && typeof params.type === 'string')
@@ -262,9 +301,19 @@ export const codexBackend: LocalBackend = {
return;
}
- // Noise we explicitly drop without surfacing:
- // thread/started, thread/tokenUsage/updated,
- // account/rateLimits/updated, mcpServer/startupStatus/updated
+ // Anything else — surface as a log event. Bucketed noise
+ // (CODEX_DROP_TO_DEBUG) goes at level=debug so it's visible only
+ // with ORKAS_LOG_LEVEL=debug; everything genuinely unknown goes
+ // at level=info so users see what the binary is doing instead
+ // of staring at a quiet rail. Trimmed to keep rail rows short.
+ const lvl: 'debug' | 'info' = CODEX_DROP_TO_DEBUG.has(method) ? 'debug' : 'info';
+ const summary = JSON.stringify(params || {}).slice(0, 200);
+ opts.onEvent({
+ type: 'log',
+ level: lvl,
+ message: `${method}: ${summary}`,
+ source: 'codex',
+ });
}
function handleLegacyCodexEvent(ev: Record<string, any>) {
@@ -333,6 +382,7 @@ export const codexBackend: LocalBackend = {
type: 'done', status,
durationMs: Date.now() - startedAt,
sessionId: threadId,
+ ...(lastUsage ? { usage: lastUsage } : {}),
...extra,
});
resolveOuter();
@@ -442,3 +492,49 @@ export function extractThreadId(result: any): string | undefined {
if (result.thread && typeof result.thread.id === 'string' && result.thread.id) return result.thread.id;
return undefined;
}
+
+/** Extract token usage from a `thread/tokenUsage/updated` notification's
+ * params block. Codex flips between snake_case and camelCase across
+ * versions and wraps the counters under `usage` / `info.totalTokenUsage`
+ * / `info.lastTokenUsage`; we accept all observed shapes and produce
+ * the normalized `{input, output, cacheRead, cacheCreate, model}`
+ * payload the rest of the system speaks. Returns undefined when no
+ * recognizable numeric field is present.
+ *
+ * Exposed for unit testing. */
+export function extractCodexUsage(params: any): undefined | Record<string, number | string> {
+ if (!params || typeof params !== 'object') return undefined;
+ const candidates: any[] = [];
+ if (params.usage) candidates.push(params.usage);
+ if (params.info?.totalTokenUsage) candidates.push(params.info.totalTokenUsage);
+ if (params.info?.lastTokenUsage) candidates.push(params.info.lastTokenUsage);
+ if (params.payload?.info?.totalTokenUsage) candidates.push(params.payload.info.totalTokenUsage);
+ if (params.payload?.info?.lastTokenUsage) candidates.push(params.payload.info.lastTokenUsage);
+ // Bare params block can itself carry the fields when codex inlines them.
+ candidates.push(params);
+
+ for (const c of candidates) {
+ if (!c || typeof c !== 'object') continue;
+ const input = pickNum(c, ['input_tokens', 'inputTokens']);
+ const output = pickNum(c, ['output_tokens', 'outputTokens']);
+ const cacheRead = pickNum(c, ['cache_read_input_tokens', 'cacheReadInputTokens', 'cached_input_tokens', 'cachedInputTokens']);
+ const cacheCreate = pickNum(c, ['cache_creation_input_tokens', 'cacheCreationInputTokens']);
+ if (input === undefined && output === undefined && cacheRead === undefined && cacheCreate === undefined) continue;
+ const out: Record<string, number | string> = {};
+ if (input !== undefined) out.input = input;
+ if (output !== undefined) out.output = output;
+ if (cacheRead !== undefined) out.cacheRead = cacheRead;
+ if (cacheCreate !== undefined) out.cacheCreate = cacheCreate;
+ const model = params.model || params.info?.model || params.payload?.info?.model || params.payload?.model;
+ if (typeof model === 'string' && model) out.model = model;
+ return out;
+ }
+ return undefined;
+}
+
+function pickNum(o: Record<string, any>, keys: string[]): number | undefined {
+ for (const k of keys) {
+ if (typeof o[k] === 'number' && Number.isFinite(o[k])) return o[k];
+ }
+ return undefined;
+}
diff --git a/src/main/features/local_agents/backends/openclaw.ts b/src/main/features/local_agents/backends/openclaw.ts
index 7a330f9e..5e2f0dff 100644
--- a/src/main/features/local_agents/backends/openclaw.ts
+++ b/src/main/features/local_agents/backends/openclaw.ts
@@ -131,8 +131,9 @@ export const openclawBackend: LocalBackend = {
opts.onEvent({ type: 'text-delta', text: replyText });
}
+ const usage = parsed?.usage;
if (code === 0 && replyText) {
- return finish('completed', { output: replyText, sessionId: sid });
+ return finish('completed', { output: replyText, sessionId: sid, ...(usage ? { usage } : {}) });
}
if (code === 0 && !replyText) {
// Exit clean but no parseable reply → treat as failed so
@@ -142,6 +143,7 @@ export const openclawBackend: LocalBackend = {
output: '',
sessionId: sid,
stderrTail: tail.toString(),
+ ...(usage ? { usage } : {}),
});
}
finish('failed', {
@@ -149,6 +151,7 @@ export const openclawBackend: LocalBackend = {
output: replyText,
sessionId: sid,
stderrTail: tail.toString(),
+ ...(usage ? { usage } : {}),
});
});
});
@@ -192,7 +195,7 @@ function stripAnsi(s: string): string {
*/
export function parseOpenclawReply(stderrText: string):
| null
- | { text: string; sessionId?: string; error?: string } {
+ | { text: string; sessionId?: string; error?: string; usage?: Record<string, number | string> } {
if (!stderrText) return null;
const clean = stripAnsi(stderrText);
@@ -219,7 +222,11 @@ export function parseOpenclawReply(stderrText: string):
const sessionId = obj.meta?.agentMeta?.sessionId
|| obj.meta?.sessionId
|| undefined;
- return { text, sessionId };
+ const usage = _extractOpenclawUsage(
+ obj.meta?.agentMeta?.usage || obj.meta?.usage,
+ obj.meta?.agentMeta?.model || obj.meta?.agentMeta?.provider,
+ );
+ return { text, sessionId, ...(usage ? { usage } : {}) };
}
if (obj && typeof obj === 'object' && typeof obj.error === 'string') {
return { text: '', error: String(obj.error) };
@@ -228,6 +235,40 @@ export function parseOpenclawReply(stderrText: string):
return null;
}
+/** Normalize openclaw's `meta.agentMeta.usage` block (or a fallback at
+ * `meta.usage`) into our shared usage shape. openclaw passes through
+ * whatever the upstream provider returned (Anthropic / OpenAI / etc.),
+ * so the keys are snake_case or camelCase depending on provider. We
+ * accept the most common spellings. Returns undefined when no number
+ * was extractable. Exposed indirectly via parseOpenclawReply tests. */
+function _extractOpenclawUsage(
+ raw: any,
+ model: string | undefined,
+): undefined | Record<string, number | string> {
+ if (!raw || typeof raw !== 'object') return undefined;
+ const input = _num(raw.input_tokens, raw.inputTokens, raw.prompt_tokens);
+ const output = _num(raw.output_tokens, raw.outputTokens, raw.completion_tokens);
+ const cacheRead = _num(raw.cache_read_input_tokens, raw.cacheReadInputTokens, raw.cached_input_tokens);
+ const cacheCreate = _num(raw.cache_creation_input_tokens, raw.cacheCreationInputTokens);
+ if (input === undefined && output === undefined && cacheRead === undefined && cacheCreate === undefined) {
+ return undefined;
+ }
+ const out: Record<string, number | string> = {};
+ if (input !== undefined) out.input = input;
+ if (output !== undefined) out.output = output;
+ if (cacheRead !== undefined) out.cacheRead = cacheRead;
+ if (cacheCreate !== undefined) out.cacheCreate = cacheCreate;
+ if (typeof model === 'string' && model) out.model = model;
+ return out;
+}
+
+function _num(...vals: any[]): number | undefined {
+ for (const v of vals) {
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
+ }
+ return undefined;
+}
+
function findMatchingBrace(s: string, openIdx: number): number {
let depth = 0;
let inStr = false;
diff --git a/src/main/features/local_agents/backends/opencode.ts b/src/main/features/local_agents/backends/opencode.ts
index 44198a8d..35786f6b 100644
--- a/src/main/features/local_agents/backends/opencode.ts
+++ b/src/main/features/local_agents/backends/opencode.ts
@@ -44,6 +44,10 @@ export const opencodeBackend: LocalBackend = {
let resultStatus: 'completed' | 'failed' | undefined;
let resultError: string | undefined;
let observedSessionId: string | undefined;
+ // Most-recent per-step usage snapshot; step_finish events fire
+ // throughout the turn, each carrying the cumulative-so-far. We
+ // forward the latest as `done.usage` at termination.
+ let lastUsage: Record<string, number | string> | undefined;
opts.onEvent({
type: 'process-info',
@@ -70,7 +74,13 @@ export const opencodeBackend: LocalBackend = {
const trimmed = line.trim();
if (!trimmed) return;
let obj: any;
- try { obj = JSON.parse(trimmed); } catch { return; }
+ try { obj = JSON.parse(trimmed); }
+ catch {
+ // Non-NDJSON line on stdout — surface so users see CLI's
+ // own logging / startup banner instead of a silent gap.
+ opts.onEvent({ type: 'raw-line', line: trimmed });
+ return;
+ }
const ev = mapOpencodeEvent(obj);
if (ev?.captureSessionId) observedSessionId = ev.captureSessionId;
if (ev?.event) {
@@ -78,6 +88,10 @@ export const opencodeBackend: LocalBackend = {
if (ev.event.type === 'text-delta' && typeof (ev.event as any).text === 'string') {
textOut += (ev.event as any).text as string;
}
+ if (ev.event.type === 'status' && (ev.event as any).status === 'usage') {
+ const u = (ev.event as any).usage;
+ if (u && typeof u === 'object') lastUsage = u;
+ }
}
if (ev?.terminal) {
resultStatus = ev.terminal.status;
@@ -104,6 +118,7 @@ export const opencodeBackend: LocalBackend = {
type: 'done', status,
durationMs: Date.now() - startedAt,
sessionId: observedSessionId,
+ ...(lastUsage ? { usage: lastUsage } : {}),
...extra,
});
resolve();
@@ -192,14 +207,75 @@ export function mapOpencodeEvent(obj: any):
out!.terminal = { status: 'failed', error: String(msg) };
return out;
}
- case 'step_finish':
- // Token usage event; nothing to surface (we don't track usage
- // for CLI calls in archive context yet).
+ case 'step_finish': {
+ // Carries per-step token usage. Surface as a status:'usage' event
+ // when we can pull numbers out, so the rail renders a live
+ // running counter; otherwise fall back to a debug log so users
+ // still see that a step completed.
+ const usage = extractOpencodeUsage(obj.part || obj);
+ if (usage) {
+ out!.event = { type: 'status', status: 'usage', usage };
+ } else {
+ out!.event = {
+ type: 'log',
+ level: 'debug',
+ message: `step_finish: ${JSON.stringify(obj.part || obj).slice(0, 160)}`,
+ source: 'opencode',
+ };
+ }
return out;
+ }
case 'step_start':
out!.event = { type: 'status', status: 'running' };
return out;
default:
+ // Genuinely unknown opencode event — keep visible at level=info
+ // so we notice when the wire format drifts (matches the codex
+ // treatment).
+ if (typeof obj.type === 'string' && obj.type) {
+ out!.event = {
+ type: 'log',
+ level: 'info',
+ message: `${obj.type}: ${JSON.stringify(obj).slice(0, 200)}`,
+ source: 'opencode',
+ };
+ return out;
+ }
return out!.captureSessionId ? out : undefined;
}
}
+
+/** Extract token usage from an opencode `step_finish` event's `part`
+ * block. Opencode's wire format isn't entirely stable across versions;
+ * we accept the shapes observed in practice (tokens nested under
+ * `tokens.{input,output,cache}`) and inline at the top level.
+ * Exposed for unit testing. */
+export function extractOpencodeUsage(part: any): undefined | Record<string, number | string> {
+ if (!part || typeof part !== 'object') return undefined;
+ const candidates: any[] = [];
+ if (part.tokens) candidates.push(part.tokens);
+ if (part.usage) candidates.push(part.usage);
+ candidates.push(part);
+ for (const c of candidates) {
+ if (!c || typeof c !== 'object') continue;
+ const input = numOrUndef(c.input, c.inputTokens, c.input_tokens);
+ const output = numOrUndef(c.output, c.outputTokens, c.output_tokens);
+ const cacheRead = numOrUndef(c.cache, c.cacheRead, c.cache_read, c.cache_read_input_tokens);
+ if (input === undefined && output === undefined && cacheRead === undefined) continue;
+ const out: Record<string, number | string> = {};
+ if (input !== undefined) out.input = input;
+ if (output !== undefined) out.output = output;
+ if (cacheRead !== undefined) out.cacheRead = cacheRead;
+ const model = part.model || part.providerID || part.modelID;
+ if (typeof model === 'string' && model) out.model = model;
+ return out;
+ }
+ return undefined;
+}
+
+function numOrUndef(...vals: any[]): number | undefined {
+ for (const v of vals) {
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
+ }
+ return undefined;
+}
diff --git a/src/main/features/local_agents/runner.ts b/src/main/features/local_agents/runner.ts
index c708340a..f3e5b815 100644
--- a/src/main/features/local_agents/runner.ts
+++ b/src/main/features/local_agents/runner.ts
@@ -26,6 +26,8 @@ import { opencodeBackend } from './backends/opencode.js';
import { hermesBackend } from './backends/hermes.js';
import { type LocalBackend, type LocalEvent } from './backends/base.js';
import * as persist from './persist.js';
+import { sessionToolResultsDir } from '../../paths.js';
+import { maybeSpillToolResult } from '../../util/tool-result-cap.js';
const log = createLogger('local-agents:runner');
@@ -42,6 +44,55 @@ function resolveTimeoutMs(): number {
return n;
}
+/** How long the runner waits without seeing ANY backend event before
+ * emitting an `idle` heartbeat. The ticker below fires every
+ * `IDLE_TICK_MS`; the first emit happens once
+ * `now - lastEventAt > threshold`. Default 90 s because a thinking
+ * turn between tool calls runs ~10-40 s — 90 s comfortably skips real
+ * activity and catches genuine stalls. Backends with no streaming at
+ * all (openclaw) pass a smaller value via `BackendRunOptions.idleMs`. */
+const DEFAULT_IDLE_MS = 90 * 1000;
+const DEFAULT_IDLE_TICK_MS = 30 * 1000;
+/** Lower bound on user-supplied / backend-supplied idle thresholds so a
+ * misconfigured value can't drum the rail every second. Tests can
+ * shrink this through `ORKAS_LOCAL_AGENT_IDLE_MIN_MS` to exercise the
+ * heartbeat at a manageable speed; production never sets it. */
+const MIN_IDLE_MS_DEFAULT = 30 * 1000;
+
+function envNum(name: string): number | undefined {
+ const raw = process.env[name];
+ if (!raw) return undefined;
+ const n = Number(raw);
+ return Number.isFinite(n) ? n : undefined;
+}
+
+function resolveIdleMs(backendHint: number | undefined): number {
+ const minMs = envNum('ORKAS_LOCAL_AGENT_IDLE_MIN_MS') ?? MIN_IDLE_MS_DEFAULT;
+ const candidates: Array<number | undefined> = [
+ backendHint,
+ envNum('ORKAS_LOCAL_AGENT_IDLE_MS'),
+ ];
+ for (const c of candidates) {
+ if (c !== undefined && c >= minMs) return c;
+ }
+ return Math.max(DEFAULT_IDLE_MS, minMs);
+}
+
+function resolveIdleTickMs(idleMs: number): number {
+ // Tick at most every 30 s; for very short thresholds (tests, or a
+ // future short-idleMs backend) divide so the user sees ~3 pulses
+ // before the threshold is reached.
+ return Math.min(DEFAULT_IDLE_TICK_MS, Math.max(50, Math.floor(idleMs / 3)));
+}
+
+/** Default idle threshold per backend. Override only when the backend
+ * semantics deviate from "streams events through the turn"; today
+ * openclaw is the only one (no streaming at all — see openclaw.ts
+ * header). */
+const BACKEND_IDLE_MS: Partial<Record<LocalCliType, number>> = {
+ openclaw: 30 * 1000,
+};
+
const BACKENDS: Partial<Record<LocalCliType, LocalBackend>> = {
claude: claudeBackend,
codex: codexBackend,
@@ -108,7 +159,48 @@ export async function run(opts: RunCliAgentOpts): Promise<RunCliAgentResult> {
// a renderer crash mid-run still leaves a complete jsonl trail.
let streamedOutput = '';
let terminal: { status: RunCliAgentResult['status']; output?: string; error?: string; sessionId?: string } | null = null;
+ // Buffer events for the devtools archive so the debug panel sees CLI
+ // dispatches alongside core-agent calls. Translation = LocalEvent →
+ // dispatch start so the panel can render a relative timeline.
+ const archiveAppend = (e: LocalEvent) => {
+ archiveEvents.push({
+ t: Date.now() - startedAtMs,
+ type: e.type,
+ data: { ...e } as unknown as Record<string, unknown>,
+ });
+ };
+ const idleThresholdMs = resolveIdleMs(BACKEND_IDLE_MS[opts.cli]);
+ // CLI dispatch session id (matches the devtools-archive session id
+ // built below). The per-session spill dir is anchored on this so
+ // sweep / read paths can find the file again.
+ const cliSessionId = `${opts.uid}-cli-${opts.cli}-${handle.runId}`;
+ const spillDir = sessionToolResultsDir(opts.uid, cliSessionId);
+ let lastEventAt = Date.now();
const onEvent = (e: LocalEvent) => {
+ // Self-emitted idle pulses don't count as "the CLI did something"
+ // — without this carve-out we'd reset our own deadline and stop
+ // pulsing during a real stall.
+ if (e.type !== 'idle') lastEventAt = Date.now();
+ // Tool-event result phase: spill oversized output to disk before
+ // it lands in events.jsonl / the renderer stream. Above 50 KB the
+ // raw bash output bloats the persistence log and the renderer
+ // memory; the spill keeps a head+tail preview inline (matching
+ // the in-process tool-result spill format) and exposes the full
+ // path via `outputPath` for click-to-expand. Backends don't know
+ // about this — they always emit the full output.
+ if (e.type === 'tool-event' && (e as any).phase === 'result' && typeof (e as any).output === 'string') {
+ const { output, outputPath } = maybeSpillToolResult({
+ toolResultsDir: spillDir,
+ toolName: String((e as any).tool || 'tool'),
+ callId: String((e as any).callId || ''),
+ output: (e as any).output as string,
+ });
+ // Rewrite in place so the persisted event and the forwarded
+ // event match exactly — no divergence between disk replay and
+ // live render.
+ (e as any).output = output;
+ if (outputPath) (e as any).outputPath = outputPath;
+ }
persist.append(handle, e);
if (e.type === 'text-delta' && typeof e.text === 'string') {
streamedOutput += e.text;
@@ -125,6 +217,21 @@ export async function run(opts: RunCliAgentOpts): Promise<RunCliAgentResult> {
opts.onEvent(e);
};
+ // Idle ticker — purely informational; never kills the process. The
+ // existing 20-minute wall-clock timeout stays the only kill path. We
+ // re-emit at IDLE_TICK_MS cadence so the user gets a steady drumbeat
+ // ("○ no output for 30s" repeated) confirming the run is still
+ // ostensibly alive, rather than a single heartbeat that ages out.
+ const idleTickMs = resolveIdleTickMs(idleThresholdMs);
+ const idleTimer = setInterval(() => {
+ if (terminal) return; // run already finished, don't keep pulsing
+ const stalledMs = Date.now() - lastEventAt;
+ if (stalledMs > idleThresholdMs) {
+ onEvent({ type: 'idle', stalledMs });
+ }
+ }, idleTickMs);
+ if (typeof idleTimer.unref === 'function') idleTimer.unref();
+
try {
await backend.run({
binPath: entry.path,
@@ -136,6 +243,7 @@ export async function run(opts: RunCliAgentOpts): Promise<RunCliAgentResult> {
signal: opts.signal,
onEvent,
timeoutMs: resolveTimeoutMs(),
+ idleMs: BACKEND_IDLE_MS[opts.cli],
});
} catch (err) {
const msg = (err as Error).message || String(err);
@@ -145,6 +253,8 @@ export async function run(opts: RunCliAgentOpts): Promise<RunCliAgentResult> {
}
}
+ clearInterval(idleTimer);
+
// Backends are required to emit a `done` — if missing, treat as
// failure so callers don't hang on an absent terminal event.
if (!terminal) {
diff --git a/src/main/features/marketplace.ts b/src/main/features/marketplace.ts
index 30fa7e6f..36c68ba3 100644
--- a/src/main/features/marketplace.ts
+++ b/src/main/features/marketplace.ts
@@ -51,6 +51,7 @@ import {
userMarketplaceDirCloud,
} from '../paths';
import { getActiveUserId } from './users';
+import { getCurrentLang } from '../i18n';
import { invalidateSkills as invalidateCoreAgentSkills } from '../model/core-agent/skill-registry';
import {
getSkillCacheDir, isCacheFresh, readAgentCache, touchCacheEntry,
@@ -58,7 +59,6 @@ import {
} from './marketplace_cache';
import {
addAgentInstall, addSkillInstall, removeAgentInstall, removeSkillInstall,
- readInstalls, writeInstalls,
} from './marketplace_installs';
import { createLogger } from '../logger';
@@ -68,13 +68,14 @@ const log = createLogger('marketplace');
// Profile-driven (mirrors Server `env/start/{dev_,}api_start.sh` — see PC/CLAUDE.md §1 +
// Server CLAUDE.md §7): `ORKAS_PROFILE=global` (default) routes to overseas (`orkas.ai`),
// `ORKAS_PROFILE=cn` routes to China (`orkas.work`). `run.sh` exports the env from its
-// positional arg (`./run.sh cn`). Devs running against a local Server can still override
-// the entire base via `ORKAS_API_BASE_URL=http://127.0.0.1:8888/api ./run.sh`.
+// positional arg (`./run.sh cn`). An explicit `ORKAS_API_BASE_URL` always wins.
//
-// **No build-mode branch on purpose** — OrkasOpen contract (per
-// `OpenSource/SyncCode/strip-rules.json`) bans build-mode checks outside the two
-// whitelisted infra files, and "dev vs packaged behavior must be identical". Profile +
-// env override are the explicit knobs.
+// **No build-mode branch in this file on purpose** — OrkasOpen contract (per
+// `OpenSource/SyncCode/strip-rules.json`) bans `app.isPackaged` checks outside the two
+// whitelisted infra files. The "dev → local Server" default is set ONCE in `index.ts`
+// (which IS whitelisted) by pinning `process.env.ORKAS_API_BASE_URL=http://127.0.0.1:8888/api`
+// when `!app.isPackaged`, so every API base resolver picks it up uniformly — no scattered
+// build-mode logic in feature modules.
const PROFILE_BASES: Record<string, string> = {
global: 'https://www.orkas.ai/api',
cn: 'https://www.orkas.work/api',
@@ -89,10 +90,13 @@ export function apiBase(): string {
// ── envelope ──────────────────────────────────────────────────────────────
interface Envelope { code: number; msg?: string; [k: string]: unknown }
-async function postJson<T>(p: string, body: unknown): Promise<T> {
+export async function postJson<T>(p: string, body: unknown): Promise<T> {
const res = await fetch(`${apiBase()}${p}`, {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Accept-Language': getCurrentLang(),
+ },
body: JSON.stringify(body || {}),
});
const text = await res.text();
@@ -475,79 +479,6 @@ export async function ensureDefaultInstalls(uid: string): Promise<{ seeded_agent
}
}
-// ── one-time backfill for older install records ──────────────────────────
-// Earlier install paths (predating the create_uid + version persistence) wrote manifest
-// rows + `_install.json` files without those fields. The UI surfaces the author badge +
-// version chip from `_install.json`, so older records render blank chips. Backfill is a
-// startup pass: for every manifest row missing `create_uid`, look it up in the catalog and
-// rewrite both the manifest entry and the per-machine `_install.json`. Idempotent — once
-// every row is populated, the function short-circuits with no network call.
-//
-// We use the catalog `/list` endpoint (cheap, no side-effects) instead of `/detail` (which
-// increments download_count). The first page (size=100) covers current scale; pagination can
-// be added when the published catalog exceeds that.
-export async function backfillMarketplaceCreateUid(uid: string): Promise<void> {
- let manifest;
- try { manifest = await readInstalls(uid); } catch { return; }
- const agentMissing = manifest.agents.filter((a) => !a.create_uid);
- const skillMissing = manifest.skills.filter((s) => !s.create_uid);
- if (!agentMissing.length && !skillMissing.length) return;
-
- // Build (id → create_uid) maps by pulling the catalog list (paginated up to 200 rows total).
- const agentMap = agentMissing.length ? await _fetchCreateUidMap('agents') : new Map<string, string>();
- const skillMap = skillMissing.length ? await _fetchCreateUidMap('skills') : new Map<string, string>();
-
- let touched = false;
- for (const a of agentMissing) {
- const cuid = agentMap.get(a.id);
- if (cuid === undefined) continue;
- a.create_uid = cuid;
- await _patchInstallMeta(userMarketplaceAgentDir(uid, a.id), { create_uid: cuid, version: a.version });
- touched = true;
- }
- for (const s of skillMissing) {
- const cuid = skillMap.get(s.id);
- if (cuid === undefined) continue;
- s.create_uid = cuid;
- await _patchInstallMeta(userMarketplaceSkillDir(uid, s.id), { create_uid: cuid, version: s.version });
- touched = true;
- }
- if (touched) {
- await writeInstalls(uid, manifest);
- log.info(`backfilled create_uid: ${agentMissing.length} agent(s) + ${skillMissing.length} skill(s)`);
- }
-}
-
-async function _fetchCreateUidMap(kind: 'agents' | 'skills'): Promise<Map<string, string>> {
- const out = new Map<string, string>();
- try {
- // Two pages of 100 = 200 rows; sufficient for current marketplace size.
- for (let page = 1; page <= 2; page++) {
- const r = await postJson<{ list: Array<{ id: string; create_uid?: string }>; total: number }>(
- `/marketplace/${kind}/list`, { page, size: 100 },
- );
- for (const row of r.list || []) {
- if (row && typeof row.id === 'string') out.set(row.id, row.create_uid || '');
- }
- if ((r.list || []).length < 100) break;
- }
- } catch (err) {
- log.warn(`backfill ${kind} catalog fetch failed: ${(err as Error).message}`);
- }
- return out;
-}
-
-async function _patchInstallMeta(dir: string, patch: { create_uid: string; version: string }): Promise<void> {
- const f = path.join(dir, '_install.json');
- if (!fs.existsSync(f)) return;
- try {
- const j = JSON.parse(await fsp.readFile(f, 'utf8'));
- j.create_uid = patch.create_uid;
- if (!j.version) j.version = patch.version;
- await fsp.writeFile(f, JSON.stringify(j, null, 2), 'utf8');
- } catch { /* corrupt _install.json — skip; reconcile will rewrite on next version bump */ }
-}
-
// ── uninstall (user-facing; non-dev) ──────────────────────────────────────
// Removes the per-machine install copy + manifest entry. **Does NOT touch the server row**
// (different from `marketplace_dev.deleteMarketplace*` which wipes COS + DB). After this runs:
diff --git a/src/main/features/marketplace_reconcile.ts b/src/main/features/marketplace_reconcile.ts
index 222ac0e7..f849e2ff 100644
--- a/src/main/features/marketplace_reconcile.ts
+++ b/src/main/features/marketplace_reconcile.ts
@@ -20,9 +20,12 @@ import * as path from 'node:path';
import {
userMarketplaceAgentDir, userMarketplaceSkillDir,
} from '../paths';
-import { readInstalls, type AgentInstall, type SkillInstall } from './marketplace_installs';
+import {
+ readInstalls, addAgentInstall, addSkillInstall,
+ type AgentInstall, type SkillInstall,
+} from './marketplace_installs';
import { invalidateSkills as invalidateCoreAgentSkills } from '../model/core-agent/skill-registry';
-import { extractBundleSafely } from './marketplace';
+import { extractBundleSafely, postJson } from './marketplace';
import { createLogger } from '../logger';
const log = createLogger('marketplace_reconcile');
@@ -67,6 +70,93 @@ function _setStatus(next: ReconcileStatus): void {
}
}
+/** Pre-reconcile step: sync the local cloud manifest against the server catalog. For every
+ * installed item, look up the server's current (version, published_at). When the server has
+ * newer values, write them back into the manifest — the subsequent `reconcileInstalls` pass
+ * then detects the mismatch against per-machine `_install.json` and re-pulls the blob.
+ *
+ * Side effects: at most one `addAgentInstall` / `addSkillInstall` write per changed row,
+ * each going through the same per-uid lock as user-initiated installs. Items absent from the
+ * server catalog (e.g. admin-deleted) are left untouched — auto-uninstall stays user-explicit.
+ *
+ * Network failures are swallowed (offline boot must not block the rest of startup); the next
+ * launch retries.
+ */
+export async function checkServerUpdatesForInstalls(uid: string): Promise<{ updated_agents: number; updated_skills: number }> {
+ const manifest = await readInstalls(uid);
+ if (manifest.agents.length === 0 && manifest.skills.length === 0) {
+ return { updated_agents: 0, updated_skills: 0 };
+ }
+
+ let agentMap: Map<string, _CatalogRow>;
+ let skillMap: Map<string, _CatalogRow>;
+ try {
+ [agentMap, skillMap] = await Promise.all([
+ _fetchServerCatalogMap('agents'),
+ _fetchServerCatalogMap('skills'),
+ ]);
+ } catch (err) {
+ log.warn(`server-check fetch failed (offline?): ${(err as Error).message}`);
+ return { updated_agents: 0, updated_skills: 0 };
+ }
+
+ let updated_agents = 0;
+ let updated_skills = 0;
+ for (const a of manifest.agents) {
+ const server = agentMap.get(a.id);
+ if (!server) continue;
+ if (server.version !== a.version || server.published_at !== a.published_at) {
+ log.info(`server-update agent ${a.id}: v${a.version} → v${server.version} (published_at ${a.published_at} → ${server.published_at})`);
+ // Replace the row in the manifest; reconcile will detect the version/published_at
+ // mismatch against `_install.json` and re-pull. agent_json_url is reused (server
+ // overwrites the same COS key on republish — see Server `api/marketplace.py::upload_agent`).
+ await addAgentInstall(uid, {
+ id: a.id, version: server.version, published_at: server.published_at,
+ agent_json_url: a.agent_json_url, create_uid: a.create_uid,
+ });
+ updated_agents++;
+ }
+ }
+ for (const s of manifest.skills) {
+ const server = skillMap.get(s.id);
+ if (!server) continue;
+ if (server.version !== s.version || server.published_at !== s.published_at) {
+ log.info(`server-update skill ${s.id}: v${s.version} → v${server.version} (published_at ${s.published_at} → ${server.published_at})`);
+ await addSkillInstall(uid, {
+ id: s.id, version: server.version, published_at: server.published_at,
+ bundle_url: s.bundle_url, create_uid: s.create_uid,
+ });
+ updated_skills++;
+ }
+ }
+ if (updated_agents + updated_skills > 0) {
+ log.info(`server-check: ${updated_agents} agent(s) + ${updated_skills} skill(s) marked for update`);
+ }
+ return { updated_agents, updated_skills };
+}
+
+interface _CatalogRow { version: string; published_at: number }
+
+/** Paginate the public `/marketplace/{kind}/list` endpoint and collapse to (id → version + ts).
+ * Page-size 100 × 20 pages = 2000 row cap (well above current catalog scale). */
+async function _fetchServerCatalogMap(kind: 'agents' | 'skills'): Promise<Map<string, _CatalogRow>> {
+ const out = new Map<string, _CatalogRow>();
+ const PAGE_SIZE = 100;
+ for (let page = 1; page <= 20; page++) {
+ const r = await postJson<{ list: Array<{ id?: string; version?: string; published_at?: number }>; total?: number }>(
+ `/marketplace/${kind}/list`, { page, size: PAGE_SIZE },
+ );
+ const list = r.list || [];
+ for (const row of list) {
+ if (typeof row.id === 'string' && typeof row.version === 'string' && typeof row.published_at === 'number') {
+ out.set(row.id, { version: row.version, published_at: row.published_at });
+ }
+ }
+ if (list.length < PAGE_SIZE) break;
+ }
+ return out;
+}
+
/** Read manifest + reconcile every entry in parallel. Returns counts for logging. Emits status
* updates through the subscribe channel so the renderer can show a "syncing" banner. */
export async function reconcileInstalls(uid: string): Promise<{ pulled_agents: number; pulled_skills: number; failed: string[] }> {
diff --git a/src/main/features/users.ts b/src/main/features/users.ts
index 1b03c032..fee19240 100644
--- a/src/main/features/users.ts
+++ b/src/main/features/users.ts
@@ -32,6 +32,7 @@ import { createLogger } from '../logger';
import { sweepToolResults } from '../util/tool-result-cap';
import { migrateLegacySessionIds } from '../util/migrate-session-ids';
import { migrateAgentLayout } from '../util/migrate-agent-layout';
+import { migrateKbToLocalContexts } from '../util/migrate-kb-to-local';
const log = createLogger('users');
@@ -131,6 +132,12 @@ export function activateUser(uid: string): void {
try { migrateAgentLayout(uid); }
catch (err) { log.warn(`migrateAgentLayout uid=${uid}: ${(err as Error).message}`); }
+ // KB vector store moved from cloud/contexts/.kb → local/contexts/.kb
+ // (multi-device-sync batch 2 — index is machine-private, never crosses
+ // devices). Idempotent + stamped. See util/migrate-kb-to-local.ts.
+ try { migrateKbToLocalContexts(uid); }
+ catch (err) { log.warn(`migrateKbToLocalContexts uid=${uid}: ${(err as Error).message}`); }
+
// Pin core-agent's auth/state dir to this uid's local/config/.
// `resolveAuthDir()` re-reads this env var on every call (see
// core-agent/src/auth/store.ts::resolveAuthDir), so switching at runtime is
diff --git a/src/main/index.ts b/src/main/index.ts
index 4964ded8..5b76dbea 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -34,6 +34,17 @@ import { app, BrowserWindow, Menu, ipcMain, nativeImage, protocol, shell } from
// edge case where productName isn't picked up early.
app.setName('Orkas');
+// Dev = local Server. The PC has three API base resolvers (`features/account/server.ts`,
+// `ORKAS_API_BASE_URL` env var first — pinning it here once means every business call routes to
+// the local Server when running unpackaged (no scattered build-mode branches in feature modules).
+// Packaged builds: not set → each resolver falls back to its profile/prod default.
+// Explicit launcher env (`./dev.sh`, `ORKAS_API_BASE_URL=… ./run.sh`) wins, so a dev can still
+// repro a bug against a remote Server. `app.isPackaged` here is allowlisted in
+// `OpenSource/SyncCode/strip-rules.json::isPackaged_allowed_files`.
+if (!app.isPackaged && !process.env.ORKAS_API_BASE_URL) {
+ process.env.ORKAS_API_BASE_URL = 'http://127.0.0.1:8888/api';
+}
+
// Register the KB file protocol BEFORE `app.whenReady()` — privileged
// schemes can't be added after. `kb-file:///<relpath>` serves a single
// file out of the current active user's `<uid>/cloud/contexts/`. Used by
@@ -122,6 +133,8 @@ 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).
+
function createWindow(): BrowserWindow {
const dev = !app.isPackaged;
@@ -203,6 +216,26 @@ function registerIpc(): void {
ipcMain.handle('orkas.appVersion', () => app.getVersion());
+ // Synchronous boot bundle for i18n. Renderer's preload calls this via
+ // `ipcRenderer.sendSync` BEFORE any DOM scripts run, so the renderer can
+ // populate _currentLang + _tables synchronously at module load — first
+ // paint shows the user's preferred language with no English flash. Using
+ // sendSync (and not the async `config.getLanguage` IPC) is the whole point:
+ // an async round-trip schedules a microtask, paint slips through. Reads
+ // ~100 KB of locale JSON per renderer boot; SSD-fast.
+ 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 } };
+ } catch (err) {
+ log.warn('bootI18n failed', { error: (err as Error)?.message });
+ event.returnValue = { ok: false };
+ }
+ });
+
ipcMain.handle('orkas.diagnostics', async () => {
const sample = {
nowIso: storage.nowIso(),
@@ -526,8 +559,20 @@ function registerChatMediaProtocol(): void {
if (host === 'local') {
// pathname starts with `/`; on Windows the drive-letter prefix needs
// that leading slash stripped. `_pathnameToAbsPath` handles both.
+ // Try media (image/video) first; fall through to preview (pdf/html)
+ // on bad-ext only — every other failure (not_found / too_large) is
+ // terminal, so we don't mask a real error by re-checking under a
+ // different bucket.
const abs = _pathnameToAbsPath(u.pathname || '');
- const resolved = chatAttachments.resolveLocalMediaPath(abs);
+ let resolved: ReturnType<typeof chatAttachments.resolveLocalMediaPath>
+ | ReturnType<typeof chatAttachments.resolveLocalPreviewPath>
+ = chatAttachments.resolveLocalMediaPath(abs);
+ if (!resolved.ok && (resolved as { code?: string }).code === 'bad_input') {
+ // Only retry under preview when the media resolver rejected on extension;
+ // path validation errors ('path must be absolute' / 'path required') re-raise.
+ const previewTry = chatAttachments.resolveLocalPreviewPath(abs);
+ if (previewTry.ok) resolved = previewTry;
+ }
if (!resolved.ok) {
// Same `(x as {field?: T}).field` access pattern as the cid branch above —
// tsc's narrow on `if (!resolved.ok)` doesn't always propagate to the
@@ -743,23 +788,17 @@ if (!gotLock) {
m.subscribeReconcileStatus((status) => {
ipc.broadcastToRenderer('marketplace:reconcile-status', status);
});
+ // Server-side update sweep runs first so the manifest leads the per-machine
+ // `_install.json` for items the admin has republished — reconcile then picks up the
+ // mismatch and re-pulls the new blob. Network failures here are swallowed by the
+ // helper itself; reconcile still runs against the stale manifest.
+ await m.checkServerUpdatesForInstalls(users.getActiveUserId());
await m.reconcileInstalls(users.getActiveUserId());
} catch (err) {
createLogger('marketplace_reconcile').warn('startup reconcile failed', {
error: (err as Error).message,
});
}
- try {
- // Backfill `create_uid` / `version` for older install records (predates those fields
- // being persisted). Idempotent — no-op when every row already has the field. Runs after
- // reconcile so any freshly-pulled record already has the fields and the backfill skips it.
- const mp = await import('./features/marketplace');
- await mp.backfillMarketplaceCreateUid(users.getActiveUserId());
- } catch (err) {
- createLogger('marketplace_backfill').warn('startup backfill failed', {
- error: (err as Error).message,
- });
- }
})();
app.on('activate', () => {
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 7da0fc00..ac56ce70 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -51,7 +51,7 @@ import { createLogger, logFromRenderer } from '../logger';
import * as path from 'node:path';
import * as fs from 'node:fs';
import { shell } from 'electron';
-import { WS_ROOT } from '../paths';
+import { WS_ROOT, chatAttachmentDir } from '../paths';
const log = createLogger('ipc');
@@ -85,6 +85,17 @@ async function _resolveWorkspaceScope(
return undefined;
}
+// Resolve the cid-scoped attachment dir from a renderer payload, when present.
+// The file-tools' allowed-paths scope is "active workspace ∪ this cid's
+// attachment dir" (CLAUDE.md §5); reveal + preview must honour the same
+// union so a user can preview an attachment they uploaded, not just files
+// the LLM wrote into the workspace.
+function _attachmentScopeForPayload(userId: string, payload: any): string | null {
+ if (!payload || typeof payload.cid !== 'string' || !payload.cid) return null;
+ if (!safeId(payload.cid)) return null;
+ return path.resolve(chatAttachmentDir(userId, payload.cid));
+}
+
// ── Invoke handlers ──────────────────────────────────────────────────────
// Contract: `(payload, { userId, sender }) => result` where result is
// merged into a `{ ok: true, ...result }` response. Throw to signal error.
@@ -970,7 +981,10 @@ const invokeHandlers: Record<string, InvokeHandler> = {
const ws = userWorkspace.getWorkspacePath(ctx.userId, projectId);
const norm = path.resolve(target);
const wsNorm = path.resolve(ws);
- if (!norm.startsWith(wsNorm + path.sep) && norm !== wsNorm) {
+ const attachmentScope = _attachmentScopeForPayload(ctx.userId, payload);
+ const inAttachment = !!attachmentScope &&
+ (norm === attachmentScope || norm.startsWith(attachmentScope + path.sep));
+ if (!inAttachment && !norm.startsWith(wsNorm + path.sep) && norm !== wsNorm) {
throw new Error('path is outside the user workspace');
}
if (!fs.existsSync(norm)) throw new Error('file not found');
@@ -978,6 +992,63 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { path: norm };
},
+ // Resolve a per-conversation attachment's absolute path. The renderer's
+ // chip carries (cid, name) but the in-app file viewer's contract is
+ // "abs path in"; we go through `resolveAttachmentAbsPath` so the same
+ // safe-name / traversal / not-a-file gates the chat-media:// handler
+ // already enforces apply here.
+ 'attachments.absPath': async (payload, ctx) => {
+ const cid = payload?.cid;
+ const name = payload?.name;
+ if (typeof cid !== 'string' || !cid) throw new Error('missing cid');
+ if (typeof name !== 'string' || !name) throw new Error('missing name');
+ const r = chatAttachments.resolveAttachmentAbsPath(ctx.userId, cid, name);
+ if (!r.ok) {
+ const err = r as { code?: string; error?: string };
+ return { ok: false, error: err.error || err.code || 'failed' };
+ }
+ return { ok: true, path: r.absPath, kind: r.kind };
+ },
+
+ // Read a file's text content for the in-app preview overlay
+ // (markdown / plain text — pdf and html are streamed via `chat-media://`
+ // instead). Same scope as the file-tools per CLAUDE.md §5: active
+ // workspace ∪ the attachment dir of the current cid. 2 MB cap is
+ // intentional — the whole file is slurped into the JS heap and crosses
+ // IPC, so larger files would balloon the renderer; the caller falls
+ // through to the "too large → open folder" dialog on `error: 'too_large'`.
+ 'produced.readText': async (payload, ctx) => {
+ const target = payload?.path;
+ if (typeof target !== 'string' || !target) {
+ throw new Error('missing path');
+ }
+ const projectId = await _resolveWorkspaceScope(ctx.userId, payload);
+ const ws = userWorkspace.getWorkspacePath(ctx.userId, projectId);
+ const norm = path.resolve(target);
+ const wsNorm = path.resolve(ws);
+ const attachmentScope = _attachmentScopeForPayload(ctx.userId, payload);
+ const inAttachment = !!attachmentScope &&
+ (norm === attachmentScope || norm.startsWith(attachmentScope + path.sep));
+ const inWorkspace = norm === wsNorm || norm.startsWith(wsNorm + path.sep);
+ if (!inWorkspace && !inAttachment) {
+ throw new Error('path is outside the user workspace');
+ }
+ let st: fs.Stats;
+ try { st = fs.statSync(norm); }
+ catch { return { ok: false, error: 'not_found' }; }
+ if (!st.isFile()) return { ok: false, error: 'not_found' };
+ const MAX_TEXT_BYTES = 2 * 1024 * 1024;
+ if (st.size > MAX_TEXT_BYTES) {
+ return { ok: false, error: 'too_large', size: st.size, cap: MAX_TEXT_BYTES };
+ }
+ let text: string;
+ try { text = fs.readFileSync(norm, 'utf8'); }
+ catch (err) { return { ok: false, error: String((err as Error).message || 'read failed') }; }
+ // Strip UTF-8 BOM so markdown / json don't render a leading invisible char.
+ if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1);
+ return { ok: true, text, size: st.size };
+ },
+
// Read the install data root (`<container>/data`) — read-only display
// for the settings page "Data root" row. WS_ROOT is process-stable so
// no async work is needed.
@@ -996,6 +1067,10 @@ const invokeHandlers: Record<string, InvokeHandler> = {
// Discovery + model catalogs only; actual spawning happens inside group_chat
// dispatch via `features/local_agents/runner.ts`, never as a standalone IPC.
...localAgentsHandlers,
+
+ // User-account login (Google / Apple OAuth). Stripped from the OrkasOpen build.
+
+ // Multi-device sync. Stripped from the OrkasOpen build (depends on account).
};
// ── Stream handlers ──────────────────────────────────────────────────────
@@ -1211,12 +1286,12 @@ export function register(): void {
return { ok: true, ...(result || {}) };
} catch (err) {
log.error(`invoke ${channel} failed`, { error: (err as Error)?.message || String(err) });
- const out: { ok: false; error: string; code?: string } = {
+ const out: { ok: false; error: string; code?: string | number } = {
ok: false,
error: (err as Error).message || String(err),
};
const code = (err as { code?: unknown }).code;
- if (typeof code === 'string') out.code = code;
+ if (typeof code === 'string' || typeof code === 'number') out.code = code;
return out;
}
});
diff --git a/src/main/ipc/local_agents.ts b/src/main/ipc/local_agents.ts
index b368d852..006d1fad 100644
--- a/src/main/ipc/local_agents.ts
+++ b/src/main/ipc/local_agents.ts
@@ -1,18 +1,33 @@
/**
* IPC handlers for local CLI agent discovery.
*
- * Three logical channels exposed to the renderer:
- * - `localAgents.list` → all known CLI types with availability + version
- * - `localAgents.detect` → single-CLI re-probe (bypasses cache)
- * - `localAgents.listModels` → static model catalog for a CLI type
+ * Logical channels exposed to the renderer:
+ * - `localAgents.list` → all known CLI types with availability + version
+ * - `localAgents.detect` → single-CLI re-probe (bypasses cache)
+ * - `localAgents.listModels` → static model catalog for a CLI type
+ * - `localAgents.readToolResult` → read a spilled CLI tool_result file
+ * (renderer click-to-expand)
*
* No `run` channel here — the renderer doesn't spawn CLIs directly;
* dispatch goes through the existing `groupChat` channel and `bus.ts`
* routes CLI agents into `features/local_agents/runner.ts` (Step 6).
*/
+import * as fs from 'node:fs';
+import * as path from 'node:path';
import { detectAll, detectOne, invalidateCache, LOCAL_CLI_TYPES, type LocalCliType, type LocalCliEntry } from '../features/local_agents/registry.js';
import { listModels } from '../features/local_agents/models.js';
+import { getActiveUserId } from '../features/users.js';
+import { userToolResultsDir } from '../paths.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('ipc:local_agents');
+
+/** Inline-expand cap. The renderer's <pre> can render a few hundred KB
+ * without freezing, but past that the user wants an editor anyway. We
+ * cap reads here AND tell the renderer via `truncated: true` so it
+ * can suggest opening the file directly. */
+const READ_TOOL_RESULT_MAX_BYTES = 256 * 1024;
function isLocalCliType(v: unknown): v is LocalCliType {
return typeof v === 'string' && (LOCAL_CLI_TYPES as readonly string[]).includes(v);
@@ -72,4 +87,75 @@ export const invokeHandlers = {
if (!isLocalCliType(type)) throw new Error('invalid CLI type');
return { models: listModels(type) };
},
+
+ /**
+ * Read a spilled CLI tool_result file. The renderer's click-to-expand
+ * UI calls this with the `outputPath` it received on a `tool-event
+ * phase:'result'` event.
+ *
+ * Hard constraints:
+ * - Path MUST resolve under the active uid's
+ * `<uid>/local/tool-results/` directory. Symlink-traversal is
+ * blocked by realpath-comparing against the canonical root, so a
+ * compromised CLI can't trick the renderer into reading
+ * arbitrary files.
+ * - Read is byte-capped (256 KB inline); larger files truncate
+ * and set `truncated: true`. The shell.openPath path for "open
+ * in editor" is a separate IPC, not added in this round.
+ *
+ * Returns `{ok:true, content, truncated}` or `{ok:false, error}`;
+ * never throws across the IPC boundary so a UI bug can't crash the
+ * renderer.
+ */
+ 'localAgents.readToolResult': async ({ path: filePath }: { path?: unknown }) => {
+ if (typeof filePath !== 'string' || !filePath) {
+ return { ok: false as const, error: 'invalid path' };
+ }
+ const uid = (() => {
+ try { return getActiveUserId(); }
+ catch { return ''; }
+ })();
+ if (!uid) return { ok: false as const, error: 'no active user' };
+ const rootDir = userToolResultsDir(uid);
+ // Resolve both sides via realpath when they exist, then compare.
+ // The renderer-supplied path may legitimately not exist anymore
+ // (sweep ran, tool-result evicted) — handle ENOENT cleanly.
+ let resolved: string;
+ try {
+ resolved = fs.realpathSync(filePath);
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code === 'ENOENT') return { ok: false as const, error: 'file no longer exists' };
+ return { ok: false as const, error: `cannot resolve path: ${(err as Error).message}` };
+ }
+ let rootResolved: string;
+ try { rootResolved = fs.realpathSync(rootDir); }
+ catch { return { ok: false as const, error: 'tool-results dir not found' }; }
+ const rel = path.relative(rootResolved, resolved);
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
+ log.warn('readToolResult rejected out-of-scope path', { filePath, uid });
+ return { ok: false as const, error: 'path is outside tool-results scope' };
+ }
+ try {
+ const stat = fs.statSync(resolved);
+ if (!stat.isFile()) return { ok: false as const, error: 'not a regular file' };
+ const total = stat.size;
+ if (total <= READ_TOOL_RESULT_MAX_BYTES) {
+ const content = fs.readFileSync(resolved, 'utf8');
+ return { ok: true as const, content, truncated: false };
+ }
+ // Oversized — read head only. Buffer-level slice avoids loading
+ // the whole file into memory.
+ const fd = fs.openSync(resolved, 'r');
+ try {
+ const buf = Buffer.alloc(READ_TOOL_RESULT_MAX_BYTES);
+ fs.readSync(fd, buf, 0, READ_TOOL_RESULT_MAX_BYTES, 0);
+ return { ok: true as const, content: buf.toString('utf8'), truncated: true };
+ } finally {
+ fs.closeSync(fd);
+ }
+ } catch (err) {
+ return { ok: false as const, error: (err as Error).message };
+ }
+ },
};
diff --git a/src/main/model/core-agent/event-mapper.ts b/src/main/model/core-agent/event-mapper.ts
index c3c535c6..0078d583 100644
--- a/src/main/model/core-agent/event-mapper.ts
+++ b/src/main/model/core-agent/event-mapper.ts
@@ -42,6 +42,30 @@ function resultPreview(s: string, max = 300): string {
return oneLine.length > max ? oneLine.slice(0, max) + '…' : oneLine;
}
+/**
+ * When `util/tool-result-cap.ts` spills an oversized in-process tool
+ * result to disk, it rewrites `result.content` into a
+ * `<persisted-output tool="..." size="..." path="...">...preview...</persisted-output>`
+ * marker. This is what the model sees, and it's what we receive as
+ * `ev.result` here in the event mapper. The renderer's click-to-expand
+ * UI needs the absolute path to read back the full body via
+ * `localAgents.readToolResult` — so we extract it from the marker.
+ *
+ * Returns `{ path, size }` when the marker is present, `null` otherwise
+ * (most tool calls don't spill — their result is just the raw output
+ * string, exposed directly through the `output` field on the event).
+ *
+ * Exposed for unit testing.
+ */
+export function extractPersistedOutputPath(result: string): { path: string; size: number } | null {
+ if (!result || typeof result !== 'string') return null;
+ // Match the opening tag only; the body and closing tag can be huge.
+ // tool-result-cap.ts owns the format — keep this regex in sync.
+ const m = /<persisted-output\b[^>]*?\bsize="(\d+)"[^>]*?\bpath="([^"]+)"/.exec(result);
+ if (!m) return null;
+ return { path: m[2], size: Number(m[1]) };
+}
+
/**
* Translate a raw retry reason (usually `err.message` from core-agent) into
* a short user-facing phrase. The raw strings come from undici / pi-ai /
@@ -126,18 +150,37 @@ export async function* mapCoreAgentEvents(
}
case 'tool_end': {
- const preview = resultPreview(ev.result || '');
+ const rawResult = ev.result || '';
+ const preview = resultPreview(rawResult);
+ // Two click-to-expand storage paths, decided here:
+ // - oversized → util/tool-result-cap.ts already spilled to
+ // disk; rawResult is a `<persisted-output path=...>` marker.
+ // Pass the absolute path so the renderer reads back via
+ // localAgents.readToolResult IPC.
+ // - normal → rawResult IS the full body (≤ 50 KB cap).
+ // Pass it inline so the renderer stashes on the row and
+ // renders directly without IO. The model already saw this
+ // same body — sending it twice (event + persistent session)
+ // adds ≤ 50 KB per call, well within memory budget.
+ const spill = extractPersistedOutputPath(rawResult);
+ const data: Record<string, unknown> = {
+ phase: 'end',
+ id: ev.id,
+ name: ev.name,
+ isError: !!ev.isError,
+ result_preview: preview,
+ };
+ if (spill) {
+ data.result_path = spill.path;
+ data.result_size = spill.size;
+ } else if (rawResult) {
+ data.output = rawResult;
+ }
yield {
type: 'event',
event: {
stream: 'tool',
- data: {
- phase: 'end',
- id: ev.id,
- name: ev.name,
- isError: !!ev.isError,
- result_preview: preview,
- },
+ data,
},
};
// Same dedupe rationale as `tool_start`: the renderer renders the
diff --git a/src/main/model/core-agent/search-tools.ts b/src/main/model/core-agent/search-tools.ts
index f95f450a..c00b82dd 100644
--- a/src/main/model/core-agent/search-tools.ts
+++ b/src/main/model/core-agent/search-tools.ts
@@ -82,7 +82,7 @@ export async function createWebSearchOverrideTool(): Promise<AgentTool> {
const profile = pickActiveSearchProfile();
if (profile) {
const label = SEARCH_PROVIDER_LABEL[profile.provider] || profile.provider;
- log.info('web_search via paid API', { provider: profile.provider, query: query.slice(0, 80), count });
+ log.info('web_search via paid API', { provider: profile.provider, query_len: query.length, count });
try {
const res = await runSearchAdapter(profile, query, count);
log.info('web_search paid API ok', { provider: profile.provider, results: res.results.length });
@@ -106,7 +106,7 @@ export async function createWebSearchOverrideTool(): Promise<AgentTool> {
}
}
- log.info('web_search via builtin keyless (no paid profile configured)', { query: query.slice(0, 80), count });
+ log.info('web_search via builtin keyless (no paid profile configured)', { query_len: query.length, count });
return mod.runBuiltinWebSearch(query, count);
},
});
diff --git a/src/main/paths.ts b/src/main/paths.ts
index 929fc8d2..df693066 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -135,13 +135,24 @@ export const userSessionFile = (uid: string, sessionId: string) => path.j
// Curated knowledge base (the "organized" region of the historical
// two-region contexts design).
export const userContextsDir = (uid: string) => path.join(userCloudRoot(uid), 'contexts');
+// Machine-private mirror of contexts/ — holds derived state that must NOT
+// cross devices (currently just the KB vector store; see `userKbDir` below).
+// **Why** mirror the cloud structure under local/ instead of an ad-hoc
+// `<uid>/local/kb/`: keeps the mental model "everything KB lives under
+// .../contexts/.kb/" intact across the cloud/local divide so paths.ts
+// stays grep-able and the migration story is symmetric.
+export const userLocalContextsDir = (uid: string) => path.join(userLocalRoot(uid), 'contexts');
// Local vector store for the knowledge base (part of the cloud-sync domain,
// stored in the same directory tree as the text content; on conflict the
// newer mtime wins). The hidden sub-directory `.kb/` keeps it out of the
// contexts user-visible listing (listContextsTree filters dotfiles).
// Runtime WAL/SHM sidecar files are excluded from sync.
-export const userKbDir = (uid: string) => path.join(userContextsDir(uid), '.kb');
+// KB vector store: machine-private, NOT cloud-synced (multi-device-sync
+// batch 2 decision). Path moved from `<uid>/cloud/contexts/.kb/` (legacy)
+// to `<uid>/local/contexts/.kb/` (current). One-shot rename runs from
+// `util/migrate-kb-to-local.ts` on activateUser.
+export const userKbDir = (uid: string) => path.join(userLocalContextsDir(uid), '.kb');
export const userKbVectorDbPath = (uid: string) => path.join(userKbDir(uid), 'vector.db');
export const userKbConfigPath = (uid: string) => path.join(userKbDir(uid), 'config.json');
@@ -340,6 +351,23 @@ 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');
+// ── Multi-device sync (machine-private state) ────────────────────────────
+// `<uid>/local/sync/` is the engine's per-machine bookkeeping; nothing here
+// crosses devices (per plan §3.2). `index.json` is the last-synced snapshot
+// (path → {sha256, size, mtime_ms, _v, compressed}), `state.json` carries
+// generation / pending_uploads / device_id, and `conflicts/` retains
+// snapshots for the recovery UX (default 30d; profile-tunable per batch 7).
+export const userSyncDir = (uid: string) => path.join(userLocalRoot(uid), 'sync');
+export const userSyncIndexFile = (uid: string) => path.join(userSyncDir(uid), 'index.json');
+export const userSyncStateFile = (uid: string) => path.join(userSyncDir(uid), 'state.json');
+export const userSyncConflictsDir = (uid: string) => path.join(userSyncDir(uid), 'conflicts');
+// Cached copy of the last-fetched cloud manifest. Read on engine startup so
+// the settings card's storage breakdown can render instantly without
+// waiting for a network round-trip. Refreshed at the end of every
+// successful sync pass.
+export const userSyncManifestCacheFile = (uid: string) =>
+ path.join(userSyncDir(uid), 'manifest_cached.json');
+
// ── Build-time resources (shipped with installer, read-only) ────────────
// The 95MB ONNX embedding model ships via electron-builder's `extraResources`
// (it does not go through asar); dev and packaged builds have different paths:
@@ -411,6 +439,10 @@ export function ensureUserLayout(uid: string): void {
userSearchDir(uid),
userFileCacheDir(uid),
userToolResultsDir(uid),
+ userSyncDir(uid),
+ userSyncConflictsDir(uid),
+ userLocalContextsDir(uid),
+ userKbDir(uid),
];
for (const d of dirs) fs.mkdirSync(d, { recursive: true });
diff --git a/src/main/preload.js b/src/main/preload.js
index 9a055e7a..2235b318 100644
--- a/src/main/preload.js
+++ b/src/main/preload.js
@@ -22,6 +22,21 @@
const { contextBridge, ipcRenderer } = require('electron');
+// Synchronous i18n boot — handed to the renderer via contextBridge before any
+// renderer-side script runs. The renderer's i18n module reads window.__orkasI18nBoot
+// at script-tag execution time (line 1118 of index.html, after all data-i18n
+// elements have been parsed), so applyDomI18n() can translate the DOM before
+// the first paint. Falls back to a null bundle on failure — i18n.js then runs
+// its old async initI18n() path. sendSync blocks for one short IPC round-trip
+// (~1-2 ms); the trade is paying that for zero language-flash on startup.
+let _i18nBoot = null;
+try {
+ const res = ipcRenderer.sendSync('orkas:bootI18n');
+ if (res && res.ok && (res.lang === 'zh' || res.lang === 'en') && res.tables) {
+ _i18nBoot = { lang: res.lang, tables: res.tables };
+ }
+} catch (_) { /* main not ready / handler missing → renderer falls back to async */ }
+
let _streamCounter = 0;
function nextRequestId() {
_streamCounter += 1;
@@ -109,6 +124,63 @@ function stream(channel, payload, onEvent) {
return { promise, cancel };
}
+// push channel are stripped from the OrkasOpen build — see OpenSource/SyncCode/strip-rules.json.
+const account = {
+ status: () => invoke('account.status'),
+ listProviders: () => invoke('account.listProviders'),
+ startLogin: () => invoke('account.startLogin'),
+ logout: () => invoke('account.logout'),
+ currentUser: () => invoke('account.currentUser'),
+ // Subscribe to status-change pushes from main (login completed / session revoked). Returns an
+ // unsubscribe function.
+ onChange: (cb) => {
+ if (typeof cb !== 'function') return () => {};
+ const listener = (_evt, payload) => { try { cb(payload); } catch (_) { /* renderer cb threw */ } };
+ },
+};
+
+// Voice-to-text (the chat-composer mic button → the Server's /voice/asr_ws ASR proxy). The
+// `voice` namespace + renderer/modules/voice-input.js are stripped from the OrkasOpen build
+// (offline client, no Server) — see OpenSource/SyncCode/strip-rules.json.
+const voice = {
+};
+
+// Multi-device sync. Stripped from the OrkasOpen build along with the account namespace
+// it depends on — see OpenSource/SyncCode/strip-rules.json.
+const sync = {
+ runNow: () => invoke('sync.runNow'),
+ status: () => invoke('sync.status'),
+ usage: () => invoke('sync.usage'),
+ getEnabled: () => invoke('sync.getEnabled'),
+ setEnabled: (enabled, opts) => invoke('sync.setEnabled', {
+ enabled: !!enabled,
+ purge: !!(opts && opts.purge),
+ }),
+ usageBreakdown: () => invoke('sync.usageBreakdown'),
+ getPendingMassDelete: () => invoke('sync.getPendingMassDelete'),
+ confirmPendingDelete: () => invoke('sync.confirmPendingDelete'),
+ cancelPendingDelete: () => invoke('sync.cancelPendingDelete'),
+ onStatus: (cb) => {
+ if (typeof cb !== 'function') return () => {};
+ const listener = (_evt, payload) => { try { cb(payload); } catch (_) { /* swallow */ } };
+ },
+ onUsage: (cb) => {
+ if (typeof cb !== 'function') return () => {};
+ const listener = (_evt, payload) => { try { cb(payload); } catch (_) { /* swallow */ } };
+ },
+ // Fires after a sync pass pulls / renames / tombstone-deletes at least one
+ // file — the on-disk cloud/ tree now has content the renderer's in-memory
+ // lists don't know about. Payload: { domains: string[], cids: string[] }.
+ onDataChanged: (cb) => {
+ if (typeof cb !== 'function') return () => {};
+ const listener = (_evt, payload) => { try { cb(payload); } catch (_) { /* swallow */ } };
+ },
+};
+
+// Expose the sync-fetched i18n bundle on its own bridge key so the renderer
+// can pick it up at module load. Read-only — the renderer never mutates it.
+contextBridge.exposeInMainWorld('__orkasI18nBoot', _i18nBoot);
+
contextBridge.exposeInMainWorld('orkas', {
ping: () => ipcRenderer.invoke('orkas.ping'),
diagnostics: () => ipcRenderer.invoke('orkas.diagnostics'),
@@ -116,6 +188,9 @@ contextBridge.exposeInMainWorld('orkas', {
getLanguage: () => invoke('config.getLanguage'),
setLanguage: (language) => invoke('config.setLanguage', { language }),
getLocales: () => invoke('config.getLocales'),
+ account,
+ voice,
+ sync,
invoke,
stream,
onPushEvent,
diff --git a/src/main/prompts/chat_commander.md b/src/main/prompts/chat_commander.md
index f4171a74..bfb0f859 100644
--- a/src/main/prompts/chat_commander.md
+++ b/src/main/prompts/chat_commander.md
@@ -243,7 +243,7 @@ When a user message has an `<attachments>` prefix, each `<file name=... path=...
**`read_file` / `stat_file` semantics**:
- text / pdf / docx all use `charStart` / `charEnd` (0-based half-open intervals); omitted = full content. Response header is `<file path=.. kind=.. total_chars="N" covered="a-b">…</file>`.
- For pdf / docx not yet extracted, `read_file` returns `E_NEED_STAT`; call `stat_file(path)` first to trigger extraction. text has no such issue.
-- image does NOT take a range; the response is a real-time compressed grayscale JPEG fed to the vision model (**you see it; the user does NOT**).
+- image does NOT take a range; the response is a real-time compressed grayscale JPEG fed to the vision model (**you see it; the user does NOT**). Manifest entries marked `attached="inline"` already ride this turn's vision input — answer from what you see, do NOT call `read_file` on them.
**`search_files` / `grep_files`**: scope = `$working_dir` ∪ the current conversation's attachment dir. `search_files` finds paths by filename / glob; `grep_files` searches text across files (auto-extracts pdf/docx on hit).
diff --git a/src/main/util/migrate-kb-to-local.ts b/src/main/util/migrate-kb-to-local.ts
new file mode 100644
index 00000000..198dbba4
--- /dev/null
+++ b/src/main/util/migrate-kb-to-local.ts
@@ -0,0 +1,137 @@
+/**
+ * One-shot migration: move `<uid>/cloud/contexts/.kb/` to
+ * `<uid>/local/contexts/.kb/` (multi-device-sync batch 2 decision —
+ * vector store is machine-private and must not cross devices).
+ *
+ * Stamps `<uid>/local/.migrations` to prevent re-runs. Same convention as
+ * `migrate-session-ids.ts`.
+ *
+ * Edge cases:
+ * - New path already exists, old path doesn't: nothing to do (post-migration
+ * baseline). Stamp and return.
+ * - New path exists AND old path exists: keep new, rename old to
+ * `.kb.legacy-<ts>` so we never delete user data automatically. Log warn
+ * so support can investigate. Stamp.
+ * - Old path is a file (not a directory): leave it alone (corrupt FS state),
+ * stamp anyway since the schema says it should be a directory.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+import {
+ userContextsDir, // <uid>/cloud/contexts/
+ userLocalContextsDir, // <uid>/local/contexts/
+ userKbDir, // <uid>/local/contexts/.kb/ (after this migration)
+ userLocalConfigDir,
+} from '../paths';
+import { createLogger } from '../logger';
+
+const log = createLogger('migrate');
+const MIGRATION_TAG = 'kb-to-local-contexts-v1';
+
+function migrationsFile(uid: string): string {
+ // userLocalConfigDir = <uid>/local/config; up one to <uid>/local/
+ return path.join(path.dirname(userLocalConfigDir(uid)), '.migrations');
+}
+
+function alreadyApplied(uid: string): boolean {
+ const f = migrationsFile(uid);
+ if (!fs.existsSync(f)) return false;
+ try {
+ const content = fs.readFileSync(f, 'utf8');
+ return content.split('\n').some((line) => line.trim() === MIGRATION_TAG);
+ } catch {
+ return false;
+ }
+}
+
+function stamp(uid: string): void {
+ const f = migrationsFile(uid);
+ try {
+ fs.mkdirSync(path.dirname(f), { recursive: true });
+ fs.appendFileSync(f, `${MIGRATION_TAG}\n`);
+ } catch (err) {
+ log.warn(`stamp failed uid=${uid}: ${(err as Error).message}`);
+ }
+}
+
+export function migrateKbToLocalContexts(uid: string): void {
+ if (alreadyApplied(uid)) return;
+
+ const legacyKb = path.join(userContextsDir(uid), '.kb'); // <uid>/cloud/contexts/.kb
+ const newKb = userKbDir(uid); // <uid>/local/contexts/.kb
+
+ const legacyExists = fs.existsSync(legacyKb);
+ const newExists = fs.existsSync(newKb);
+
+ if (!legacyExists) {
+ stamp(uid);
+ return;
+ }
+
+ let legacyIsDir = false;
+ try { legacyIsDir = fs.statSync(legacyKb).isDirectory(); } catch { /* ignore */ }
+
+ if (!legacyIsDir) {
+ log.warn(`kb migration: legacy .kb at ${legacyKb} is not a directory; leaving alone`);
+ stamp(uid);
+ return;
+ }
+
+ // Ensure parent of new path exists.
+ fs.mkdirSync(path.dirname(newKb), { recursive: true });
+
+ if (newExists) {
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
+ const sidelined = `${legacyKb}.legacy-${ts}`;
+ log.warn(
+ `kb migration: both ${legacyKb} and ${newKb} exist; keeping ${newKb}, ` +
+ `renaming legacy → ${sidelined}`,
+ );
+ try {
+ fs.renameSync(legacyKb, sidelined);
+ } catch (err) {
+ log.warn(`kb migration: rename-to-sidelined failed: ${(err as Error).message}`);
+ }
+ stamp(uid);
+ return;
+ }
+
+ try {
+ fs.renameSync(legacyKb, newKb);
+ log.info(`kb migration: moved ${legacyKb} → ${newKb}`);
+ } catch (err) {
+ // Cross-device rename can fail on some filesystems. Fall back to a copy +
+ // delete; better to slow-pass than to leave the user without their index.
+ const msg = (err as Error).message;
+ if ((err as NodeJS.ErrnoException).code === 'EXDEV') {
+ log.warn(`kb migration: cross-device rename, falling back to copy`);
+ try {
+ copyDirSync(legacyKb, newKb);
+ rmRfSync(legacyKb);
+ } catch (err2) {
+ log.error(`kb migration: copy fallback failed: ${(err2 as Error).message}`);
+ return; // do NOT stamp — retry next boot
+ }
+ } else {
+ log.error(`kb migration: rename failed: ${msg}`);
+ return;
+ }
+ }
+ stamp(uid);
+}
+
+function copyDirSync(src: string, dst: string): void {
+ fs.mkdirSync(dst, { recursive: true });
+ for (const e of fs.readdirSync(src, { withFileTypes: true })) {
+ const s = path.join(src, e.name);
+ const d = path.join(dst, e.name);
+ if (e.isDirectory()) copyDirSync(s, d);
+ else if (e.isFile()) fs.copyFileSync(s, d);
+ }
+}
+
+function rmRfSync(p: string): void {
+ try { fs.rmSync(p, { recursive: true, force: true }); } catch { /* ignore */ }
+}
diff --git a/src/main/util/tool-result-cap.ts b/src/main/util/tool-result-cap.ts
index 6c913a5b..fc25143b 100644
--- a/src/main/util/tool-result-cap.ts
+++ b/src/main/util/tool-result-cap.ts
@@ -160,6 +160,49 @@ export function persistToolResult(
return abs;
}
+/** Spill a CLI tool-event's full output to disk when it exceeds the
+ * 50 KB persistence threshold. Mirrors the in-process tool spill
+ * policy above so an oversized bash output looks the same to the
+ * renderer regardless of whether it came from `wrapToolWithCap`
+ * (in-process tools) or a CLI subprocess's tool-event.
+ *
+ * Used by `local_agents/runner.ts` to wrap each `tool-event
+ * phase:'result'` before forwarding to the renderer. Backends stay
+ * unaware of the spill mechanism — they always emit the full output.
+ *
+ * Returns the rewritten `{output, outputPath}`. When below threshold,
+ * `outputPath` is undefined and `output` is the original content
+ * unchanged. */
+export function maybeSpillToolResult(opts: {
+ toolResultsDir: string;
+ toolName: string;
+ callId: string;
+ output: string;
+}): { output: string; outputPath?: string } {
+ const { toolResultsDir, toolName, output } = opts;
+ if (!output || output.length < PERSIST_THRESHOLD) {
+ return { output };
+ }
+ try {
+ const abs = persistToolResult(toolResultsDir, toolName, output);
+ log.info(`cli tool spill tool=${toolName} session=${path.basename(toolResultsDir)} size=${output.length} path=${abs}`);
+ // Same preview shape as the in-process path so the renderer's
+ // click-to-expand logic works identically.
+ return {
+ output: buildPersistedOutputMarker(abs, toolName, output),
+ outputPath: abs,
+ };
+ } catch (err) {
+ // Disk-write failure: surface a truncated preview rather than the
+ // full payload so we don't blow up the event stream.
+ log.warn(`cli tool spill failed, falling back to truncated preview tool=${toolName}: ${(err as Error).message}`);
+ const head = output.slice(0, PREVIEW_HEAD);
+ return {
+ output: `${head}\n\n[note: oversized output spill failed: ${(err as Error).message}]`,
+ };
+ }
+}
+
export function buildPersistedOutputMarker(
absPath: string,
toolName: string,
diff --git a/src/renderer/index.html b/src/renderer/index.html
index a73fd4dd..1e06a1a2 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -1,4 +1,8 @@
<!doctype html>
+<!-- `<html lang>` is updated to the user's preferred language by i18n.js at
+ script-load (line 1118), based on the sync bundle preload exposed on
+ window.__orkasI18nBoot. The fallback `en` here is what shows if both the
+ preload bridge and the IPC handler are unavailable. -->
<html lang="en">
<head>
<meta charset="utf-8" />
@@ -355,7 +359,11 @@
<button type="button" class="marketplace-tab" data-mp-tab="agent" data-i18n="marketplace.tab_agent">Agents</button>
<button type="button" class="marketplace-tab" data-mp-tab="skill" data-i18n="marketplace.tab_skill">Skills</button>
</div>
- <input type="text" class="marketplace-search" data-mp-search data-i18n-placeholder="marketplace.search_ph" />
+ <div class="marketplace-search-wrap">
+ <input type="text" class="marketplace-search" data-mp-search data-i18n-placeholder="marketplace.search_ph" />
+ <button type="button" class="marketplace-search-clear" data-mp-search-clear data-i18n-title="common.clear" hidden>&times;</button>
+ </div>
+ <button type="button" class="btn btn-sm btn-primary marketplace-search-btn" data-mp-search-btn data-i18n="marketplace.search">Search</button>
</div>
<div class="marketplace-categories" data-mp-categories></div>
<div class="marketplace-body" data-mp-body></div>
@@ -470,8 +478,18 @@
<h2 data-i18n="settings.title">Settings</h2>
<div class="settings-version" id="settings-version"></div>
</div>
+
+ <!-- 4-tab restructure (batch 6 + 4 decision; see PC/docs/plans/multi-device-sync.md §4.9).
+ OrkasOpen contract: the 账号 tab AND the sync card inside 数据 tab are
+ stripped (see strip-rules.json) — settings.js handles missing-tab gracefully. -->
+ <div class="settings-tabs" role="tablist">
+ <button class="settings-tab is-active" data-settings-tab="account" data-i18n="settings.tab.account">账号</button>
+ <button class="settings-tab" data-settings-tab="data" data-i18n="settings.tab.data">数据</button>
+ <button class="settings-tab" data-settings-tab="general" data-i18n="settings.tab.general">通用</button>
+ <button class="settings-tab" data-settings-tab="credentials" data-i18n="settings.tab.credentials">配置</button>
+ </div>
+
<div class="settings-body">
- <div class="settings-section-head" data-i18n="settings.section.general">General</div>
<div class="settings-group">
<div class="settings-group-head">
@@ -488,145 +506,232 @@
</label>
</div>
</div>
-
- <div class="settings-group">
- <div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.commander_avatar.title">Commander avatar</div>
- <div class="settings-group-sub" data-i18n="settings.commander_avatar.sub">Click the avatar to pick a new icon and color.</div>
- </div>
- <div class="settings-row">
- <span class="settings-commander-avatar-slot" id="settings-commander-avatar"></span>
- <span class="settings-status muted" id="settings-commander-avatar-hint" data-i18n="settings.commander_avatar.hint">Click the avatar on the left to change it</span>
+ <!-- ───────────────────────── 账号 ───────────────────────── -->
+ <div class="settings-tab-pane" data-settings-pane="account">
+ <!-- Account card — populated by views/login/account_settings.js; hidden when not
+ signed in. This block + that script are stripped from the OrkasOpen build. -->
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="account.settings_title">账号</div>
+ </div>
+ </div>
+ </div>
</div>
</div>
- <div class="settings-group">
- <div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.localexec.title">Local Execution</div>
- <div class="settings-group-sub" data-i18n="settings.localexec.sub">Once granted, agents may run shell commands, read/write workspace files, and generate PDFs. Without permission those tools refuse to run.</div>
- </div>
- <div class="settings-row">
- <span class="settings-status" id="settings-localexec-status" data-i18n="settings.localexec.status_loading">Loading…</span>
- <button class="btn btn-sm btn-primary" id="settings-localexec-toggle" data-i18n="settings.localexec.btn_grant">Grant local execution</button>
- </div>
- </div>
+ <!-- ───────────────────────── 数据 ───────────────────────── -->
+ <div class="settings-tab-pane" data-settings-pane="data" hidden>
+ <!-- ─── 云端 ───────────────────────────────────────────────
+ Sync cards — multi-device sync status / quota / conflicts. Split into separate
+ .settings-group cards so the layout breathes; the whole subsection is stripped
+ in OrkasOpen along with features/sync. Settings.js gates rendering on
+ `typeof window.orkas?.sync !== 'undefined'`. -->
+ <div class="settings-section-head" id="settings-section-cloud" data-i18n="settings.section.cloud" style="display:none">云端</div>
- <div class="settings-group">
- <div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.metacognition.title">Metacognition-level Agent Self-Evolution</div>
- <div class="settings-group-sub" data-i18n="settings.metacognition.sub">When on, each agent periodically reviews its recent performance, draws lessons, and adjusts how it works so it does better next time. We call it "meta-cognitive" because the agent doesn't just do tasks — it also reasons about "how am I doing, and how could I do better next time?" That cognition about its own cognition is metacognition. Turn off to stop the self-review.</div>
- </div>
- <div class="settings-row">
- <label class="settings-toggle">
- <input type="checkbox" id="settings-metacognition-toggle" />
- <span data-i18n="settings.metacognition.toggle">Enable</span>
- </label>
- <span class="settings-status muted" id="settings-metacognition-status"></span>
+ <!-- Card 1: 主开关 + 状态 + 立即同步 -->
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.sync.title">云端同步</div>
+ <div class="settings-group-sub" data-i18n="settings.sync.privacy_note">数据通过 HTTPS 加密上传到私有云存储,仅你的账号可访问。</div>
+ </div>
+ <div class="settings-row">
+ <label class="settings-toggle settings-toggle-tight">
+ <span data-i18n="settings.sync.toggle_enable">启用云端同步</span>
+ </label>
+ </div>
+ <!-- "关闭中…" — shown only while the disable RPC is in flight. -->
+ <span class="settings-status muted" data-i18n="settings.sync.disabling">关闭中…</span>
+ </div>
+ <!-- Disable-failed slot: inline error + retry button.
+ Replaces the previous uiAlert toast; user asked for an
+ in-card actionable failure state. -->
+ </div>
+ </div>
+ </div>
+ </div>
+ <!-- Mass-delete confirmation panel — only visible when the
+ engine paused with reason `mass_delete_pending`. -->
+ <span data-i18n="settings.sync.mass_delete_summary">即将从云端删除 </span>
+ <span data-i18n="settings.sync.mass_delete_summary_tail"> 个文件。请确认这是有意的操作。</span>
+ </div>
+ <div class="settings-row">
+ </div>
+ </div>
</div>
- </div>
-
- <div class="settings-section-head" data-i18n="settings.section.models">Models & credentials</div>
- <div class="settings-section-note" data-i18n="settings.section.models_note">API keys and OAuth tokens are stored locally only — never synced or sent off-device.</div>
- <div class="settings-group">
- <div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.add_auth_title">Add model authorization</div>
- <div class="settings-group-sub" data-i18n="settings.add_auth_sub">Pick a provider and model, then add an API key or OAuth account.</div>
- </div>
- <div class="settings-row">
- <label data-i18n="settings.provider">Provider</label>
- <div class="ai-select" id="settings-picker-provider"></div>
- </div>
- <div class="settings-row">
- <label data-i18n="settings.model">Model</label>
- <div class="ai-select" id="settings-picker-model"></div>
- </div>
- <div class="settings-row">
- <button class="btn btn-primary" id="settings-add-entry-btn" data-i18n="settings.add_account">+ Add account</button>
- <span class="settings-status" id="settings-picker-status"></span>
+ <!-- Card 2: 存储空间 (quota bar + always-visible category/project breakdown) -->
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.sync.storage_title">存储空间</div>
+ </div>
+ </div>
</div>
- </div>
- <div class="settings-group">
- <div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.configured_title">Configured (by priority)</div>
- <div class="settings-group-sub" data-i18n="settings.configured_sub">The first entry is the default model; later entries are the fallback chain. Drag to reorder.</div>
- </div>
- <div class="settings-entries" id="settings-entries">
- <div class="settings-empty" data-i18n="settings.loading">Loading…</div>
+ <!-- Card 3: 冲突记录 -->
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.sync.conflicts_title">冲突记录</div>
+ <div class="settings-group-sub" data-i18n="settings.sync.conflicts_sub">两台设备同时修改同一文件时,被覆盖的版本会留底在这里,可恢复。</div>
+ </div>
+ <div class="settings-empty" data-i18n="settings.sync.conflicts_empty">暂无冲突</div>
+ </div>
</div>
- </div>
- <div class="settings-section-head" data-i18n="settings.section.tools">Tool capabilities</div>
- <div class="settings-section-note" data-i18n="settings.section.tools_note">Search and image-gen API keys are stored locally only — never synced or sent off-device.</div>
+ <!-- ─── 本地 ───────────────────────────────────────────────
+ Maintenance actions on local data; not synced. -->
+ <div class="settings-section-head" data-i18n="settings.section.local">本地</div>
- <div class="settings-group">
- <div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.search.title">Search API Key</div>
- <div class="settings-group-sub" data-i18n="settings.search.sub">Priority: paid API &gt; model-native search &gt; built-in keyless scraper.</div>
- </div>
- <div class="settings-row">
- <label data-i18n="settings.search.provider">Provider</label>
- <div class="ai-select" id="settings-search-provider"></div>
- </div>
- <div class="settings-row">
- <label data-i18n="settings.search.api_key">API Key</label>
- <input type="text" class="form-input" id="settings-search-key-input" autocomplete="off" spellcheck="false" />
- </div>
- <div class="settings-row">
- <button class="btn btn-primary" id="settings-search-add-btn" data-i18n="settings.search.add">+ Add search key</button>
- <span class="settings-status" id="settings-search-status"></span>
+ <div class="settings-group">
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.data_root.title">Data root</div>
+ <div class="settings-group-sub" data-i18n="settings.data_root.sub">All conversations, agents, skills, and KB content live under this directory. Click the path to open it in the OS file manager.</div>
+ </div>
+ <div class="settings-row">
+ <button class="btn btn-sm" id="settings-data-root-btn" type="button" title="" data-i18n-title="settings.data_root.open_tooltip"><span id="settings-data-root-path" class="muted"></span></button>
+ </div>
</div>
- <div class="settings-entries" id="settings-search-entries">
- <div class="settings-empty" data-i18n="settings.loading">Loading…</div>
+
+ <div class="settings-group">
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.clear_all_convs.title">Clear all conversations</div>
+ <div class="settings-group-sub" data-i18n="settings.clear_all_convs.sub">Removes every conversation and its associated message history, attachments, plan, sessions, and search index entries — same cascade as clicking × on a single conversation, applied to all of them. Skills and agents are NOT touched.</div>
+ </div>
+ <div class="settings-row">
+ <button class="btn btn-sm btn-danger" id="settings-clear-all-convs-btn" data-i18n="settings.clear_all_convs.btn">Clear all conversations</button>
+ <span class="settings-status muted" id="settings-clear-all-convs-status"></span>
+ </div>
</div>
</div>
- <div class="settings-group">
- <div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.image.title">Image generation API Key</div>
- <div class="settings-group-sub" data-i18n="settings.image.sub">API for the generate_image tool. Falls back to chat keys when those target OpenAI or Google.</div>
- </div>
- <div class="settings-row">
- <label data-i18n="settings.image.provider">Provider</label>
- <div class="ai-select" id="settings-image-provider"></div>
+ <!-- ───────────────────────── 通用 ───────────────────────── -->
+ <div class="settings-tab-pane" data-settings-pane="general" hidden>
+ <div class="settings-group">
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.language.title">语言 / Language</div>
+ </div>
+ <div class="settings-row" id="settings-language-row">
+ <label class="settings-lang-opt">
+ <input type="radio" name="settings-language" value="zh" />
+ <span data-i18n="settings.language.zh">简体中文</span>
+ </label>
+ <label class="settings-lang-opt">
+ <input type="radio" name="settings-language" value="en" />
+ <span data-i18n="settings.language.en">English</span>
+ </label>
+ </div>
</div>
- <div class="settings-row">
- <label data-i18n="settings.image.api_key">API Key</label>
- <input type="text" class="form-input" id="settings-image-key-input" autocomplete="off" spellcheck="false" />
+
+ <div class="settings-group">
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.commander_avatar.title">Commander avatar</div>
+ <div class="settings-group-sub" data-i18n="settings.commander_avatar.sub">Click the avatar to pick a new icon and color.</div>
+ </div>
+ <div class="settings-row">
+ <span class="settings-commander-avatar-slot" id="settings-commander-avatar"></span>
+ <span class="settings-status muted" id="settings-commander-avatar-hint" data-i18n="settings.commander_avatar.hint">Click the avatar on the left to change it</span>
+ </div>
</div>
- <div class="settings-row">
- <button class="btn btn-primary" id="settings-image-add-btn" data-i18n="settings.image.add">+ Add image key</button>
- <span class="settings-status" id="settings-image-status"></span>
+
+ <div class="settings-group">
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.localexec.title">Local Execution</div>
+ <div class="settings-group-sub" data-i18n="settings.localexec.sub">Once granted, agents may run shell commands, read/write workspace files, and generate PDFs. Without permission those tools refuse to run.</div>
+ </div>
+ <div class="settings-row">
+ <span class="settings-status" id="settings-localexec-status" data-i18n="settings.localexec.status_loading">Loading…</span>
+ <button class="btn btn-sm btn-primary" id="settings-localexec-toggle" data-i18n="settings.localexec.btn_grant">Grant local execution</button>
+ </div>
</div>
- <div class="settings-entries" id="settings-image-entries">
- <div class="settings-empty" data-i18n="settings.loading">Loading…</div>
+
+ <div class="settings-group">
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.metacognition.title">Metacognition-level Agent Self-Evolution</div>
+ <div class="settings-group-sub" data-i18n="settings.metacognition.sub">When on, each agent periodically reviews its recent performance, draws lessons, and adjusts how it works so it does better next time.</div>
+ </div>
+ <div class="settings-row">
+ <label class="settings-toggle">
+ <input type="checkbox" id="settings-metacognition-toggle" />
+ <span data-i18n="settings.metacognition.toggle">Enable</span>
+ </label>
+ <span class="settings-status muted" id="settings-metacognition-status"></span>
+ </div>
</div>
</div>
- <div class="settings-section-head" data-i18n="settings.section.data">Data</div>
- <div class="settings-section-note" data-i18n="settings.section.data_note">Maintenance actions on local data. These cannot be undone.</div>
+ <!-- ───────────────────────── 配置 ───────────────────────── -->
+ <div class="settings-tab-pane" data-settings-pane="credentials" hidden>
+ <div class="settings-section-note" data-i18n="settings.section.models_note">API keys and OAuth tokens are stored locally only — never synced or sent off-device.</div>
- <div class="settings-group">
- <div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.data_root.title">Data root</div>
- <div class="settings-group-sub" data-i18n="settings.data_root.sub">All conversations, agents, skills, and KB content live under this directory. Click the path to open it in the OS file manager.</div>
+ <div class="settings-group">
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.add_auth_title">Add model authorization</div>
+ <div class="settings-group-sub" data-i18n="settings.add_auth_sub">Pick a provider and model, then add an API key or OAuth account.</div>
+ </div>
+ <div class="settings-row">
+ <label data-i18n="settings.provider">Provider</label>
+ <div class="ai-select" id="settings-picker-provider"></div>
+ </div>
+ <div class="settings-row">
+ <label data-i18n="settings.model">Model</label>
+ <div class="ai-select" id="settings-picker-model"></div>
+ </div>
+ <div class="settings-row">
+ <button class="btn btn-primary" id="settings-add-entry-btn" data-i18n="settings.add_account">+ Add account</button>
+ <span class="settings-status" id="settings-picker-status"></span>
+ </div>
</div>
- <div class="settings-row">
- <button class="btn btn-sm" id="settings-data-root-btn" type="button" title="" data-i18n-title="settings.data_root.open_tooltip"><span id="settings-data-root-path" class="muted"></span></button>
+
+ <div class="settings-group">
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.configured_title">Configured (by priority)</div>
+ <div class="settings-group-sub" data-i18n="settings.configured_sub">The first entry is the default model; later entries are the fallback chain. Drag to reorder.</div>
+ </div>
+ <div class="settings-entries" id="settings-entries">
+ <div class="settings-empty" data-i18n="settings.loading">Loading…</div>
+ </div>
</div>
- </div>
- <div class="settings-group">
- <div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.clear_all_convs.title">Clear all conversations</div>
- <div class="settings-group-sub" data-i18n="settings.clear_all_convs.sub">Removes every conversation and its associated message history, attachments, plan, sessions, and search index entries — same cascade as clicking × on a single conversation, applied to all of them. Skills and agents are NOT touched.</div>
+ <div class="settings-group">
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.search.title">Search API Key</div>
+ <div class="settings-group-sub" data-i18n="settings.search.sub">Priority: paid API &gt; model-native search &gt; built-in keyless scraper.</div>
+ </div>
+ <div class="settings-row">
+ <label data-i18n="settings.search.provider">Provider</label>
+ <div class="ai-select" id="settings-search-provider"></div>
+ </div>
+ <div class="settings-row">
+ <label data-i18n="settings.search.api_key">API Key</label>
+ <input type="text" class="form-input" id="settings-search-key-input" autocomplete="off" spellcheck="false" />
+ </div>
+ <div class="settings-row">
+ <button class="btn btn-primary" id="settings-search-add-btn" data-i18n="settings.search.add">+ Add search key</button>
+ <span class="settings-status" id="settings-search-status"></span>
+ </div>
+ <div class="settings-entries" id="settings-search-entries">
+ <div class="settings-empty" data-i18n="settings.loading">Loading…</div>
+ </div>
</div>
- <div class="settings-row">
- <button class="btn btn-sm btn-danger" id="settings-clear-all-convs-btn" data-i18n="settings.clear_all_convs.btn">Clear all conversations</button>
- <span class="settings-status muted" id="settings-clear-all-convs-status"></span>
+
+ <div class="settings-group">
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="settings.image.title">Image generation API Key</div>
+ <div class="settings-group-sub" data-i18n="settings.image.sub">API for the generate_image tool. Falls back to chat keys when those target OpenAI or Google.</div>
+ </div>
+ <div class="settings-row">
+ <label data-i18n="settings.image.provider">Provider</label>
+ <div class="ai-select" id="settings-image-provider"></div>
+ </div>
+ <div class="settings-row">
+ <label data-i18n="settings.image.api_key">API Key</label>
+ <input type="text" class="form-input" id="settings-image-key-input" autocomplete="off" spellcheck="false" />
+ </div>
+ <div class="settings-row">
+ <button class="btn btn-primary" id="settings-image-add-btn" data-i18n="settings.image.add">+ Add image key</button>
+ <span class="settings-status" id="settings-image-status"></span>
+ </div>
+ <div class="settings-entries" id="settings-image-entries">
+ <div class="settings-empty" data-i18n="settings.loading">Loading…</div>
+ </div>
</div>
</div>
+
</div>
</div>
</section>
@@ -885,6 +990,7 @@
<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/chat-file-viewer.js"></script>
<script src="./modules/strip-structural-blocks.js"></script>
<script src="./modules/projects.js"></script>
<script src="./modules/project-detail.js"></script>
@@ -946,5 +1052,13 @@
<script src="./vendor/mathjax/tex-chtml.js" defer></script>
<script src="./modules/math.js"></script>
<script src="./modules/settings.js"></script>
+ <script src="./modules/sync_settings.js"></script>
+ <script src="./modules/sync_refresh.js"></script>
+ <script src="./modules/sidebar_status.js"></script>
+ <script src="./modules/devtools-sysinfo.js"></script>
+ <script src="./modules/devtools-relaunch.js"></script>
+ <script src="./modules/devtools-native-search.js"></script>
+ <script src="./modules/devtools-archives.js"></script>
+ <script src="./modules/devtools.js"></script>
</body>
</html>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index 666b4bfe..6c034b31 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -10,6 +10,7 @@
"common.close": "Close",
"common.copy": "Copy",
"common.remove": "Remove",
+ "common.dev_suffix": " (dev)",
"component.enabled": "Enabled",
"component.disabled": "Disabled",
"component.enable": "Enable",
@@ -51,6 +52,11 @@
"chat.project_none": "None",
"chat.project_picker_title": "Pick project",
"chat.attach_title": "Upload attachment (text / PDF / Word / image / video)",
+ "chat.mic_title": "Voice input",
+ "chat.mic_stop_title": "Stop recording",
+ "chat.mic_error_permission": "Microphone access was blocked. Allow it in your system settings to use voice input.",
+ "chat.mic_error_unavailable": "Voice input is unavailable right now.",
+ "chat.mic_login_required": "Sign in to use voice input.",
"chat.chip_remove_title": "Remove",
"chat.send_title": "Send",
"chat.attach_uploading": "Uploading",
@@ -82,6 +88,15 @@
"chat.from_user": "User",
"chat.from_agent_unknown": "Agent",
"chat.produced_reveal_title": "Reveal in folder",
+ "chat.produced_preview_title": "Preview",
+ "chat.preview_close_title": "Close",
+ "chat.preview_reveal_title": "Open in folder",
+ "chat.preview_unsupported_message": "Cannot preview {ext} files in app. Open the containing folder?",
+ "chat.preview_unsupported_no_ext": "(no extension)",
+ "chat.preview_too_large_message": "“{name}” is {size} MB, over the {cap} MB preview cap. Open the containing folder?",
+ "chat.preview_read_failed_message": "Could not read “{name}”. Open the containing folder?",
+ "chat.preview_unsupported_reveal": "Open Folder",
+ "chat.preview_cancel": "Close",
"chat.process_info": "Process info",
"artifact.title": "Interactive app",
"artifact.reload": "Reload",
@@ -130,6 +145,7 @@
"chat.send_failed": "Send failed: {msg}",
"chat.interrupted": "Interrupted",
"chat.stream_done": "● Generation complete",
+ "chat.tool_result_expand_hint": "Click to view full output",
"chat.form.title": "Confirm parameters",
"chat.form.submit": "Confirm",
"chat.form.reset": "Reset",
@@ -427,6 +443,56 @@
"kb_picker.target": "Saving to: {rel}",
"chat.archive_picker_title": "Archive message to knowledge base",
"settings.title": "Settings",
+ "settings.tab.account": "Account",
+ "settings.tab.data": "Data",
+ "settings.tab.general": "General",
+ "settings.tab.credentials": "Credentials",
+ "settings.account.signed_out_hint": "Not signed in. Multi-device sync and remote backup require login.",
+ "settings.section.cloud": "Cloud",
+ "settings.section.local": "Local",
+ "settings.sync.title": "Cloud sync",
+ "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.",
+ "settings.sync.toggle_enable": "Enable cloud sync",
+ "settings.sync.disable_title": "Turn off cloud sync",
+ "settings.sync.disable_message": "This device will stop syncing.\nIf another device also has cloud sync enabled, deleting cloud data will affect its local copy — choose carefully.",
+ "settings.sync.disable_keep_cloud": "Keep cloud data",
+ "settings.sync.disable_purge_cloud": "Delete cloud data",
+ "settings.sync.disabling": "Disabling and wiping cloud data…",
+ "settings.sync.disable_failed": "Disable failed: {error}",
+ "settings.sync.retry": "Retry",
+ "settings.sync.state_paused_disabled": "Disabled",
+ "settings.sync.state_paused_other_device_syncing": "Another device is syncing",
+ "settings.sync.state_paused_mass_delete_pending": "Confirm deletion",
+ "settings.sync.mass_delete_title": "Lots of local deletions detected",
+ "settings.sync.mass_delete_summary": "About to delete ",
+ "settings.sync.mass_delete_summary_tail": " files from cloud. Confirm this is intentional.",
+ "settings.sync.mass_delete_confirm": "Confirm delete",
+ "settings.sync.mass_delete_cancel": "Cancel & restore",
+ "settings.sync.btn_sync_now": "Sync now",
+ "settings.sync.state_idle": "Up to date",
+ "settings.sync.state_syncing": "Syncing…",
+ "settings.sync.state_error": "Sync failed",
+ "settings.sync.state_paused_login_required": "Sign in to enable",
+ "settings.sync.state_paused_quota_full": "Quota full",
+ "settings.sync.state_paused_offline": "Offline",
+ "settings.sync.last_sync": "Last synced: ",
+ "settings.sync.just_now": "just now",
+ "settings.sync.uploading": "up",
+ "settings.sync.downloading": "down",
+ "settings.sync.conflicts_summary": "Conflict log",
+ "settings.sync.conflicts_empty": "No conflicts",
+ "settings.sync.group_conversations": "Conversations",
+ "settings.sync.group_kb": "Knowledge base",
+ "settings.sync.group_agents": "Agents",
+ "settings.sync.group_skills": "Skills",
+ "settings.sync.group_apps": "Apps",
+ "settings.sync.group_other": "Other",
+ "settings.sync.privacy_note": "Encrypted over HTTPS to private cloud storage; only your account can access it.",
+ "settings.sync.error_generic": "Sync failed",
+ "settings.sync.error_network": "Network error — check your connection and retry",
+ "settings.sync.error_quota_full": "Cloud storage full",
"settings.section.general": "General",
"settings.section.models": "Models & credentials",
"settings.section.models_note": "API keys and OAuth tokens are stored locally only — never synced or sent off-device.",
@@ -594,6 +660,74 @@
"settings.metacognition.sub": "When on, each agent periodically reviews its recent performance, draws lessons, and adjusts how it works so it does better next time. We call it \"meta-cognitive\" because the agent doesn't just do tasks — it also reasons about \"how am I doing, and how could I do better next time?\" That cognition about its own cognition is metacognition. Turn off to stop the self-review.",
"settings.metacognition.toggle": "Enable",
"settings.metacognition.env_forced_off": "Forced off by env ORKAS_METACOGNITION=0",
+ "settings.data_root.title": "Data directory",
+ "settings.data_root.sub": "All your data lives under this directory. Click to open it in the file manager.",
+ "settings.data_root.open_tooltip": "Open in file manager",
+ "devtools.title": "Devtools",
+ "devtools.subtitle": "Dev mode only",
+ "devtools.sysinfo_title": "System info",
+ "devtools.copy_title": "Copy as text",
+ "devtools.copy": "Copy",
+ "devtools.relaunch_title": "Relaunch",
+ "devtools.relaunch_sub": "Relaunch the Orkas process so local code changes take effect",
+ "devtools.relaunch_btn": "Relaunch (Cmd/Ctrl + Shift + R)",
+ "devtools.native_search_title": "Model native web search",
+ "devtools.native_search_sub": "When enabled, injects model server-side search tool on supported models. In-memory only, defaults on after restart.",
+ "devtools.native_search_toggle": "Enable model-native web search (OpenAI / Anthropic / Google)",
+ "devtools.archives_title": "LLM call archives",
+ "devtools.archives_sub": "The last 30 streamChatWithModel calls with full input / output / events",
+ "devtools.refresh": "Refresh",
+ "devtools.clear": "Clear",
+ "devtools.archives_empty": "(no calls recorded)",
+ "devtools.archives_detail_empty": "Pick a call on the left to see details",
+ "devtools.input_title": "User input",
+ "devtools.events_title": "Stream events",
+ "devtools.output_title": "Model output",
+ "devtools.context_title": "Context",
+ "devtools.tools_title": "Available tools",
+ "devtools.copied": "Copied",
+ "devtools.copy_failed": "Copy failed: {reason}",
+ "devtools.relaunching": "Relaunching…",
+ "devtools.relaunch_confirm": "Relaunch Orkas?",
+ "devtools.relaunch_failed": "Relaunch failed: {reason}",
+ "devtools.archives.empty": "(no calls recorded)",
+ "devtools.archives.aborted": "Aborted",
+ "devtools.archives.error": "Error",
+ "devtools.archives.ok": "OK",
+ "devtools.archives.duration": "{ms}ms",
+ "devtools.archives.clear_confirm": "Clear all call archives?",
+ "devtools.archives.clear_failed": "Clear failed: {reason}",
+ "devtools.archives.refresh_failed": "Refresh failed: {reason}",
+ "devtools.archives.read_failed": "Read failed: {reason}",
+ "devtools.archives.clear_confirm2": "Clear all debug archives? This cannot be undone.",
+ "devtools.archives.badge_kind_agent": "agent",
+ "devtools.archives.badge_kind_agent_title": "Agent-edit chat",
+ "devtools.archives.badge_kind_skill": "skill",
+ "devtools.archives.badge_kind_skill_title": "Skill-edit chat",
+ "devtools.archives.badge_kind_extract_img": "img-vision",
+ "devtools.archives.badge_kind_extract_img_title": "KB image recognition",
+ "devtools.archives.badge_kind_cli": "cli",
+ "devtools.archives.badge_kind_cli_title": "Local CLI agent dispatch",
+ "devtools.archives.status_error": "Error",
+ "devtools.archives.status_aborted": "Aborted",
+ "devtools.archives.status_ok": "OK",
+ "devtools.archives.meta_start": "Start: {time}",
+ "devtools.archives.meta_duration": "Duration: {s}s",
+ "devtools.archives.meta_tokens": "Tokens: input {input} · output {output}{cache}",
+ "devtools.archives.meta_cache_hit": " · cache hit {read} ({pct}%)",
+ "devtools.archives.meta_cache_write": " · cache write {write}",
+ "devtools.archives.meta_tokens_missing": "Tokens: provider didn't report (pi-ai adapter hard-codes 0 or usage unavailable)",
+ "devtools.archives.prompt_empty": "(empty)",
+ "devtools.archives.no_events": "(no events)",
+ "devtools.archives.aborted_tag": "[aborted]",
+ "devtools.archives.error_tag": "[error] {msg}",
+ "devtools.archives.context_empty": "(none)",
+ "devtools.archives.context_skill_all": "all skills (no allowlist)",
+ "devtools.archives.context_skill_none": "(empty set, zero skills)",
+ "devtools.archives.tools_empty": "(no tools — or pre-upgrade archive)",
+ "devtools.archives.tools_source_extra": "Caller-injected (e.g. group_chat commander's plan_set / agent management tools)",
+ "devtools.archives.tools_source_orkas": "Orkas-injected (override / extension)",
+ "devtools.archives.tools_source_core_agent": "core-agent builtin",
"agent_modal.title": "New agent",
"agent_modal.tab_create": "Create",
"agent_modal.tab_external": "External",
@@ -738,6 +872,7 @@
"marketplace.uninstall_ok": "Uninstalled",
"marketplace.uninstall_failed": "Uninstall failed: {reason}",
"marketplace.search_ph": "Search",
+ "marketplace.search": "Search",
"marketplace.empty": "Nothing here yet",
"marketplace.load_failed": "Failed to load marketplace",
"marketplace.install_ok": "Installed",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index ecefa436..43ae9ebd 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -10,6 +10,7 @@
"common.close": "关闭",
"common.copy": "复制",
"common.remove": "移除",
+ "common.dev_suffix": "(开发)",
"component.enabled": "已启用",
"component.disabled": "已禁用",
"component.enable": "启用",
@@ -51,6 +52,11 @@
"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": "上传中",
@@ -82,6 +88,15 @@
"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": "过程信息",
"artifact.title": "互动应用",
"artifact.reload": "重新加载",
@@ -130,6 +145,7 @@
"chat.send_failed": "发送失败: {msg}",
"chat.interrupted": "已中断",
"chat.stream_done": "● 生成完成",
+ "chat.tool_result_expand_hint": "点击查看完整输出",
"chat.form.title": "请确认参数",
"chat.form.submit": "确认",
"chat.form.reset": "重置",
@@ -427,6 +443,56 @@
"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.storage_title": "存储空间",
+ "settings.sync.conflicts_title": "冲突记录",
+ "settings.sync.conflicts_sub": "多设备并发修改同一文件时,被覆盖的版本会保留在此。",
+ "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.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 Key 与 OAuth 令牌只保存在本机,不上云、不外发。",
@@ -594,6 +660,74 @@
"settings.metacognition.sub": "开启后,每个 Agent 会在工作一段时间后自动复盘最近的表现,总结经验、调整自己的工作方式,下次接到任务时表现更好。称为「元认知」是因为 Agent 不只在做任务,还会反思「自己做得怎样、下次怎么做更好」——这种对自身认知过程的认知就是元认知。关闭后 Agent 不再自动复盘。",
"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": "模型原生联网搜索",
+ "devtools.native_search_sub": "开启后在支持的模型上注入模型原生搜索工具;内存态,重启默认 on",
+ "devtools.native_search_toggle": "启用模型原生 web search(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": "成功",
+ "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": "agent",
+ "devtools.archives.badge_kind_agent_title": "智能体编辑会话",
+ "devtools.archives.badge_kind_skill": "skill",
+ "devtools.archives.badge_kind_skill_title": "技能编辑会话",
+ "devtools.archives.badge_kind_extract_img": "img-vision",
+ "devtools.archives.badge_kind_extract_img_title": "知识库图片识别",
+ "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": "成功",
+ "devtools.archives.meta_start": "开始: {time}",
+ "devtools.archives.meta_duration": "耗时: {s}s",
+ "devtools.archives.meta_tokens": "Tokens: 输入 {input} · 输出 {output}{cache}",
+ "devtools.archives.meta_cache_hit": " · 缓存命中 {read} ({pct}%)",
+ "devtools.archives.meta_cache_write": " · 缓存写入 {write}",
+ "devtools.archives.meta_tokens_missing": "Tokens: 该 provider 未上报(pi-ai 未透传或 usage 为 0)",
+ "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": "(空集,零技能)",
+ "devtools.archives.tools_empty": "(无工具或非新版本存档)",
+ "devtools.archives.tools_source_extra": "调用方注入(如群聊 commander 的 plan_set / agent 管理工具)",
+ "devtools.archives.tools_source_orkas": "Orkas 注入(覆盖 / 扩展)",
+ "devtools.archives.tools_source_core_agent": "core-agent 内置",
"agent_modal.title": "新建智能体",
"agent_modal.tab_create": "创建",
"agent_modal.tab_external": "外接",
@@ -738,6 +872,7 @@
"marketplace.uninstall_ok": "已卸载",
"marketplace.uninstall_failed": "卸载失败:{reason}",
"marketplace.search_ph": "搜索",
+ "marketplace.search": "搜索",
"marketplace.empty": "暂无内容",
"marketplace.load_failed": "加载失败",
"marketplace.install_ok": "安装成功",
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 5411f9c3..3dfa4464 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -378,10 +378,16 @@ function _renderAgentRowMenuItems(menu, agentId) {
const enabled = a ? a.enabled !== false : true;
const isCustom = a?.source === 'custom';
const canEdit = isCustom;
+ // Dev mode lifts the source guard for built-in edit / delete; custom adds
+ // a "promote to built-in" item too.
+ const canEdit = isCustom || (a?.source === 'builtin' && false);
+ // Dev-only entry on builtin: tag the label so the user knows this isn't a
+ // normal user capability (mirrors marketplace.upload's "(dev)" treatment).
+ const editLabelSuffix = (a?.source === 'builtin' && false) ? t('common.dev_suffix') : '';
const toggleLabel = enabled ? t('component.disable') : t('component.enable');
const items = [];
if (canEdit) {
- items.push(`<div class="agent-row-menu-item" data-action="edit">${escapeHtml(t('agents.edit'))}</div>`);
+ items.push(`<div class="agent-row-menu-item" data-action="edit">${escapeHtml(t('agents.edit') + editLabelSuffix)}</div>`);
}
if (isCustom && false) {
items.push(`<div class="agent-row-menu-item" data-action="promote">${escapeHtml(t('agents.promote_to_builtin'))}</div>`);
@@ -559,7 +565,11 @@ function _renderAgentDetail(agent, editing) {
if (delBtn) delBtn.style.display = (canEdit && !editing) ? '' : 'none';
if (editBtn) {
editBtn.style.display = canEdit ? '' : 'none';
- editBtn.textContent = editing ? t('agents.edit_btn_done') : t('agents.edit_btn_edit');
+ // Tag the "Edit" label on builtin agents (dev-only entry); "Done" stays
+ // bare because the user is already in edit mode and the marker would be
+ // redundant noise.
+ const editSuffix = (!editing && agent.source === 'builtin' && false) ? t('common.dev_suffix') : '';
+ editBtn.textContent = editing ? t('agents.edit_btn_done') : (t('agents.edit_btn_edit') + editSuffix);
}
_renderAgentEnabledButton({ id: agent.agent_id, enabled: agent.enabled !== false });
diff --git a/src/renderer/modules/chat-file-viewer.js b/src/renderer/modules/chat-file-viewer.js
new file mode 100644
index 00000000..2348077b
--- /dev/null
+++ b/src/renderer/modules/chat-file-viewer.js
@@ -0,0 +1,375 @@
+// ─── Chat file preview ────────────────────────────────────────────────
+// In-app overlay for files the LLM produced (green chips) and for non-image
+// user attachment chips. Mirrors `chat-lightbox.js`'s lazy-singleton pattern;
+// kept separate from it because the renderer logic per kind diverges enough
+// (iframe vs. <div> vs. <pre> body, no zoom/pan) that one merged module
+// would just be two co-located if-trees.
+//
+// Render strategies:
+// image (.png/.jpg/.jpeg/.webp/.gif) → delegate to openChatImageLightbox
+// pdf (.pdf) → <iframe> + Chromium PDFium
+// html (.html/.htm) → sandbox="allow-scripts" iframe
+// md (.md/.markdown) → renderMarkdown(text) in a <div>
+// text (.txt/.json/.csv/.code…) → <pre> with the source
+// else → uiConfirm "Open the folder?"
+//
+// chat-media://local/<abs> serves pdf/html bytes (streamed via
+// serveFileRange — no JS-heap explosion even on huge files). Markdown / text
+// go via the `produced.readText` IPC; that path slurps the whole file into
+// the JS heap and crosses IPC, hence the 2 MB cap on the main side, hence
+// the "too large → open folder" fallback below.
+//
+// Security:
+// - HTML iframe sandbox is "allow-scripts" ONLY — no allow-same-origin,
+// no allow-popups, no allow-top-navigation. `chat-media://` origin ≠
+// renderer origin, so SOP already blocks parent.* access; the sandbox
+// flags pre-empt top-window navigation and new-window pop.
+// - The reveal-in-folder header button goes through workspace.revealPath,
+// which the main process re-validates against the workspace + attachment
+// scope.
+//
+// Usage:
+// openChatFileViewer(absPath, displayName?, opts?)
+// opts.cid — pass through when the file is a per-conv attachment, so
+// main can include the cid's attachment dir in the reveal /
+// read scope. Workspace-only paths can omit it.
+
+let _viewerEl = null;
+let _viewerBody = null;
+let _viewerTitle = null;
+let _viewerRevealBtn = null;
+let _viewerKeyHandler = null;
+let _viewerCurrentPath = null;
+let _viewerCurrentCid = null;
+
+const _viewerLog = (typeof createLogger === 'function')
+ ? createLogger('chat-file-viewer')
+ : { warn: () => {}, info: () => {}, error: () => {} };
+
+// Extensions we'll try to render inline. Anything else falls through to the
+// "unsupported — open folder?" dialog. Lists are intentionally narrow:
+// 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 _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
+// highlighting in this round; <pre> with white-space:pre-wrap is enough.
+const _TEXT_EXTS = new Set([
+ '.txt', '.log',
+ '.csv', '.tsv',
+ '.json', '.yaml', '.yml',
+ '.xml', '.ini', '.toml', '.conf',
+ '.py', '.pyi',
+ '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',
+ '.sh', '.bash', '.zsh',
+ '.rb', '.go', '.rs', '.java', '.kt',
+ '.c', '.cpp', '.cc', '.h', '.hpp',
+ '.css', '.scss', '.less',
+ '.sql', '.graphql', '.gql',
+]);
+
+function _extOf(name) {
+ if (!name) return '';
+ const i = name.lastIndexOf('.');
+ return i >= 0 ? name.slice(i).toLowerCase() : '';
+}
+
+// Pure kind classifier. Exposed as `_kindOf` for fixture tests via the
+// CJS-bridge at the bottom of this file (PC/CLAUDE.md §9 escape hatch).
+function _kindOf(name) {
+ const ext = _extOf(name);
+ if (_IMAGE_EXTS.has(ext)) return 'image';
+ if (ext === '.pdf') return 'pdf';
+ if (ext === '.html' || ext === '.htm') return 'html';
+ if (_MARKDOWN_EXTS.has(ext)) return 'markdown';
+ if (_TEXT_EXTS.has(ext)) return 'text';
+ return 'unsupported';
+}
+
+// Build `chat-media://local/<abs>` URL. Matches main-side _pathnameToAbsPath:
+// strip the leading `/` on Unix (the parser adds it back via pathname); on
+// Windows replace `\` with `/`. encodeURI (not encodeURIComponent) preserves
+// the `/` separators while escaping spaces / non-ASCII so URL parsing on
+// the main side stays well-formed.
+function _chatMediaLocalUrl(absPath) {
+ let p = String(absPath || '');
+ // Normalize Windows drive paths: `C:\a\b` → `C:/a/b`.
+ if (p.includes('\\')) p = p.replace(/\\/g, '/');
+ // Strip the single leading slash on Unix so the abs path becomes the URL
+ // path; main re-adds it. Win paths start with `C:` so this branch is a
+ // no-op there.
+ if (p.startsWith('/')) p = p.slice(1);
+ return `chat-media://local/${encodeURI(p)}`;
+}
+
+// Localized label helper — falls back to the English fallback when i18n
+// tables aren't loaded yet (mirrors dialogs.js).
+function _viewerLabel(key, fallback) {
+ try { const v = t(key); return v === key ? fallback : v; } catch (_) { return fallback; }
+}
+
+function _isViewerOpen() {
+ return !!(_viewerEl && _viewerEl.classList.contains('is-open'));
+}
+
+function _ensureViewer() {
+ if (_viewerEl) return _viewerEl;
+ const root = document.createElement('div');
+ root.className = 'chat-file-viewer';
+ 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>';
+ 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-close" aria-label="${closeLabel}" title="${closeLabel}">×</button>
+ </div>
+ </div>
+ <div class="chat-file-viewer-body"></div>
+ </div>
+ `;
+ document.body.appendChild(root);
+
+ _viewerEl = root;
+ _viewerBody = root.querySelector('.chat-file-viewer-body');
+ _viewerTitle = root.querySelector('.chat-file-viewer-title');
+ _viewerRevealBtn = root.querySelector('.chat-file-viewer-reveal');
+
+ // i18n change → re-label the icon-only buttons. Same lazy listener pattern
+ // as chat-lightbox; the singleton is created on first open so the
+ // listener doesn't leak per re-open.
+ window.addEventListener('i18n-change', () => {
+ if (!_viewerEl) return;
+ const c = _viewerEl.querySelector('.chat-file-viewer-close');
+ const r = _viewerEl.querySelector('.chat-file-viewer-reveal');
+ const cl = _viewerLabel('chat.preview_close_title', 'Close');
+ const rl = _viewerLabel('chat.preview_reveal_title', 'Open in folder');
+ if (c) { c.setAttribute('aria-label', cl); c.setAttribute('title', cl); }
+ if (r) { r.setAttribute('aria-label', rl); r.setAttribute('title', rl); }
+ });
+
+ root.querySelector('.chat-file-viewer-backdrop').addEventListener('click', closeChatFileViewer);
+ root.querySelector('.chat-file-viewer-close').addEventListener('click', closeChatFileViewer);
+ _viewerRevealBtn.addEventListener('click', _onRevealClick);
+
+ return root;
+}
+
+async function _onRevealClick() {
+ const p = _viewerCurrentPath;
+ if (!p) return;
+ try {
+ const payload = { path: p };
+ if (_viewerCurrentCid) payload.cid = _viewerCurrentCid;
+ const res = await window.orkas.invoke('workspace.revealPath', payload);
+ if (!res || !res.ok) {
+ _viewerLog.warn('reveal failed', { path: p, error: res && res.error });
+ }
+ } catch (err) {
+ _viewerLog.warn('reveal threw', { path: p, error: String(err && err.message || err) });
+ }
+}
+
+function _openViewerShell(displayName) {
+ const el = _ensureViewer();
+ _viewerTitle.textContent = displayName || '';
+ _viewerBody.innerHTML = '';
+ el.classList.add('is-open');
+ el.setAttribute('aria-hidden', 'false');
+ if (!_viewerKeyHandler) {
+ _viewerKeyHandler = (e) => {
+ if (!_isViewerOpen()) return;
+ // IME guard: Esc commits IME composition cancel — don't double-fire close.
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Escape') closeChatFileViewer();
+ };
+ document.addEventListener('keydown', _viewerKeyHandler);
+ }
+ return el;
+}
+
+function closeChatFileViewer() {
+ if (!_viewerEl) return;
+ _viewerEl.classList.remove('is-open');
+ _viewerEl.setAttribute('aria-hidden', 'true');
+ // Drop iframe / blob src so big preview docs can be GC'd promptly when
+ // the user closes the overlay. Without this, hidden iframes keep the
+ // PDFium / HTML document alive in memory until the next reopen.
+ if (_viewerBody) _viewerBody.innerHTML = '';
+ _viewerCurrentPath = null;
+ _viewerCurrentCid = null;
+ if (_viewerKeyHandler) {
+ document.removeEventListener('keydown', _viewerKeyHandler);
+ _viewerKeyHandler = null;
+ }
+}
+
+// ── Per-kind body builders ───────────────────────────────────────────────
+
+function _renderPdfBody(absPath, displayName) {
+ _openViewerShell(displayName);
+ const url = _chatMediaLocalUrl(absPath);
+ // `#toolbar=1&navpanes=0` are Chromium PDFium control hints (keep toolbar,
+ // hide left sidebar). Same pattern as the KB context PDF viewer.
+ _viewerBody.innerHTML = `<iframe class="chat-file-viewer-pdf" src="${url}#toolbar=1&navpanes=0" title="${escapeHtml(displayName || '')}"></iframe>`;
+}
+
+function _renderHtmlBody(absPath, displayName) {
+ _openViewerShell(displayName);
+ const url = _chatMediaLocalUrl(absPath);
+ // sandbox: allow-scripts ONLY. chat-media:// is a distinct origin from
+ // file://, so SOP blocks parent.* access; we additionally forbid
+ // allow-same-origin (no cookie / localStorage / sibling-fetch reach),
+ // allow-popups (no window.open), and allow-top-navigation (no top-frame
+ // redirects). Self-contained LLM-generated HTML still runs its inline
+ // scripts and styles.
+ const sandbox = 'allow-scripts';
+ _viewerBody.innerHTML = `<iframe class="chat-file-viewer-html" sandbox="${sandbox}" src="${url}" title="${escapeHtml(displayName || '')}"></iframe>`;
+}
+
+async function _renderMarkdownBody(absPath, displayName, cid) {
+ _openViewerShell(displayName);
+ _viewerBody.innerHTML = `<div class="chat-file-viewer-loading">…</div>`;
+ const text = await _readTextFile(absPath, cid);
+ if (text === null) return; // _readTextFile already routed to the fallback dialog
+ // renderMarkdown is the single markdown surface; matches chat bubbles so
+ // generated reports look identical here and inline.
+ const md = (typeof renderMarkdown === 'function') ? renderMarkdown(text) : escapeHtml(text);
+ _viewerBody.innerHTML = `<div class="chat-file-viewer-md">${md}</div>`;
+ // Same async LaTeX typeset chat bubbles use. Skipped silently if math.js
+ // isn't loaded (e.g. tests).
+ if (typeof typesetMath === 'function') {
+ try { typesetMath(_viewerBody); } catch (_) { /* non-fatal */ }
+ }
+}
+
+async function _renderTextBody(absPath, displayName, cid) {
+ _openViewerShell(displayName);
+ _viewerBody.innerHTML = `<div class="chat-file-viewer-loading">…</div>`;
+ const text = await _readTextFile(absPath, cid);
+ if (text === null) return;
+ _viewerBody.innerHTML = `<pre class="chat-file-viewer-text">${escapeHtml(text)}</pre>`;
+}
+
+// Fetch a file's text via IPC. Returns the text on success; on rejection
+// surfaces the fallback dialog (and returns null so the caller knows to
+// stop). Closes the overlay before showing the dialog so it doesn't stack
+// on top of a half-built viewer.
+async function _readTextFile(absPath, cid) {
+ _viewerCurrentPath = absPath;
+ _viewerCurrentCid = cid || null;
+ try {
+ const payload = { path: absPath };
+ if (cid) payload.cid = cid;
+ const res = await window.orkas.invoke('produced.readText', payload);
+ if (res && res.ok) return String(res.text || '');
+ // Specifically distinguish too_large so the user sees "file is X MB,
+ // open in folder?" instead of a generic failure.
+ const err = (res && res.error) || 'unknown';
+ closeChatFileViewer();
+ if (err === 'too_large') {
+ const sizeMb = ((res && res.size) || 0) / 1024 / 1024;
+ const capMb = ((res && res.cap) || 2 * 1024 * 1024) / 1024 / 1024;
+ await _showUnsupportedDialog(absPath, cid, {
+ messageKey: 'chat.preview_too_large_message',
+ vars: { name: absPath.split(/[\\/]/).pop() || absPath, size: sizeMb.toFixed(1), cap: capMb.toFixed(0) },
+ fallback: `File is ${sizeMb.toFixed(1)} MB (over the ${capMb.toFixed(0)} MB preview cap). Open the containing folder?`,
+ });
+ } else {
+ await _showUnsupportedDialog(absPath, cid, {
+ messageKey: 'chat.preview_read_failed_message',
+ vars: { name: absPath.split(/[\\/]/).pop() || absPath },
+ fallback: 'Could not read this file. Open the containing folder?',
+ });
+ }
+ return null;
+ } catch (e) {
+ _viewerLog.warn('readText threw', { path: absPath, error: String(e && e.message || e) });
+ closeChatFileViewer();
+ await _showUnsupportedDialog(absPath, cid, {
+ messageKey: 'chat.preview_read_failed_message',
+ vars: { name: absPath.split(/[\\/]/).pop() || absPath },
+ fallback: 'Could not read this file. Open the containing folder?',
+ });
+ return null;
+ }
+}
+
+// Fallback dialog: explain to the user that we can't preview this file
+// inline, and offer to open the folder it lives in. uiConfirm returns true
+// on the (relabeled) primary button.
+async function _showUnsupportedDialog(absPath, cid, opts) {
+ const name = absPath.split(/[\\/]/).pop() || absPath;
+ const ext = _extOf(name) || _viewerLabel('chat.preview_unsupported_no_ext', '(no extension)');
+ const message = opts && opts.messageKey
+ ? _viewerLabel(opts.messageKey, opts.fallback || '')
+ : _viewerLabel('chat.preview_unsupported_message', `Cannot preview ${ext} files in app. Open the containing folder?`);
+ // i18n substitution: do the {var} replace ourselves — `t()` only
+ // substitutes when called with `vars`, but _viewerLabel hides that. Reach
+ // through to `t` directly with vars when we have them.
+ let final = message;
+ if (opts && opts.vars && typeof t === 'function') {
+ try {
+ const v = t(opts.messageKey, opts.vars);
+ if (v && v !== opts.messageKey) final = v;
+ } catch (_) { /* keep fallback */ }
+ } else if (typeof t === 'function') {
+ try {
+ const v = t('chat.preview_unsupported_message', { ext });
+ if (v && v !== 'chat.preview_unsupported_message') final = v;
+ } catch (_) { /* keep fallback */ }
+ }
+ const okLabel = _viewerLabel('chat.preview_unsupported_reveal', 'Open Folder');
+ const cancelLabel = _viewerLabel('chat.preview_cancel', 'Close');
+ const ok = await uiConfirm({ message: final, okLabel, cancelLabel });
+ if (!ok) return;
+ try {
+ const payload = { path: absPath };
+ if (cid) payload.cid = cid;
+ const res = await window.orkas.invoke('workspace.revealPath', payload);
+ if (!res || !res.ok) _viewerLog.warn('fallback reveal failed', { path: absPath, error: res && res.error });
+ } catch (err) {
+ _viewerLog.warn('fallback reveal threw', { path: absPath, error: String(err && err.message || err) });
+ }
+}
+
+// ── Public entry point ───────────────────────────────────────────────────
+
+function openChatFileViewer(absPath, displayName, opts) {
+ if (!absPath) return;
+ const cid = (opts && opts.cid) || null;
+ const name = displayName || (absPath.split(/[\\/]/).pop() || absPath);
+ const kind = _kindOf(name);
+ _viewerCurrentPath = absPath;
+ _viewerCurrentCid = cid;
+
+ if (kind === 'image') {
+ // Delegate — the image lightbox already has zoom / pan / keyboard. We
+ // need the chat-media:// URL since openChatImageLightbox expects an
+ // <img>-loadable src, not an abs path.
+ if (typeof openChatImageLightbox === 'function') {
+ openChatImageLightbox(_chatMediaLocalUrl(absPath), name);
+ }
+ return;
+ }
+ if (kind === 'pdf') return _renderPdfBody(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);
+ // unsupported — go straight to the dialog, never open the shell.
+ return _showUnsupportedDialog(absPath, cid, {});
+}
+
+// CJS bridge for vitest — pure functions only, per PC/CLAUDE.md §9.
+if (typeof module !== 'undefined' && typeof module.exports === 'object') {
+ module.exports = { _kindOf, _extOf, _chatMediaLocalUrl };
+}
diff --git a/src/renderer/modules/chat-input-form.js b/src/renderer/modules/chat-input-form.js
index 297ede37..432da22a 100644
--- a/src/renderer/modules/chat-input-form.js
+++ b/src/renderer/modules/chat-input-form.js
@@ -198,7 +198,7 @@
const changePill = document.createElement('span');
changePill.className = 'form-field-dir-change';
- changePill.textContent = t('input.dir.change') || 'Change';
+ changePill.textContent = t('input.dir.change');
card.appendChild(changePill);
let value = (typeof initial === 'string' && initial) ? initial : '';
@@ -210,7 +210,7 @@
changePill.style.display = '';
card.classList.remove('is-empty');
} else {
- pathLabel.textContent = t('input.dir.pick') || 'Pick directory…';
+ pathLabel.textContent = t('input.dir.pick');
pathLabel.removeAttribute('title');
pathLabel.classList.add('is-empty');
changePill.style.display = 'none';
diff --git a/src/renderer/modules/chat-lightbox.js b/src/renderer/modules/chat-lightbox.js
index 9271d194..06014b96 100644
--- a/src/renderer/modules/chat-lightbox.js
+++ b/src/renderer/modules/chat-lightbox.js
@@ -138,7 +138,7 @@ function _ensureLightbox() {
const root = document.createElement('div');
root.className = 'chat-lightbox';
root.setAttribute('aria-hidden', 'true');
- const closeLabel = typeof t === 'function' ? t('chat.lightbox_close_title') : 'Close';
+ const closeLabel = t('chat.lightbox_close_title');
root.innerHTML = `
<div class="chat-lightbox-backdrop"></div>
<div class="chat-lightbox-stage">
@@ -155,7 +155,7 @@ function _ensureLightbox() {
if (!_lightboxEl) return;
const btn = _lightboxEl.querySelector('.chat-lightbox-close');
if (btn) {
- const label = typeof t === 'function' ? t('chat.lightbox_close_title') : 'Close';
+ const label = t('chat.lightbox_close_title');
btn.setAttribute('aria-label', label);
btn.setAttribute('title', label);
}
diff --git a/src/renderer/modules/contexts.js b/src/renderer/modules/contexts.js
index 0b12684d..aab8035d 100644
--- a/src/renderer/modules/contexts.js
+++ b/src/renderer/modules/contexts.js
@@ -650,7 +650,7 @@ window.saveCtxNew = saveCtxNew;
// for inline rename on the next tree render, and immediately drops the
// viewer into edit mode so the user can start typing content.
async function createCtxNewTextFile(parentDir = '') {
- const stemBase = t('contexts.new.untitled_stem') || 'untitled';
+ const stemBase = t('contexts.new.untitled_stem');
// Collect sibling file names so we can uniquify if a conflict exists.
const siblings = _ctxListChildren(parentDir).map(n => n.name);
let stem = stemBase;
@@ -685,14 +685,14 @@ async function createCtxNewTextFile(parentDir = '') {
// behavior is layered on by the KB viewer; the file itself stays portable
// and indexable like any other md note.
async function createCtxNewTodoFile(parentDir = '') {
- const stemBase = t('contexts.new.todo_stem') || 'todo list';
+ const stemBase = t('contexts.new.todo_stem');
const siblings = _ctxListChildren(parentDir).map(n => n.name);
let stem = stemBase;
let i = 2;
while (siblings.includes(`${stem}.md`)) { stem = `${stemBase} ${i++}`; }
const name = `${stem}.md`;
const fullPath = parentDir ? `${parentDir}/${name}` : name;
- const heading = t('contexts.new.todo_template_heading') || 'Todo';
+ const heading = t('contexts.new.todo_template_heading');
const template = `# ${heading}\n\n- [ ] \n- [ ] \n- [ ] \n`;
try {
const res = await apiFetch('/api/contexts/write', {
@@ -1322,7 +1322,7 @@ function _ctxApplyTodo(ta) {
const { lineStart, lineEnd } = _ctxLineSpan(value, ta.selectionStart, ta.selectionEnd);
const block = value.slice(lineStart, lineEnd);
const lines = block.split('\n');
- const placeholder = t('contexts.editor.placeholder.todo') || 'task';
+ const placeholder = t('contexts.editor.placeholder.todo');
// Pick the mode from the first non-empty line.
const firstNonEmpty = lines.find(l => l.trim().length > 0) || '';
let mode;
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index f3ddbf7b..5524471e 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -292,7 +292,7 @@ function _renderRecipientChip(target) {
nameEl.removeAttribute('data-i18n');
} else {
nameEl.setAttribute('data-i18n', 'chat.recipient_commander');
- nameEl.textContent = (typeof t === 'function') ? t('chat.recipient_commander') : 'Commander';
+ nameEl.textContent = t('chat.recipient_commander');
}
}
}
@@ -622,7 +622,7 @@ function _renderActorAvatarHtml(fromId) {
* (deleted agents whose old chats still need a label). */
function _groupActorLabel(fromId) {
if (fromId === 'user') return null;
- if (fromId === 'commander') return t('chat.from_commander') || 'Commander';
+ if (fromId === 'commander') return t('chat.from_commander');
if (typeof _agentsCache !== 'undefined' && Array.isArray(_agentsCache)) {
const a = _agentsCache.find((x) => x && x.agent_id === fromId);
if (a && a.name) return a.name;
@@ -635,7 +635,7 @@ function _groupActorLabel(fromId) {
// Last resort: never leak the id. Show a neutral placeholder; the chip
// will repaint as soon as the cache catches up (state_changed handler
// refreshes _groupMembersCache).
- return t('chat.from_agent_unknown') || 'Agent';
+ return t('chat.from_agent_unknown');
}
const _groupMembersCache = new Map(); // cid → Actor[]
async function _refreshGroupMembers(cid) {
@@ -978,8 +978,10 @@ function _renderMessageAttachmentsHtml(names, cid) {
// ── Produced files (assistant messages only) ─────────────────────────────
// Files written by the LLM via write_file / markdown_to_pdf / html_to_pdf.
-// Chips use the same visual language as attachments; clicking invokes
-// `workspace.revealPath` which calls shell.showItemInFolder in main.
+// Chips use the same visual language as attachments; clicking opens an
+// in-app preview overlay (chat-file-viewer.js) that renders the file's
+// final form (PDF / HTML / markdown / text) or falls through to a dialog
+// offering "open the containing folder" for unsupported kinds.
function _iconForProduced(name) {
const ext = (name.split('.').pop() || '').toLowerCase();
@@ -1009,10 +1011,9 @@ function _iconForProduced(name) {
function _renderMessageProducedHtml(absPaths) {
// Chip shows just the filename. The full absolute path lives only in
// `data-produced-path` for the click handler; tooltip is a static
- // localized "show in folder" hint instead of the raw OS path (which
- // exposes the user's home directory and is hostile UX in mixed-locale
- // contexts).
- const hint = t('chat.produced_reveal_title') || 'Show in folder';
+ // localized "preview" hint instead of the raw OS path (which exposes
+ // the user's home directory and is hostile UX in mixed-locale contexts).
+ const hint = t('chat.produced_preview_title');
const items = absPaths.map((p) => {
const base = p.split(/[\\/]/).pop() || p;
const icon = _iconForProduced(base);
@@ -1109,38 +1110,62 @@ function _hydrateMessageCreatedSkillChip(msgDiv) {
function _hydrateMessageProducedChips(msgDiv) {
const chips = msgDiv.querySelectorAll('.chat-msg-produced-item');
chips.forEach((chip) => {
- chip.addEventListener('click', async (e) => {
+ chip.addEventListener('click', (e) => {
e.stopPropagation();
const p = chip.dataset.producedPath;
if (!p) return;
- // Opens the OS file manager focused on the file (Finder on macOS,
- // Explorer on Windows). The main-process handler validates the
- // path is inside the active workspace and refuses outside paths.
- try {
- const res = await window.orkas.invoke('workspace.revealPath', { path: p });
- if (!res || !res.ok) {
- _convLog.warn('reveal failed', { path: p, error: res && res.error });
- }
- } catch (err) {
- _convLog.warn('reveal threw', { path: p, error: String(err && err.message || err) });
+ // chat-file-viewer dispatches by extension to in-app preview overlay
+ // or, on unsupported kinds, an "open folder?" fallback dialog.
+ if (typeof openChatFileViewer === 'function') {
+ const base = p.split(/[\\/]/).pop() || p;
+ openChatFileViewer(p, base);
}
});
});
}
-function _hydrateMessageAttachmentThumbs(msgDiv, _cid) {
- // Wire click-to-enlarge on image chips. Image bytes are served by the
- // `chat-media://` protocol directly (no IPC fetch here). If the underlying
- // file was deleted, the <img> will fail silently and the chip shows the
- // broken-image placeholder — not worth hiding, the user chose to delete it.
- const images = msgDiv.querySelectorAll('.chat-msg-attach.is-image');
- images.forEach((chip) => {
- const img = chip.querySelector('img.chat-msg-attach-thumb');
- if (!img) return;
- chip.addEventListener('click', (e) => {
+function _hydrateMessageAttachmentThumbs(msgDiv, cid) {
+ // Image chips have a thumb we want to enlarge via the lightbox; the rest
+ // (pdf / docx / text / video) get the same kind-aware viewer as produced
+ // chips. Video chips have inline <video> controls in the bubble already,
+ // so clicking the chip body shouldn't re-open the same playback — skip
+ // them. We rely on `_chatMediaUrl(cid, name)` having loaded the bytes for
+ // images so the lightbox can reuse the already-cached resource.
+ const allChips = msgDiv.querySelectorAll('.chat-msg-attach');
+ allChips.forEach((chip) => {
+ if (chip.classList.contains('is-video')) return;
+ if (chip.classList.contains('is-image')) {
+ const img = chip.querySelector('img.chat-msg-attach-thumb');
+ if (!img) return;
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ if (typeof openChatImageLightbox === 'function') {
+ openChatImageLightbox(img.src, chip.dataset.attachName || '');
+ }
+ });
+ return;
+ }
+ // Non-image, non-video attachment chip → open the file viewer. The
+ // chip carries `(cid, name)`, not an absolute path; resolve via
+ // `attachments.absPath` so the viewer keeps a single "abs path in"
+ // contract. cid flows through to the viewer so reveal / read scope
+ // includes the per-conversation attachment dir.
+ const name = chip.dataset.attachName || (chip.querySelector('.chat-msg-attach-label')?.textContent || '').trim();
+ const chipCid = chip.dataset.attachCid || cid;
+ if (!name || !chipCid) return;
+ chip.classList.add('is-clickable');
+ chip.addEventListener('click', async (e) => {
e.stopPropagation();
- if (typeof openChatImageLightbox === 'function') {
- openChatImageLightbox(img.src, chip.dataset.attachName || '');
+ if (typeof openChatFileViewer !== 'function') return;
+ try {
+ const res = await window.orkas.invoke('attachments.absPath', { cid: chipCid, name });
+ if (!res || !res.ok || !res.path) {
+ _convLog.warn('attachments.absPath failed', { cid: chipCid, name, error: res && res.error });
+ return;
+ }
+ openChatFileViewer(res.path, name, { cid: chipCid });
+ } catch (err) {
+ _convLog.warn('attachments.absPath threw', { cid: chipCid, name, error: String(err && err.message || err) });
}
});
});
@@ -1682,13 +1707,13 @@ function appendChatMessage(message, autoScroll = true, opts = {}) {
? ''
: _groupActorLabel(message._from || (message._from_label ? '' : ''))
|| message._from_label
- || (t('chat.from_agent_unknown') || 'Agent');
+ || (t('chat.from_agent_unknown'));
const avatarHtml = role === 'user' ? '' : _renderActorAvatarHtml(message._from);
const headerHtml = role === 'user'
? `<div class="chat-msg-header chat-msg-header-user"><span class="chat-msg-time">${formatTime(message.time || new Date().toISOString())}</span></div>`
: `<div class="chat-msg-header">${avatarHtml}<span class="chat-msg-from">${escapeHtml(headerName)}</span><span class="chat-msg-time">${formatTime(message.time || new Date().toISOString())}</span></div>`;
const planAnnHtml = message._plan_announcement
- ? `<div class="chat-plan-announce">📋 ${escapeHtml(t('chat.plan_announce') || 'Plan')}</div>` : '';
+ ? `<div class="chat-plan-announce">📋 ${escapeHtml(t('chat.plan_announce'))}</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.
@@ -1901,9 +1926,9 @@ function _renderQuotePreview() {
// capture flow through naturally; fall back to the click-time snapshot
// when the actor was deleted between capture and render.
const liveName = q.fromActor === 'commander'
- ? (t('chat.from_commander') || 'Commander')
+ ? (t('chat.from_commander'))
: _groupActorLabel(q.fromActor);
- const fromName = liveName || q.fromName || (t('chat.from_agent_unknown') || 'Agent');
+ const fromName = liveName || q.fromName || (t('chat.from_agent_unknown'));
const trunc = String(q.text || '');
const fileChips = (q.produced || []).map((p) => {
const base = String(p || '').split(/[\\/]/).pop() || p;
@@ -1988,6 +2013,7 @@ function _attachBubbleArchiveBtn(msgDiv, getContent) {
} catch (_) { produced = []; }
const fromName = fromActor === 'commander'
? (t('chat.from_commander') || 'Commander')
+ ? (t('chat.from_commander'))
: (_groupActorLabel(fromActor) || '');
_setQuote(currentCid, { fromActor, fromName, msgId, text, produced });
const input = document.getElementById('chat-input');
@@ -2475,7 +2501,8 @@ function _processKindOf(text) {
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 === '◆' || g === '◇') return 'think'; // reasoning / reply marker
+ 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
@@ -3268,8 +3295,8 @@ function _setPlaceholderActor(ph, actorId) {
const chip = ph.querySelector('[data-role="from-chip"]');
if (chip && !chip.textContent) {
const label = actorId === 'commander'
- ? (t('chat.from_commander') || 'Commander')
- : (_groupActorLabel(actorId) || (t('chat.from_agent_unknown') || 'Agent'));
+ ? (t('chat.from_commander'))
+ : (_groupActorLabel(actorId) || (t('chat.from_agent_unknown')));
chip.textContent = label;
}
const avatarSlot = ph.querySelector('[data-role="from-avatar"]');
@@ -3358,7 +3385,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') || 'Plan'}`;
+ lbl.textContent = `📋 ${t('chat.plan_announce')}`;
bubble.insertBefore(lbl, bubble.firstChild);
}
}
@@ -4045,9 +4072,54 @@ function _formatEventLine(evt) {
// 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
+ // attach it to claude's `result` status so users see token count
+ // on every turn). Order: model · in/out/total · cache(read/write)
+ // · cost — keeps the eye-magnets (total tokens) center-left and
+ // the slow-changing model name first. Helper inlined to avoid
+ // scope leakage.
+ const usageSuffix = (() => {
+ const u = data?.usage;
+ if (!u || typeof u !== 'object') return '';
+ const parts = [];
+ if (typeof u.model === 'string' && u.model) parts.push(u.model);
+ const tokParts = [];
+ if (typeof u.input === 'number') tokParts.push('in=' + u.input);
+ if (typeof u.output === 'number') tokParts.push('out=' + u.output);
+ // Show total only when both halves are present, otherwise the
+ // number is misleading (we don't know what's missing).
+ if (typeof u.input === 'number' && typeof u.output === 'number') {
+ tokParts.push('total=' + (u.input + u.output));
+ }
+ 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
+ // 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);
+ if (typeof u.cacheCreate === 'number') cacheParts.push('cache_write=' + u.cacheCreate);
+ if (cacheParts.length) parts.push(cacheParts.join(' '));
+ if (typeof u.cost === 'number') {
+ // 4 decimals catches sub-cent calls; rstrip trailing zeros
+ // to keep $0.5 from rendering as $0.5000.
+ const cents = u.cost.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
+ parts.push('$' + cents);
+ }
+ return parts.length ? ' · ' + parts.join(' · ') : '';
+ })();
+ if (st === 'usage') {
+ // Streaming token-counter pulse (codex / opencode). Render as
+ // a milestone-style row so the rail's last-line coalescing
+ // can update it in place when the numbers advance, rather
+ // than appending one row per pulse. See _renderAgentEvent
+ // for the in-place update logic.
+ if (!usageSuffix) return null;
+ return '● tokens' + usageSuffix;
+ }
if (st === 'session_ready' || st === 'running') return `▶ ${st}`;
- if (st === 'result' || st === 'completed') return `● ${st}`;
- if (st === 'error' || st === 'failed' || st === 'timeout') 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}`;
}
@@ -4061,6 +4133,52 @@ function _formatEventLine(evt) {
return `○ ${trimmed}`;
}
// Unknown CLI event types: hide rather than dump JSON.
+ if (cliType === 'log') {
+ // Structured CLI log records. claude --verbose / codex unknown
+ // notifications / opencode step_finish / acp commands_update all
+ // funnel here. Level decides the kind class so warn lands amber,
+ // error red, debug/info gray.
+ const level = String(data?.level || 'info').toLowerCase();
+ 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}`;
+ }
+ if (cliType === 'raw-line') {
+ // Non-JSON stdout that the backend couldn't parse as its protocol
+ // (banner, debug noise, mid-run print). Render as kind-meta so it
+ // doesn't pretend to be a structured event.
+ 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}`;
+ }
+ if (cliType === 'permission-request') {
+ // Auto-approved tool-use request the CLI gated through
+ // 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';
+ let inputSummary = '';
+ if (data?.input != null) {
+ const s = typeof data.input === 'string' ? data.input : JSON.stringify(data.input);
+ inputSummary = s.replace(/\s+/g, ' ').trim();
+ if (inputSummary.length > 120) inputSummary = inputSummary.slice(0, 120) + '…';
+ }
+ 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`;
+ }
+ // Unknown CLI event types: hide rather than dump JSON. Devtools archive
+ // still records them verbatim under `<uid>/local/test/` for debugging.
return null;
}
@@ -4085,8 +4203,150 @@ function _renderAgentEvent(msg, evt) {
}
return;
}
+
+ // CLI status:'usage' pulses update the LAST '● tokens · …' row in
+ // place rather than appending one row per pulse — long turns can
+ // emit hundreds of these and the rail would balloon otherwise. The
+ // ↓-deeper row is the canonical "running counter".
+ if (stream === 'cli'
+ && String(data?.type || '').toLowerCase() === 'status'
+ && String(data?.status || '').toLowerCase() === 'usage') {
+ const newLine = _formatEventLine(evt);
+ if (!newLine) return;
+ const body = msg.querySelector('[data-role="process"]');
+ if (body) {
+ // Find the last existing usage row by its '● tokens · ' prefix
+ // 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;
+ return;
+ }
+ }
+ }
+ _streamingAppendProgress(msg, newLine);
+ return;
+ }
+
const line = _formatEventLine(evt);
- if (line) _streamingAppendProgress(msg, line);
+ if (!line) return;
+ // All tool result rows — CLI-backed AND in-process — are
+ // click-to-expand. Two storage paths for the full body, decided per
+ // event shape:
+ // path present → spilled to disk (≥50 KB); click reads via
+ // localAgents.readToolResult IPC.
+ // output present → live event already carries the complete body
+ // (<50 KB); stash on the row's JS prop and the
+ // click handler renders directly without IO.
+ // Renderer-side memory cost is bounded by the in-process tool-result
+ // cap (50 KB worst-case per row, swept with the bubble on conv close).
+ //
+ // Two event shapes flow through here:
+ // stream='cli' + data.type='tool-event' phase='result' (CLI backends)
+ // → outputPath / output
+ // stream='tool' + data.phase='end' (in-process tools)
+ // → result_path / output
+ // Same UI affordance for both — the "symmetry is the entire point"
+ // call-out in cli-richer-output plan.
+ const cliResult = stream === 'cli'
+ && String(data?.type || '').toLowerCase() === 'tool-event'
+ && data?.phase === 'result';
+ const toolResult = stream === 'tool' && data?.phase === 'end';
+ if (cliResult || toolResult) {
+ const path = cliResult
+ ? (typeof data?.outputPath === 'string' && data.outputPath ? data.outputPath : '')
+ : (typeof data?.result_path === 'string' && data.result_path ? data.result_path : '');
+ const fullOutput = typeof data?.output === 'string' ? data.output : '';
+ // Only offer expand when there's actually more than what the
+ // preview already shows (avoids a click that reveals the same
+ // text). 160 mirrors _formatEventLine's `detailStr` cap on the
+ // CLI side; in-process side uses 300 (`resultPreview` default)
+ // but a single shared 160 threshold is fine — anything larger
+ // reads better expanded anyway.
+ const truncated = path || (fullOutput && fullOutput.replace(/\s+/g, ' ').trim().length > 160);
+ if (truncated) {
+ _streamingAppendToolResultRow(msg, line, path, fullOutput);
+ return;
+ }
+ }
+ _streamingAppendProgress(msg, line);
+}
+
+/** Append a tool-event result row that can expand its full output. Two
+ * storage paths for the full body, decided at append time:
+ * - `outputPath` (string) → runner spilled to disk; click reads via IPC.
+ * - `fullOutput` (string) → live event body (<50KB), stash on the
+ * row's JS prop; click renders directly.
+ * Exactly one of the two is required — caller (_renderAgentEvent) gates.
+ *
+ * Path is stored in a data attribute; the in-memory fullOutput hangs
+ * off `row._fullOutput` (raw JS prop, not dataset — dataset stringifies
+ * 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) {
+ const container = msg.querySelector('[data-role="process-container"]');
+ if (container) container.style.display = '';
+ const body = msg.querySelector('[data-role="process"]');
+ if (!body) return;
+ const innerWasAtBottom = _isNearBottom(body, 10);
+
+ const line = document.createElement('div');
+ const kind = _processKindOf(previewText);
+ line.className = 'stream-process-line is-expandable' + (kind ? ' kind-' + kind : '');
+ line.textContent = previewText;
+ if (outputPath) line.dataset.toolResultPath = outputPath;
+ if (fullOutput) line._fullOutput = fullOutput;
+ line.title = t('chat.tool_result_expand_hint');
+ body.appendChild(line);
+
+ // One delegated handler per bubble — cheaper than binding per row.
+ if (!body._toolResultClickBound) {
+ body._toolResultClickBound = true;
+ body.addEventListener('click', _onToolResultRowClick);
+ }
+
+ if (innerWasAtBottom) body.scrollTop = body.scrollHeight;
+ _stickBottomFromMsg(msg);
+}
+
+async function _onToolResultRowClick(ev) {
+ const row = ev.target.closest('.stream-process-line.is-expandable');
+ if (!row) return;
+ // Toggle existing expansion.
+ const next = row.nextElementSibling;
+ if (next && next.classList.contains('stream-process-line-full')) {
+ next.remove();
+ return;
+ }
+ const path = row.dataset.toolResultPath;
+ const inline = row._fullOutput;
+ const pre = document.createElement('pre');
+ pre.className = 'stream-process-line-full';
+
+ if (path) {
+ // window.orkas.invoke is the canonical IPC entry (matches every
+ // other feature's pattern — saved-apps / chat-artifact / workspace).
+ const inv = window.orkas && window.orkas.invoke;
+ if (typeof inv !== 'function') return;
+ let res;
+ try {
+ res = await inv('localAgents.readToolResult', { path });
+ } catch (err) {
+ res = { ok: false, error: String(err?.message || err) };
+ }
+ if (res && res.ok) {
+ pre.textContent = res.content + (res.truncated ? '\n\n[…truncated for display, open file for full content]' : '');
+ } else {
+ pre.textContent = '[failed to read: ' + (res?.error || 'unknown') + ']';
+ }
+ } else if (typeof inline === 'string' && inline) {
+ pre.textContent = inline;
+ } else {
+ pre.textContent = '[no content recorded for this row]';
+ }
+ row.insertAdjacentElement('afterend', pre);
}
// Update or create a single "live" line in the process pane.
diff --git a/src/renderer/modules/dialogs.js b/src/renderer/modules/dialogs.js
index 394f7e86..c408daf4 100644
--- a/src/renderer/modules/dialogs.js
+++ b/src/renderer/modules/dialogs.js
@@ -13,13 +13,13 @@ function _dialogLabel(key, zhFallback) {
try { const v = t(key); return v === key ? zhFallback : v; } catch (_) { return zhFallback; }
}
-function _uiShowDialog({ message, showCancel }) {
+function _uiShowDialog({ message, showCancel, okLabel, cancelLabel }) {
return new Promise((resolve) => {
const overlay = document.createElement('div');
overlay.className = 'modal-overlay ui-dialog-overlay open';
const msgHtml = escapeHtml(String(message || '')).replace(/\n/g, '<br />');
- const cancelText = escapeHtml(_dialogLabel('common.cancel', 'Cancel'));
- const okText = escapeHtml(_dialogLabel('common.confirm', 'Confirm'));
+ const cancelText = escapeHtml(cancelLabel || _dialogLabel('common.cancel', 'Cancel'));
+ const okText = escapeHtml(okLabel || _dialogLabel('common.confirm', 'Confirm'));
overlay.innerHTML = `
<div class="modal ui-dialog" role="dialog" aria-modal="true">
<div class="ui-dialog-message">${msgHtml}</div>
@@ -55,8 +55,21 @@ function _uiShowDialog({ message, showCancel }) {
});
}
-function uiConfirm(message) {
- return _uiShowDialog({ message, showCancel: true });
+// Backwards-compatible: `uiConfirm("message")` keeps the original
+// "Confirm" / "Cancel" pair. Pass `{message, okLabel?, cancelLabel?}` when
+// the action wants a more specific verb (e.g. "Open Folder" for the
+// preview-fallback dialog) — avoids forking a near-duplicate confirm
+// helper per CLAUDE.md §"Reuse UI components".
+function uiConfirm(arg) {
+ if (arg && typeof arg === 'object') {
+ return _uiShowDialog({
+ message: arg.message,
+ showCancel: true,
+ okLabel: arg.okLabel,
+ cancelLabel: arg.cancelLabel,
+ });
+ }
+ return _uiShowDialog({ message: arg, showCancel: true });
}
function uiAlert(message) {
@@ -115,6 +128,60 @@ function uiConfirmDanger({ title, message, dangerLabel, cancelLabel } = {}) {
});
}
+// Multi-button choice dialog. The user picks one of `choices[]` (each
+// gets its own button); the resolved value is the chosen `id`, or `null`
+// on cancel / Esc / outside-click. Used when an action has two valid
+// follow-up paths (e.g. close-sync with / without cloud purge) — a plain
+// uiConfirm would force the user to imagine the alternative.
+//
+// `choices: [{ id, label, style? }]` — `style` may be 'primary' (default),
+// 'danger', or '' for the neutral .btn look.
+function uiChoice({ title, message, choices = [], cancelLabel } = {}) {
+ return new Promise((resolve) => {
+ const overlay = document.createElement('div');
+ overlay.className = 'modal-overlay ui-dialog-overlay open';
+ const titleHtml = title ? `<div class="ui-dialog-title">${escapeHtml(String(title))}</div>` : '';
+ const msgHtml = escapeHtml(String(message || '')).replace(/\n/g, '<br />');
+ const cancelText = escapeHtml(cancelLabel || _dialogLabel('common.cancel', 'Cancel'));
+ const choiceHtml = choices.map((c) => {
+ const cls = c.style === 'danger' ? 'btn btn-danger'
+ : c.style === '' ? 'btn'
+ : 'btn btn-primary';
+ return `<button class="${cls}" data-act="choice" data-id="${escapeHtml(String(c.id))}">${escapeHtml(String(c.label || c.id))}</button>`;
+ }).join('');
+ overlay.innerHTML = `
+ <div class="modal ui-dialog" role="dialog" aria-modal="true">
+ ${titleHtml}
+ <div class="ui-dialog-message">${msgHtml}</div>
+ <div class="modal-actions">
+ <button class="btn" data-act="cancel">${cancelText}</button>
+ ${choiceHtml}
+ </div>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+
+ const onKey = (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Escape') finish(null);
+ // No Enter-to-confirm — caller must pick a choice explicitly.
+ };
+ const finish = (val) => {
+ document.removeEventListener('keydown', onKey, true);
+ overlay.remove();
+ resolve(val);
+ };
+ overlay.querySelectorAll('[data-act="choice"]').forEach((btn) => {
+ btn.addEventListener('click', () => finish(btn.dataset.id || null));
+ });
+ overlay.querySelector('[data-act="cancel"]').addEventListener('click', () => finish(null));
+ overlay.addEventListener('click', (e) => {
+ if (e.target === overlay) finish(null);
+ });
+ document.addEventListener('keydown', onKey, true);
+ });
+}
+
// Text-input prompt with cancel / confirm buttons. Returns the entered string, or
// null on cancel. Mirrors native `prompt()` semantics.
function uiPrompt(message, defaultValue = '') {
diff --git a/src/renderer/modules/i18n.js b/src/renderer/modules/i18n.js
index c8c878d7..f432831d 100644
--- a/src/renderer/modules/i18n.js
+++ b/src/renderer/modules/i18n.js
@@ -11,9 +11,13 @@
// [data-i18n-title] under root (or
// document)
//
-// Tables ship under `src/renderer/locales/{zh,en}.json`. We fetch them
-// through the IPC bridge (`window.orkas.getLocales`) — avoids fiddling
-// with sandbox + file:// fetch rules.
+// Tables ship under `src/renderer/locales/{zh,en}.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` /
+// `getLanguage` IPC pair remains as a fallback inside `initI18n()` for the
+// rare case where preload didn't expose the bundle (handler missing during
+// hot reload, contextBridge crash, ...).
//
// Modules that render content dynamically (list rows, dialog messages
// created on the fly) should register a `window.addEventListener(
@@ -26,6 +30,29 @@ let _currentLang = 'en';
let _tables = { zh: {}, en: {} };
let _ready = false;
+// 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
+// data-i18n elements have been parsed), the table + the user's lang are
+// already in hand. Apply translations now and the DOM never paints in the
+// wrong language. If the bundle is missing (preload error / handler not
+// registered), fall through to the async initI18n() flow below.
+(function _bootSyncI18n() {
+ 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 || {} };
+ _ready = true;
+ applyDomI18n();
+ document.documentElement.setAttribute('lang', _currentLang);
+ } catch (err) {
+ _i18nLog.warn('sync i18n boot failed; falling back to async', {
+ error: (err && err.message) || String(err),
+ });
+ }
+})();
+
function _lookup(key, lang) {
const tbl = _tables[lang];
return tbl && Object.prototype.hasOwnProperty.call(tbl, key) ? tbl[key] : undefined;
@@ -60,6 +87,7 @@ async function initI18n() {
}
_ready = true;
applyDomI18n();
+ document.documentElement.setAttribute('lang', _currentLang);
return _currentLang;
}
@@ -78,6 +106,7 @@ async function setLang(lang) {
_currentLang = lang;
}
applyDomI18n();
+ document.documentElement.setAttribute('lang', _currentLang);
window.dispatchEvent(new CustomEvent('i18n-change', { detail: { lang: _currentLang } }));
return _currentLang;
}
diff --git a/src/renderer/modules/local-agents.js b/src/renderer/modules/local-agents.js
index bc7697ba..725c301e 100644
--- a/src/renderer/modules/local-agents.js
+++ b/src/renderer/modules/local-agents.js
@@ -107,7 +107,7 @@ async function mountExternalCliSelect(onChange) {
if (!mount) return null;
const entries = await loadLocalCliEntries();
const available = entries.filter(e => e.available);
- const noneLabel = t('agent_modal.ext_cli_none') || '(none)';
+ const noneLabel = t('agent_modal.ext_cli_none');
const options = [
{ value: EXT_CLI_NONE, label: noneLabel },
...available.map(e => ({
diff --git a/src/renderer/modules/marketplace.js b/src/renderer/modules/marketplace.js
index ec5de1e5..ce7130c6 100644
--- a/src/renderer/modules/marketplace.js
+++ b/src/renderer/modules/marketplace.js
@@ -11,8 +11,8 @@
// cache stale / missing and writes back. Install reads from cache too.
// - openMarketplace() runs sweepCache() once on entry — 100 MB / 7d eviction.
//
-// Per-card 安装 button (in detail) materializes the cached item into the local
-// `data/builtin/{agents,skills}/` tree with a `_marketplace.json` sentinel.
+// Per-card Install button (in detail) materializes the cached item into the local
+// platform-install tree (<uid>/local/marketplace/{agents,skills}/<id>/).
//
// Dev-only upload (`openMarketplaceUpload`) is exposed for agents.js / skills.js (⋯ menu +
// detail-page actions). Category is NO LONGER asked — it lives in the spec now (agent.json
@@ -43,9 +43,10 @@ let _mpCategoriesCache = (() => {
})();
// Installed-state cache (synchronous via localStorage). Without this, every panel open
-// waits 1-2s for `agents.list` / `skills.list` IPCs before card buttons can show "已安装";
-// users see all cards flash "Install" first. The cache is updated after each successful
-// install/uninstall + after every successful background `agents.list` / `skills.list` refresh.
+// waits 1-2s for `agents.list` / `skills.list` IPCs before card buttons can show the
+// installed state; users see all cards flash "Install" first. The cache is updated after
+// each successful install/uninstall + after every successful background
+// `agents.list` / `skills.list` refresh.
const MP_INSTALLED_LS_KEY = 'orkas:mp:installed';
function _mpLoadInstalledFromLs() {
try {
@@ -79,14 +80,14 @@ let _mpReconcileStatus = { state: 'idle', total: 0, pulled: 0 };
// request on infinite-scroll, and `exhausted` flips true once a /list response is shorter
// than `MP_LISTINGS_PAGE_SIZE` or covers `total`.
//
-// SWR semantics (matches user expectation "切 tab/category 仍发请求,只是优先用缓存"):
+// SWR semantics ("switching tab/category still fires a request, but the cache renders first"):
// - Switching tab / category / opening panel:
// * Hydrate cache immediately so the grid renders prior items (no blank flash).
// * Always re-fetch page 1 in the background to overwrite stale rows.
// - Infinite scroll: when the sentinel near the grid bottom enters the viewport, fetch
// page = cached.nextPage and APPEND (dedupe by id) — never overwrite earlier pages.
// - "All" tab (category = '') feeds rows into per-category cache slots so a subsequent
-// "教育" tab open paints fast. The reverse (cat slot → "All") is NOT done — All needs
+// category tab open paints fast. The reverse (cat slot → "All") is NOT done — All needs
// a fresh time-ordered slice from the server.
const MP_LISTINGS_PAGE_SIZE = 50;
const _mpListingsCache = new Map();
@@ -119,16 +120,13 @@ function isMarketplaceOpen() {
return document.getElementById('panel-marketplace')?.classList.contains('active') === true;
}
-async function openMarketplace(initialTab = 'agent') {
+function openMarketplace(initialTab = 'agent') {
const panel = document.getElementById('panel-marketplace');
if (!panel) return;
// Kick off the reconcile watcher on first marketplace open (rather than at script load) so
// we don't fire IPC during early renderer init. Idempotent on later calls.
_mpInitReconcileWatch();
- // Hydrate persisted listings cache before first render — populates the in-memory Map so
- // `_mpHydrateFromCache` below finds entries even on a cold app start.
- await _mpHydrateListingsCache();
_mpReturnView = (typeof currentView === 'string' && currentView !== 'marketplace')
? currentView : 'agents';
@@ -152,6 +150,7 @@ async function openMarketplace(initialTab = 'agent') {
return { installedAgentIds: cached.agentIds, installedSkillIds: cached.skillIds };
})(),
loading: true,
+ searchBusy: false,
installing: new Set(),
error: '',
// Detail-view scratchpad
@@ -172,15 +171,21 @@ async function openMarketplace(initialTab = 'agent') {
_mpBound = true;
}
+ // Reset the search box so it matches the freshly-reset `q` above (clean slate on reopen).
+ const searchEl = panel.querySelector('[data-mp-search]');
+ if (searchEl) searchEl.value = '';
+
+ // Show the panel + a loading affordance synchronously — before ANY async work — so a slow
+ // cache-read IPC or a slow server fetch never leaves the user on the prior view with no
+ // feedback. `_mpLoadAll` then hydrates the listings cache, paints cached rows when present,
+ // and overlays fresh data — all via its own `_mpRender` calls.
if (typeof setView === 'function') setView('marketplace');
_mpShowGridView();
_mpRender();
- // Best-effort sweep — never block UI on a failure.
+ // Best-effort cache sweep — never blocks the UI.
window.orkas.invoke('marketplace.sweepCache').catch(() => { /* ignore */ });
- // Fire-and-forget: `_mpLoadAll` paints cache + fresh data internally via its own
- // `_mpRender` calls. Awaiting here would only delay returning control to the user.
_mpLoadAll();
}
@@ -251,7 +256,7 @@ async function _mpInitReconcileWatch() {
try { if (typeof loadAgents === 'function') loadAgents(true); } catch { /* ignore */ }
try { if (typeof loadSkills === 'function') loadSkills(true); } catch { /* ignore */ }
// If marketplace panel is open right now, also re-run the install-state hydration
- // so card buttons flip from "安装" to "已安装" without a tab switch.
+ // so card buttons flip from Install to Installed without a tab switch.
if (isMarketplaceOpen()) _mpLoadAll();
}
});
@@ -305,24 +310,24 @@ function _mpBindPanel(panel) {
);
panel.querySelectorAll('[data-mp-tab]').forEach((btn) => {
btn.addEventListener('click', () => {
- if (!_mpState) return;
+ if (!_mpState || _mpState.tab === btn.dataset.mpTab) return;
_mpState.tab = btn.dataset.mpTab;
_mpState.category = '';
- _mpRender();
+ // Re-hydrate from cache for the new (kind, '', q) and re-fetch — same cache-first path
+ // as category clicks, so the grid doesn't show the previous tab's rows under "All".
+ _mpRefreshListings();
});
});
const search = panel.querySelector('[data-mp-search]');
if (search) {
search.addEventListener('keydown', (e) => {
if (e.isComposing || e.keyCode === 229) return;
- if (e.key === 'Enter') {
- const next = search.value.trim();
- if (next === _mpState.q) return;
- _mpState.q = next;
- _mpRefreshListings();
- }
+ if (e.key === 'Enter') _mpRunSearch();
});
+ search.addEventListener('input', _mpRenderSearchClear);
}
+ panel.querySelector('[data-mp-search-btn]')?.addEventListener('click', _mpRunSearch);
+ panel.querySelector('[data-mp-search-clear]')?.addEventListener('click', _mpClearSearch);
panel.querySelector('[data-mp-detail-install]')?.addEventListener('click', _mpInstallFromDetail);
// Dev-only delete button click handler is bound by marketplace_dev.js (file absent in
// OrkasOpen). HTML element ships in index.html with display:none — dev module flips it
@@ -330,16 +335,16 @@ function _mpBindPanel(panel) {
}
async function _mpLoadAll() {
- // SWR open: paint cache immediately so the grid never goes blank between IPC roundtrips.
- // Even when the TTL has elapsed (dev mode TTL=0 always fires a refresh), the user sees the
- // stale list right away — fresh data swaps in once the background fetch lands.
- const hadCache = _mpHydrateFromCache();
- _mpState.loading = !hadCache;
- _mpState.error = '';
+ // Pull the persisted listings cache into the in-memory Map first (idempotent — no-op after
+ // the first open this session) so the cache-first paint below has prior-run rows to show.
+ await _mpHydrateListingsCache();
+ // Cache-first (SWR): paint cached rows for the current (kind, category, q) immediately; if
+ // the visible tab has no rows, show the body spinner until the listings fetch lands. Either
+ // way we always re-fetch in the background and swap fresh data in.
+ _mpHydrateFromCache();
if (_mpCategoriesCache) _mpState.categories = _mpCategoriesCache;
- // First paint with whatever we already know — categories from the renderer cache (set on
- // a prior session if it ran), listings from the hydrated cache. Avoids the "wait for the
- // IPC roundtrip before showing anything" flash that broke the cache-first promise.
+ _mpState.loading = _mpVisibleItems().length === 0;
+ _mpState.error = '';
_mpRender();
try {
@@ -363,13 +368,10 @@ async function _mpLoadAll() {
_mpPersistInstalled();
await _mpLoadListings();
} catch (err) {
- // Background-refresh failure must NOT wipe what's already on screen. Only surface as a
- // body-level error when we never managed to paint any cached items in the first place;
- // otherwise log + keep the stale view (matches SWR semantics).
+ // A failed refresh must NOT wipe what's already on screen — surface as a body-level error
+ // only when the visible tab has nothing to show; otherwise log + keep the stale view.
console.warn('marketplace background fetch failed:', err);
- if (!hadCache && _mpState.agents.length === 0 && _mpState.skills.length === 0) {
- _mpState.error = (err && err.message) || String(err);
- }
+ if (_mpVisibleItems().length === 0) _mpState.error = (err && err.message) || String(err);
} finally {
_mpState.loading = false;
_mpRender();
@@ -400,27 +402,81 @@ setTimeout(() => { _mpInitReconcileWatch().catch(() => {}); }, 0);
} catch { /* preload happens at script load; window.orkas not ready is OK */ }
})();
-// Top-level listings refresh: hydrate cache → render immediately if hit, then background
-// fetch + re-render. The single entry point for category-chip clicks and the search Enter
-// handler so the loading-state / cache-hit decision lives in one place.
-async function _mpRefreshListings() {
- const hadCache = _mpHydrateFromCache();
- _mpState.loading = !hadCache;
- _mpRender();
- await _mpLoadListings();
- _mpState.loading = false;
+// Single entry point for category-chip clicks and search submits: hydrate the cached rows for
+// the new (kind, category, q) and paint them; if the visible tab has no rows, show the body
+// spinner instead. Either way, re-fetch page 1 in the background and swap fresh data in.
+// `opts.searchBusy` additionally spins the search button while the fetch is in flight.
+async function _mpRefreshListings(opts = {}) {
+ if (!_mpState) return;
+ _mpHydrateFromCache();
+ _mpState.loading = _mpVisibleItems().length === 0;
+ _mpState.error = '';
+ if (opts.searchBusy) _mpState.searchBusy = true;
_mpRender();
+ try {
+ await _mpLoadListings();
+ } finally {
+ _mpState.loading = false;
+ if (opts.searchBusy) _mpState.searchBusy = false;
+ _mpRender();
+ }
+}
+
+// ─── Search box (input + Enter / search button + clear ×) ───
+// Triggered by Enter in the input OR a click on the search button — reads the live input
+// value, refreshes the listings for that query, and spins the search button while it loads.
+function _mpRunSearch() {
+ if (!_mpState) return;
+ const input = document.getElementById('panel-marketplace')?.querySelector('[data-mp-search]');
+ _mpState.q = (input?.value || '').trim();
+ _mpRefreshListings({ searchBusy: true });
+}
+
+// Clear (×) button inside the input: empties the box and, if a search was active, refreshes
+// back to the unfiltered list.
+function _mpClearSearch() {
+ if (!_mpState) return;
+ const input = document.getElementById('panel-marketplace')?.querySelector('[data-mp-search]');
+ if (input) { input.value = ''; input.focus(); }
+ _mpRenderSearchClear();
+ if (_mpState.q) {
+ _mpState.q = '';
+ _mpRefreshListings({ searchBusy: true });
+ }
}
-// Generation token: every call to a load fn bumps `_loadGen`; only responses from the
-// latest gen get applied. Prevents stale responses (tab / category / search switched
-// mid-flight) from overwriting current state.
+// Reflect `_mpState.searchBusy` on the search button — spinner + greyed/disabled while a
+// search fetch is in flight, plain accent button otherwise (mirrors the install-button pattern).
+function _mpRenderSearchBtn() {
+ const btn = document.getElementById('panel-marketplace')?.querySelector('[data-mp-search-btn]');
+ if (!btn) return;
+ const busy = !!(_mpState && _mpState.searchBusy);
+ btn.className = busy ? 'btn btn-sm is-disabled marketplace-search-btn' : 'btn btn-sm btn-primary marketplace-search-btn';
+ btn.disabled = busy;
+ const label = escapeHtml(t('marketplace.search'));
+ btn.innerHTML = busy ? `<span class="marketplace-btn-spinner"></span>${label}` : label;
+}
+
+// Show the clear (×) button only when the input has text.
+function _mpRenderSearchClear() {
+ const panel = document.getElementById('panel-marketplace');
+ const input = panel?.querySelector('[data-mp-search]');
+ const clearBtn = panel?.querySelector('[data-mp-search-clear]');
+ if (!clearBtn) return;
+ clearBtn.hidden = !(input && input.value.length > 0);
+}
+
+// Re-point _mpState.agents/skills at the cached rows for the current (kind, category, q).
+// (Stale-response protection lives in `_mpLoadListingsPage`'s per-kind generation token.)
function _mpHydrateFromCache() {
const cat = _mpState.category, q = _mpState.q;
const cachedA = _mpListingsCache.get(_mpListingsKey('agent', cat, q));
const cachedS = _mpListingsCache.get(_mpListingsKey('skill', cat, q));
- if (cachedA) _mpState.agents = cachedA.items;
- if (cachedS) _mpState.skills = cachedS.items;
+ // No cache for this (kind, cat, q) → clear that list rather than leave the previous
+ // tab/category's rows on screen; the caller's `loading` flag (set from
+ // `_mpVisibleItems().length`) then decides spinner vs empty-state for the now-empty tab.
+ _mpState.agents = cachedA ? cachedA.items : [];
+ _mpState.skills = cachedS ? cachedS.items : [];
return !!(cachedA || cachedS);
}
@@ -523,6 +579,12 @@ async function _mpLoadMoreCurrentKind() {
}
}
+// The list the user is currently looking at — the basis for "is the page empty → show
+// loading", and for rendering / finding cards on the active tab.
+function _mpVisibleItems() {
+ return _mpState.tab === 'agent' ? _mpState.agents : _mpState.skills;
+}
+
// ─── Grid view rendering ───
function _mpRender() {
const panel = document.getElementById('panel-marketplace');
@@ -536,6 +598,8 @@ function _mpRender() {
}
const searchEl = panel.querySelector('[data-mp-search]');
if (searchEl) searchEl.setAttribute('placeholder', t('marketplace.search_ph'));
+ _mpRenderSearchBtn();
+ _mpRenderSearchClear();
const cats = _mpState.categories;
const chips = [
@@ -571,7 +635,7 @@ function _mpRender() {
}
// Order = server-side `updated_at DESC` (newest first). No further client sort — the
// accumulator in `_mpLoadListingsPage` preserves the server's slicing.
- const items = (_mpState.tab === 'agent' ? _mpState.agents : _mpState.skills);
+ const items = _mpVisibleItems();
if (items.length === 0) {
body.innerHTML = `<div class="empty">${escapeHtml(t('marketplace.empty'))}</div>`;
return;
@@ -589,7 +653,7 @@ function _mpRender() {
e.stopPropagation();
_mpInstall(_mpState.tab, id);
} else {
- const item = (_mpState.tab === 'agent' ? _mpState.agents : _mpState.skills).find((x) => x.id === id);
+ const item = _mpVisibleItems().find((x) => x.id === id);
if (item) _mpOpenDetail(_mpState.tab, item);
}
});
@@ -653,7 +717,8 @@ function _mpCardHtml(item, lang) {
}
/** Author badge — distinguishes same-name uploads by different authors. uid=0 is the
- * "Platform" marker (官方制作); everything else falls back to a truncated uid. */
+ * Platform marker (i18n key `marketplace.author_platform`); everything else falls back
+ * to a truncated uid. */
function _mpAuthorBadgeHtml(createUid) {
if (!createUid) return '';
const label = String(createUid) === '0'
@@ -753,8 +818,8 @@ function _mpRenderDetail() {
const installBtn = panel.querySelector('[data-mp-detail-install]');
installBtn.dataset.id = item.id;
installBtn.dataset.kind = kind;
- // When installed, repurpose the primary button as "卸载" (local-only uninstall — does NOT
- // touch the server row). When installing/uninstalling, disabled with progress text + inline
+ // When installed, repurpose the primary button as Uninstall (local-only — does NOT touch
+ // the server row). When installing/uninstalling, disabled with progress text + inline
// spinner so the user sees "still working" instead of a static label.
const spinnerHtml = '<span class="marketplace-btn-spinner"></span>';
if (installing) {
@@ -847,15 +912,15 @@ function _mpAgentDetailHtml(agentJson) {
const lang = getLang();
const desc = pickDesc(agentJson, lang).trim();
const workflow = String(agentJson.workflow || '').trim();
- const placeholderHtml = `<span class="agents-detail-placeholder">${escapeHtml(t('agents.placeholder_unset') || '—')}</span>`;
+ const placeholderHtml = `<span class="agents-detail-placeholder">${escapeHtml(t('agents.placeholder_unset'))}</span>`;
return `<div class="agents-detail-body marketplace-detail-body-inner">
<div class="agents-detail-section">
- <div class="agents-detail-label">${escapeHtml(t('agents.label_desc') || 'Summary')}</div>
+ <div class="agents-detail-label">${escapeHtml(t('agents.label_desc'))}</div>
<div class="agents-detail-desc">${desc ? escapeHtml(desc) : placeholderHtml}</div>
</div>
<div class="agents-detail-section agents-detail-section-workflow">
- <div class="agents-detail-label">${escapeHtml(t('agents.label_workflow') || 'Workflow')}</div>
+ <div class="agents-detail-label">${escapeHtml(t('agents.label_workflow'))}</div>
<div class="agents-detail-workflow markdown-body">${workflow ? renderMarkdownFull(workflow) : placeholderHtml}</div>
</div>
</div>`;
@@ -885,20 +950,20 @@ function _mpSkillDetailHtml() {
const bodyHtml = isMd
? renderMarkdownFull(text)
: `<pre class="code-view"><code>${escapeHtml(text)}</code></pre>`;
- const placeholderHtml = `<span class="agents-detail-placeholder">${escapeHtml(t('agents.placeholder_unset') || '—')}</span>`;
+ const placeholderHtml = `<span class="agents-detail-placeholder">${escapeHtml(t('agents.placeholder_unset'))}</span>`;
return `
<div class="skills-detail-content marketplace-detail-body-inner">
<section class="skills-doc-section">
- <h3 class="skills-doc-section-label">${escapeHtml(t('skills.label_summary') || 'Summary')}</h3>
+ <h3 class="skills-doc-section-label">${escapeHtml(t('skills.label_summary'))}</h3>
<div class="skills-doc-section-body">${summary ? escapeHtml(summary) : placeholderHtml}</div>
</section>
<section class="skills-doc-section skills-usage-section">
<h3 class="skills-doc-section-label skills-usage-label">
- <span>${escapeHtml(t('skills.label_usage') || 'Usage')}</span>
+ <span>${escapeHtml(t('skills.label_usage'))}</span>
<button type="button" class="skills-source-toggle" data-mp-source-toggle aria-expanded="false">
<span class="skills-source-toggle-caret" aria-hidden="true">▶</span>
- <span>${escapeHtml(t('skills.label_source') || 'View source')}</span>
+ <span>${escapeHtml(t('skills.label_source'))}</span>
</button>
</h3>
<div class="skills-source-panel" data-mp-source-panel style="display:none">
@@ -935,7 +1000,7 @@ async function _mpInstall(kind, id) {
_mpPersistInstalled();
if (typeof loadAgents === 'function' && kind === 'agent') await loadAgents(true);
if (typeof loadSkills === 'function' && kind === 'skill') await loadSkills(true);
- // Success: no toast — the button flips to "已安装" + state set above is the signal.
+ // Success: no toast — the button flips to "Installed" + state set above is the signal.
// (Failure still alerts because the user otherwise has no way to know why nothing happened.)
} catch (err) {
const msg = (err && err.message) || String(err);
@@ -972,7 +1037,7 @@ async function _mpUninstall(kind, id) {
_mpPersistInstalled();
if (typeof loadAgents === 'function' && kind === 'agent') await loadAgents(true);
if (typeof loadSkills === 'function' && kind === 'skill') await loadSkills(true);
- // Success: button flips back to "安装" — no toast needed. (Failures still alert.)
+ // Success: button flips back to "Install" — no toast needed. (Failures still alert.)
} catch (err) {
const msg = (err && err.message) || String(err);
uiAlert(t('marketplace.uninstall_failed').replace('{reason}', msg));
diff --git a/src/renderer/modules/model-guard.js b/src/renderer/modules/model-guard.js
index c5be3a0b..73dea640 100644
--- a/src/renderer/modules/model-guard.js
+++ b/src/renderer/modules/model-guard.js
@@ -31,6 +31,9 @@ function _ensureGuardBanner() {
`;
el.querySelector('.model-guard-cta').addEventListener('click', () => {
if (typeof setView === 'function') setView('settings');
+ // Drop the user straight on the 配置 (Credentials) tab — that's where
+ // the model-auth UI lives now (Phase 4 4-tab restructure).
+ if (typeof window.activateSettingsTab === 'function') window.activateSettingsTab('credentials');
});
// Keep this one in sync when user toggles language.
window.addEventListener('i18n-change', () => {
@@ -95,6 +98,7 @@ function ensureModelConfigured(opts = {}) {
else window.alert(msg);
} catch (_) { /* swallow — alert is best-effort */ }
if (typeof setView === 'function') setView('settings');
+ if (typeof window.activateSettingsTab === 'function') window.activateSettingsTab('credentials');
}
return false;
}
diff --git a/src/renderer/modules/plan-rail.js b/src/renderer/modules/plan-rail.js
index 40dbad06..cdbbac24 100644
--- a/src/renderer/modules/plan-rail.js
+++ b/src/renderer/modules/plan-rail.js
@@ -67,9 +67,9 @@ function _buildStepHtml(step) {
: '';
const actions = _isStepActionable(step, _currentInFlight)
? `<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') || 'Retry')}</button>
+ <button type="button" class="btn btn-sm" data-action="retry" data-i18n="plan.action.retry">${escapeHtml(t('plan.action.retry'))}</button>
<button type="button" class="btn btn-sm" data-action="skip" data-i18n="plan.action.skip">${escapeHtml(t('plan.action.skip') || 'Skip')}</button>
- <button type="button" class="btn btn-sm btn-danger" data-action="abort" data-i18n="plan.action.abort">${escapeHtml(t('plan.action.abort') || 'Abandon plan')}</button>
+ <button type="button" class="btn btn-sm btn-danger" data-action="abort" data-i18n="plan.action.abort">${escapeHtml(t('plan.action.abort'))}</button>
</div>`
: '';
return `<div class="plan-rail-step is-${step.status}" data-step-index="${step.index}" ${step.output_msg_id ? `data-msg-id="${escapeHtml(step.output_msg_id)}"` : ''}>
@@ -238,7 +238,7 @@ document.addEventListener('click', async (ev) => {
return;
}
if (action === 'skip') {
- const ok = await uiConfirm(t('plan.confirm.skip') || 'Skip this step?');
+ const ok = await uiConfirm(t('plan.confirm.skip'));
if (!ok) return;
try {
const res = await apiFetch(
@@ -255,7 +255,7 @@ document.addEventListener('click', async (ev) => {
return;
}
if (action === 'abort') {
- const ok = await uiConfirm(t('plan.confirm.abort') || 'Abandon the entire plan?');
+ const ok = await uiConfirm(t('plan.confirm.abort'));
if (!ok) return;
try {
await apiFetch(
diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.js
index f43d0b5f..12f5b071 100644
--- a/src/renderer/modules/settings.js
+++ b/src/renderer/modules/settings.js
@@ -22,6 +22,9 @@ let _settingsState = {
};
async function loadSettings() {
+ // 4-tab structure (batch 6). Initialize switching + activate default tab
+ // (通用 by default — matches the is-active class on the markup).
+ if (typeof initSettingsTabs === 'function') initSettingsTabs();
_settingsBindLanguageOnce();
_settingsSyncLanguageRadio();
_settingsBindClearAllConvsOnce();
diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.js
index fa80448e..23741d07 100644
--- a/src/renderer/modules/skills.js
+++ b/src/renderer/modules/skills.js
@@ -319,9 +319,13 @@ function _openSkillRowMenu(anchorBtn, id, source) {
const cached = _skillsCache?.find((s) => s.id === id && s.source === source);
const enabled = cached ? cached.enabled !== false : true;
const canEdit = source === 'custom';
+ const canEdit = source === 'custom' || (source === 'builtin' && false);
+ // Dev-only entry on builtin: tag the label so the user knows this isn't a
+ // normal user capability (mirrors marketplace.upload's "(dev)" treatment).
+ const editLabelSuffix = (source === 'builtin' && false) ? t('common.dev_suffix') : '';
const items = [];
if (canEdit) {
- items.push(`<div class="skill-row-menu-item" data-action="edit">${escapeHtml(t('skills.edit'))}</div>`);
+ items.push(`<div class="skill-row-menu-item" data-action="edit">${escapeHtml(t('skills.edit') + editLabelSuffix)}</div>`);
}
items.push(
`<div class="skill-row-menu-item" data-action="toggle-enabled">${escapeHtml(enabled ? t('component.disable') : t('component.enable'))}</div>`,
@@ -1020,7 +1024,14 @@ let _skillEditSkillId = null;
function _updateEditButtonLabel() {
const btn = document.getElementById('skill-edit-btn');
if (!btn) return;
- btn.textContent = _skillEditMode ? t('skills.edit_btn_done') : t('skills.edit_btn_edit');
+ if (_skillEditMode) {
+ btn.textContent = t('skills.edit_btn_done');
+ return;
+ }
+ // Tag the "Edit" label on builtin skills (dev-only entry); the "Done"
+ // branch above stays bare — in edit mode the marker is redundant.
+ const suffix = (_selectedSkill?.source === 'builtin' && false) ? t('common.dev_suffix') : '';
+ btn.textContent = t('skills.edit_btn_edit') + suffix;
}
// When called with {autoSeed: true} (e.g. right after skill creation),
@@ -1219,7 +1230,7 @@ async function openSkillModal(editId) {
if (el) el.value = '';
}
const sel = document.getElementById('skill-dir-selected');
- if (sel) sel.textContent = t('skill_modal.dir_none') || '(none selected)';
+ if (sel) sel.textContent = t('skill_modal.dir_none');
if (editId) {
title.textContent = t('skills.modal_edit_title');
diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.js
index 9cff558c..0881b4ae 100644
--- a/src/renderer/modules/state.js
+++ b/src/renderer/modules/state.js
@@ -226,7 +226,12 @@ function bindStaticHandlers() {
if (_selectedAgent?.source === 'custom') promoteCustomAgent(_selectedAgent.id);
});
document.getElementById('agent-upload-marketplace-btn')?.addEventListener('click', () => {
- if (_selectedAgent?.source === 'custom' && typeof openMarketplaceUpload === 'function') {
+ // Upload is allowed for both custom AND builtin (dev mode) — same
+ // marketplace publishing flow per CLAUDE.md §11. The row-menu handler
+ // (agents.js) already does this; the detail-page handler had a stale
+ // `source === 'custom'` guard that silently swallowed clicks on builtin
+ // detail pages.
+ if (_selectedAgent && typeof openMarketplaceUpload === 'function') {
openMarketplaceUpload('agent', _selectedAgent.id);
}
});
@@ -263,7 +268,9 @@ function bindStaticHandlers() {
if (_selectedSkill?.source === 'custom') promoteCustomSkill(_selectedSkill.id);
});
document.getElementById('skill-upload-marketplace-btn')?.addEventListener('click', () => {
- if (_selectedSkill?.source === 'custom' && typeof openMarketplaceUpload === 'function') {
+ // Upload is allowed for both custom AND builtin (dev mode) — same as
+ // the agent upload handler above; see comment there.
+ if (_selectedSkill && typeof openMarketplaceUpload === 'function') {
openMarketplaceUpload('skill', _selectedSkill.id);
}
});
diff --git a/src/renderer/modules/user-workspace.js b/src/renderer/modules/user-workspace.js
index 2fc50448..35f4096a 100644
--- a/src/renderer/modules/user-workspace.js
+++ b/src/renderer/modules/user-workspace.js
@@ -156,11 +156,11 @@ function _createWorkspaceChip(target) {
chip.type = 'button';
chip.className = 'workspace-chip';
chip.dataset.wsTarget = target;
- chip.title = (typeof t === 'function' ? t('workspace.chip_title') : 'Click to pick a workspace');
+ chip.title = (t('workspace.chip_title'));
// Text-prefix layout matches the recipient / project chip pattern
// ("给:" / "项目:" / "工作区:") — the folder icon was replaced per UX
// feedback so all three left-side chips read as "[label]: [value]".
- const prefix = (typeof t === 'function' ? t('workspace.chip_label') : 'Workspace: ');
+ const prefix = (t('workspace.chip_label'));
chip.innerHTML =
`<span class="workspace-chip-prefix">${escapeHtml(prefix)}</span>` +
'<span class="workspace-chip-label"></span>' +
diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.js
index 6df98dc5..736f76b8 100644
--- a/src/renderer/modules/utils.js
+++ b/src/renderer/modules/utils.js
@@ -476,7 +476,7 @@ function _aiSelectMount(el, config) {
const state = {
options: [], // [{value, label, hint?}]
value: '',
- placeholder: (typeof t === 'function' ? t('ai_select.placeholder') : '— Select —'),
+ placeholder: (t('ai_select.placeholder')),
onChange: () => {},
open: false,
activeIdx: -1,
diff --git a/src/renderer/style.css b/src/renderer/style.css
index fb56b4f3..a44887af 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -2512,8 +2512,138 @@ body.model-not-configured .main-content { flex-direction: column; }
}
.chat-lightbox-close:hover { background: #f1f5f9; }
+/* In-app file preview overlay (chat-file-viewer.js). Mounted once into
+ <body> on first openChatFileViewer(). Same backdrop chrome as the image
+ lightbox; differs in that the stage is a fixed sheet (header + body)
+ instead of a free-floating image. */
+.chat-file-viewer {
+ position: fixed;
+ inset: 0;
+ z-index: 1000;
+ display: none;
+ align-items: center;
+ justify-content: center;
+}
+.chat-file-viewer.is-open { display: flex; }
+.chat-file-viewer-backdrop {
+ position: absolute;
+ inset: 0;
+ background: rgba(15, 23, 42, 0.82);
+}
+.chat-file-viewer-stage {
+ position: relative;
+ width: 92vw;
+ height: 92vh;
+ max-width: 1280px;
+ background: #fff;
+ border-radius: 10px;
+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.4);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+.chat-file-viewer-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 14px;
+ border-bottom: 1px solid #e2e8f0;
+ background: #f8fafc;
+ flex-shrink: 0;
+}
+.chat-file-viewer-title {
+ font-size: 13px;
+ font-weight: 600;
+ color: #0f172a;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ flex: 1;
+ margin-right: 12px;
+}
+.chat-file-viewer-actions {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-shrink: 0;
+}
+.chat-file-viewer-reveal,
+.chat-file-viewer-close {
+ width: 28px;
+ height: 28px;
+ border-radius: 6px;
+ border: none;
+ background: transparent;
+ color: #475569;
+ font-size: 16px;
+ line-height: 1;
+ cursor: pointer;
+ transition: background 120ms ease;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+}
+.chat-file-viewer-reveal:hover,
+.chat-file-viewer-close:hover { background: #e2e8f0; color: #0f172a; }
+.chat-file-viewer-reveal svg { display: block; }
+.chat-file-viewer-close { font-size: 20px; }
+.chat-file-viewer-body {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ background: #fff;
+}
+/* iframe-based body (pdf / html) fills the body slot. The body itself
+ handles scroll for non-iframe bodies (md / text). */
+.chat-file-viewer-pdf,
+.chat-file-viewer-html {
+ width: 100%;
+ height: 100%;
+ border: none;
+ display: block;
+}
+.chat-file-viewer-md {
+ padding: 24px 32px;
+ color: #0f172a;
+ font-size: 14px;
+ line-height: 1.7;
+ max-width: 880px;
+ margin: 0 auto;
+}
+.chat-file-viewer-text {
+ padding: 20px 24px;
+ margin: 0;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
+ font-size: 12px;
+ line-height: 1.55;
+ color: #0f172a;
+ background: #f8fafc;
+ white-space: pre-wrap;
+ word-break: break-word;
+ min-height: 100%;
+ box-sizing: border-box;
+}
+.chat-file-viewer-loading {
+ padding: 40px;
+ text-align: center;
+ color: #64748b;
+ font-size: 13px;
+}
+
+/* Attachment chips that aren't images / videos are clickable too
+ (chat-file-viewer); surface the affordance with the same hover treatment
+ as image chips. */
+.chat-msg-attach.is-clickable {
+ cursor: pointer;
+ transition: background 120ms ease;
+}
+.chat-msg-attach.is-clickable:hover {
+ background: rgba(59, 130, 246, 0.08);
+}
+
/* Files produced by the assistant (write_file / markdown_to_pdf / html_to_pdf).
- Same visual language as attachments; click reveals in Finder/Explorer. */
+ Same visual language as attachments; click opens the in-app preview overlay
+ (or, on unsupported types, falls back to a dialog with "open folder"). */
.chat-msg-produced {
display: flex;
flex-wrap: wrap;
@@ -3403,6 +3533,28 @@ body.model-not-configured .main-content { flex-direction: column; }
.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 */
+
+/* Expandable tool-result row: cursor hint + subtle underline on hover.
+ Used for CLI tool-event(result) rows whose full output spilled to
+ disk; click reveals a `.stream-process-line-full` <pre> sibling. */
+.stream-process-line.is-expandable { cursor: pointer; }
+.stream-process-line.is-expandable:hover { text-decoration: underline; text-decoration-color: rgba(0,0,0,0.25); }
+.stream-process-line-full {
+ margin: 4px 0 8px 16px;
+ padding: 8px 12px;
+ background: rgba(0,0,0,0.04);
+ border-left: 2px solid rgba(0,0,0,0.15);
+ border-radius: 4px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 12px;
+ line-height: 1.5;
+ color: #475569;
+ white-space: pre-wrap;
+ word-break: break-all;
+ max-height: 320px;
+ overflow: auto;
+}
.stream-final {
/* Appears below process section with a subtle divider when process is open */
@@ -5367,6 +5519,165 @@ body.model-not-configured .main-content { flex-direction: column; }
border-bottom: 1px solid var(--border, #e5e7eb);
}
.settings-section-head:first-child { margin-top: 0; }
+
+/* 4-tab structure (batch 6 decision). Visual primitive mirrors .marketplace-tabs. */
+.settings-tabs {
+ display: flex;
+ gap: 4px;
+ margin: 0 4px 16px;
+ border-bottom: 1px solid var(--border, #e5e7eb);
+ padding-bottom: 8px;
+}
+.settings-tab {
+ background: transparent;
+ border: none;
+ padding: 6px 14px;
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--muted);
+ border-radius: 6px;
+ cursor: pointer;
+ position: relative;
+}
+.settings-tab.is-active { background: var(--accent-soft, #eef2ff); color: var(--text); }
+/* Tab title dot — set via .has-dot on the .settings-tab. The same primitive
+ is reused on the sidebar settings button (see Phase 5). */
+.settings-tab.has-dot::after,
+.has-dot::after {
+ content: '';
+ display: inline-block;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--accent, #f59e0b);
+ margin-left: 6px;
+ vertical-align: middle;
+}
+.has-dot.is-red::after,
+.settings-tab.has-dot.is-red::after { background: #ef4444; }
+.has-dot.is-orange::after,
+.settings-tab.has-dot.is-orange::after { background: #f59e0b; }
+.settings-tab-pane[hidden] { display: none; }
+
+/* Sync card (data tab). */
+ font-size: 12px;
+ padding: 2px 8px;
+ border-radius: 10px;
+ background: rgba(16, 185, 129, 0.12);
+ color: #047857;
+ margin-right: 8px;
+}
+ max-width: 320px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+ flex: 1;
+ height: 6px;
+ background: var(--border, #e5e7eb);
+ border-radius: 3px;
+ overflow: hidden;
+ max-width: 320px;
+}
+ height: 100%;
+ width: 0%;
+ background: var(--accent, #6366f1);
+ transition: width 200ms ease;
+}
+ color: #b91c1c;
+ font-size: 12px;
+ white-space: pre-wrap;
+}
+ margin-top: 12px;
+ padding: 12px 14px;
+ background: rgba(239, 68, 68, 0.08);
+ border: 1px solid rgba(239, 68, 68, 0.35);
+ border-radius: 8px;
+ font-size: 13px;
+}
+ font-weight: 600;
+ color: #b91c1c;
+ margin-bottom: 4px;
+}
+ color: var(--text);
+ margin-bottom: 8px;
+}
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+}
+ margin: 6px 0 12px;
+ padding-left: 18px;
+ max-height: 160px;
+ overflow-y: auto;
+ color: var(--text-muted, #6b7280);
+ font-size: 12px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+}
+ /* No horizontal padding — the breakdown rows must left-align with the
+ * quota bar text above (which also sits flush against the group's left
+ * edge). Vertical breathing room only. */
+ margin-top: 10px;
+ padding: 6px 0 4px;
+ font-size: 13px;
+}
+/* Single grid hoisted to the section so all rows share the same column
+ * tracks (otherwise per-row autos sized each row independently and the
+ * size column didn't right-align across rows). Two columns now: name
+ * (1fr, left-aligned) and size (auto, right-aligned). */
+ display: grid;
+ grid-template-columns: 1fr auto;
+ column-gap: 16px;
+ row-gap: 4px;
+ align-items: center;
+ margin: 8px 0 4px;
+ font-size: 12px;
+}
+ grid-column: 1 / -1;
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--text-muted, #6b7280);
+ margin: 4px 4px 4px;
+}
+/* `display: contents` makes each row's children promote to direct grid
+ * items of the section, so the three columns line up across every row. */
+ display: contents;
+}
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+ font-variant-numeric: tabular-nums;
+ color: var(--text);
+ justify-self: end;
+}
+ margin-top: 12px;
+ font-size: 13px;
+}
+ cursor: pointer;
+ color: var(--text);
+ font-weight: 500;
+ list-style: none;
+ padding: 6px 4px;
+}
+ padding: 6px 4px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12px;
+}
+ font-size: 11px;
+ margin-top: 14px;
+ padding: 8px 10px;
+ background: var(--bg-soft, #f9fafb);
+ border-radius: 6px;
+ line-height: 1.5;
+}
.settings-section-note {
font-size: 12px;
color: var(--text-muted, #6b7280);
@@ -5462,6 +5773,11 @@ body.model-not-configured .main-content { flex-direction: column; }
user-select: none;
}
.settings-row > label.settings-toggle input[type="checkbox"] { margin: 0; }
+/* `.settings-toggle-tight` — variant where the toggle does NOT take the full
+ * row width; its sibling hint (`.settings-status`) sits right next to it
+ * instead of being pushed to the far right. Used by the sync card so
+ * "启用云端同步" + the enabled/disabled hint read as one line. */
+.settings-row > label.settings-toggle.settings-toggle-tight { flex: 0 0 auto; }
/* Shared input style — used inside modals too. */
.form-input {
@@ -6136,15 +6452,42 @@ body.model-not-configured .main-content { flex-direction: column; }
cursor: pointer;
}
.marketplace-tab.is-active { background: var(--accent-soft, #eef2ff); color: var(--text); }
-.marketplace-search {
+.marketplace-search-wrap {
+ position: relative;
flex: 1;
max-width: 320px;
margin-left: auto;
- padding: 6px 10px;
+ display: flex;
+}
+.marketplace-search {
+ flex: 1;
+ padding: 6px 28px 6px 10px;
border: 1px solid rgba(0,0,0,0.1);
border-radius: 6px;
font-size: 13px;
}
+.marketplace-search-clear {
+ position: absolute;
+ right: 5px;
+ top: 50%;
+ transform: translateY(-50%);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 18px;
+ height: 18px;
+ padding: 0;
+ border: none;
+ border-radius: 50%;
+ background: transparent;
+ color: var(--muted);
+ font-size: 15px;
+ line-height: 1;
+ cursor: pointer;
+}
+.marketplace-search-clear:hover { background: rgba(0,0,0,0.08); color: var(--text); }
+.marketplace-search-clear[hidden] { display: none; }
+.marketplace-search-btn { flex-shrink: 0; }
.marketplace-categories {
display: flex;
diff --git a/test/main/features/chat_attachments.test.ts b/test/main/features/chat_attachments.test.ts
index 788f5a81..5b146e7f 100644
--- a/test/main/features/chat_attachments.test.ts
+++ b/test/main/features/chat_attachments.test.ts
@@ -465,6 +465,106 @@ describe('chat_attachments › resolveLocalMediaPath', () => {
});
});
+describe('chat_attachments › resolveLocalPreviewPath', () => {
+ // Preview-doc sibling of resolveLocalMediaPath: accepts pdf / html / htm
+ // at arbitrary abs paths so the renderer can render LLM-produced docs
+ // inline. No size cap (Chromium streams through serveFileRange).
+ async function setup() {
+ const mod = await loadMod();
+ const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-localpreview-'));
+ return { mod, sandbox };
+ }
+
+ it('accepts an existing pdf at an arbitrary abs path', async () => {
+ const { mod, sandbox } = await setup();
+ const p = path.join(sandbox, 'doc.pdf');
+ fs.writeFileSync(p, makeMinimalPdf(['hi']));
+ const r = mod.resolveLocalPreviewPath(p);
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.kind).toBe('pdf');
+ expect(r.absPath).toBe(path.resolve(p));
+ fs.rmSync(sandbox, { recursive: true, force: true });
+ });
+
+ it('accepts .html and reports kind="html"', async () => {
+ const { mod, sandbox } = await setup();
+ const p = path.join(sandbox, 'page.html');
+ fs.writeFileSync(p, '<!doctype html><h1>ok</h1>');
+ const r = mod.resolveLocalPreviewPath(p);
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.kind).toBe('html');
+ fs.rmSync(sandbox, { recursive: true, force: true });
+ });
+
+ it('also accepts the .htm spelling', async () => {
+ const { mod, sandbox } = await setup();
+ const p = path.join(sandbox, 'old.htm');
+ fs.writeFileSync(p, '<html></html>');
+ const r = mod.resolveLocalPreviewPath(p);
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.kind).toBe('html');
+ fs.rmSync(sandbox, { recursive: true, force: true });
+ });
+
+ it('rejects image / video extensions (those belong to resolveLocalMediaPath)', async () => {
+ const { mod, sandbox } = await setup();
+ const p = path.join(sandbox, 'photo.png');
+ fs.writeFileSync(p, await makePng());
+ const r = mod.resolveLocalPreviewPath(p);
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.code).toBe('bad_input');
+ fs.rmSync(sandbox, { recursive: true, force: true });
+ });
+
+ it('rejects relative paths', async () => {
+ const { mod } = await setup();
+ const r = mod.resolveLocalPreviewPath('./foo.pdf');
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.code).toBe('bad_input');
+ });
+
+ it('returns not_found when the file is absent', async () => {
+ const { mod, sandbox } = await setup();
+ const r = mod.resolveLocalPreviewPath(path.join(sandbox, 'ghost.pdf'));
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.code).toBe('not_found');
+ fs.rmSync(sandbox, { recursive: true, force: true });
+ });
+
+ it('imposes no size cap (very-large pdfs accepted — Chromium streams)', async () => {
+ const { mod, sandbox } = await setup();
+ const p = path.join(sandbox, 'big.pdf');
+ // 60 MB — above any existing image / docx cap. The preview path has
+ // no cap by design; if a cap were silently reintroduced this would
+ // start failing.
+ fs.writeFileSync(p, Buffer.alloc(60 * 1024 * 1024));
+ const r = mod.resolveLocalPreviewPath(p);
+ expect(r.ok).toBe(true);
+ fs.rmSync(sandbox, { recursive: true, force: true });
+ });
+});
+
+describe('chat_attachments › mediaMimeFor (preview docs)', () => {
+ // Existing media MIME coverage already exists earlier in the file; this
+ // describe pins the preview-doc additions so a renamed handler doesn't
+ // silently downgrade pdf / html to octet-stream.
+ it('returns application/pdf for .pdf', async () => {
+ const m = await loadMod();
+ expect(m.mediaMimeFor('report.pdf')).toBe('application/pdf');
+ });
+ it('returns text/html for .html and .htm', async () => {
+ const m = await loadMod();
+ expect(m.mediaMimeFor('page.html')).toBe('text/html');
+ expect(m.mediaMimeFor('old.htm')).toBe('text/html');
+ });
+});
+
describe('chat_attachments › buildAttachmentManifest', () => {
it('emits text entry with total_chars (cheap stat, no body leak)', async () => {
const m = await loadMod();
@@ -521,17 +621,23 @@ describe('chat_attachments › buildAttachmentManifest', () => {
expect(r.skipped[0].name).toBe('clip.mp4');
});
- it('packs images into images[] as real-time compressed JPEG; manifest excludes them', async () => {
+ it('packs images into images[] as real-time compressed JPEG AND lists them in the manifest with attached="inline"', async () => {
const m = await loadMod();
await m.uploadAttachment(UID, CID, 'chart.png', await makePng());
const r = await m.buildAttachmentManifest(UID, CID, ['chart.png']);
- expect(r.manifest).toBe('');
+ // Manifest entry — gives the LLM a text-side handle on the image
+ // (filename + abs path) so it can answer "what did I upload" by name.
+ expect(r.manifest).toMatch(/<attachments>/);
+ expect(r.manifest).toMatch(/name="chart\.png"/);
+ expect(r.manifest).toMatch(/kind="image"/);
+ expect(r.manifest).toMatch(/attached="inline"/);
+ // Bytes — fed to vision via ChatOptions.images on the same user turn.
expect(r.images.length).toBe(1);
expect(r.images[0].mediaType).toBe('image/jpeg');
expect(r.images[0].data.length).toBeGreaterThan(100);
});
- it('caps images per message and reports the rest as skipped', async () => {
+ it('caps images per message: inlined ones appear in manifest, over-cap ones go to skipped[] only', async () => {
const m = await loadMod();
for (let i = 0; i < 7; i++) {
await m.uploadAttachment(UID, CID, `img${i}.png`, await makePng());
@@ -542,6 +648,11 @@ describe('chat_attachments › buildAttachmentManifest', () => {
{ maxImages: 3 },
);
expect(r.images).toHaveLength(3);
+ // Exactly 3 image entries in the manifest — over-cap images are dropped
+ // from BOTH images[] and entries[], surfaced only via skipped[].
+ expect(r.manifest.match(/<file [^>]*kind="image"/g)?.length).toBe(3);
+ expect(r.manifest).toMatch(/name="img0\.png"/);
+ expect(r.manifest).not.toMatch(/name="img6\.png"/);
expect(r.skipped.length).toBe(4);
expect(r.skipped.every((s) => /image cap|图片上限/.test(s.reason))).toBe(true);
});
diff --git a/test/main/features/local_agents/claude_e2e.test.ts b/test/main/features/local_agents/claude_e2e.test.ts
index 225806d1..9edaf18e 100644
--- a/test/main/features/local_agents/claude_e2e.test.ts
+++ b/test/main/features/local_agents/claude_e2e.test.ts
@@ -33,9 +33,13 @@ describe('local_agents/backends/claude › end-to-end with fake CLI', () => {
afterEach(() => { fs.rmSync(tmpDir, { recursive: true, force: true }); });
it('parses a minimal completed conversation', async () => {
+ // fake CLI reads one stdin line (the user message JSON) and then
+ // emits its stream-json output. We can't EOF-wait the way a real
+ // pipeline would (`cat > /dev/null`) because the backend now keeps
+ // stdin open for the whole turn to handle control_request — same
+ // contract real claude code has.
const fake = writeShellExecutable(tmpDir, 'claude', `#!/bin/sh
-# Read stdin and discard — claude is invoked with --input-format stream-json.
-cat > /dev/null
+read prompt
cat <<'EOF'
{"type":"system","subtype":"init","session_id":"sess-fake","cwd":"/x"}
{"type":"assistant","message":{"content":[{"type":"text","text":"Hello "}]}}
@@ -65,7 +69,6 @@ EOF
it('reports failed status when the CLI exits non-zero', async () => {
const fake = writeShellExecutable(tmpDir, 'claude', `#!/bin/sh
-cat > /dev/null
echo "boom: model unavailable" 1>&2
exit 7
`);
@@ -84,8 +87,9 @@ exit 7
it('cancels mid-run via AbortSignal (SIGTERM)', async () => {
const fake = writeShellExecutable(tmpDir, 'claude', `#!/bin/sh
-cat > /dev/null
-# Stay alive long enough to be killed.
+# Stay alive long enough to be killed. We don't bother reading stdin
+# here — the backend will write the prompt + later call stdin.end(),
+# both no-ops once SIGTERM lands.
sleep 10
`);
const events: any[] = [];
@@ -102,4 +106,95 @@ sleep 10
const done = events[events.length - 1];
expect(done.status).toBe('cancelled');
});
+
+ it('accumulates assistant.message.usage and emits running status:usage events', async () => {
+ // Two assistant blocks in sequence, each with its own usage
+ // snapshot. We expect TWO status:usage events with cumulative
+ // running totals (mirrors multica's per-model usage map but
+ // collapsed to a single flat record).
+ const fake = writeShellExecutable(tmpDir, 'claude', `#!/bin/sh
+read prompt
+cat <<'EOF'
+{"type":"system","subtype":"init","session_id":"s-acc","cwd":"/x"}
+{"type":"assistant","message":{"model":"claude-sonnet-4-6","content":[{"type":"text","text":"part 1"}],"usage":{"input_tokens":100,"output_tokens":50,"cache_read_input_tokens":1000,"cache_creation_input_tokens":20}}}
+{"type":"assistant","message":{"model":"claude-sonnet-4-6","content":[{"type":"text","text":"part 2"}],"usage":{"input_tokens":10,"output_tokens":40,"cache_read_input_tokens":1100,"cache_creation_input_tokens":0}}}
+{"type":"result","subtype":"success","result":"done","usage":{"input_tokens":110,"output_tokens":90,"cache_read_input_tokens":2100,"cache_creation_input_tokens":20},"total_cost_usd":0.0234,"message":{"model":"claude-sonnet-4-6"}}
+EOF
+`);
+ const events: any[] = [];
+ await claudeBackend.run({
+ binPath: fake,
+ prompt: 'go',
+ cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ timeoutMs: 3000,
+ });
+ const usageEvents = events.filter(e => e.type === 'status' && e.status === 'usage');
+ expect(usageEvents).toHaveLength(2);
+ expect(usageEvents[0].usage).toMatchObject({
+ input: 100, output: 50, cacheRead: 1000, cacheCreate: 20, model: 'claude-sonnet-4-6',
+ });
+ // Second one should be the cumulative running total.
+ expect(usageEvents[1].usage).toMatchObject({
+ input: 110, output: 90, cacheRead: 2100, cacheCreate: 20,
+ });
+ // The terminal status:result still carries claude's authoritative
+ // (already-summed) usage from the result record + the cost field.
+ const resultStatus = events.find(e => e.type === 'status' && e.status === 'result');
+ expect(resultStatus?.usage).toMatchObject({
+ input: 110, output: 90, cacheRead: 2100, cacheCreate: 20, cost: 0.0234,
+ });
+ const done = events[events.length - 1];
+ expect(done.status).toBe('completed');
+ });
+
+ it('auto-responds to control_request and surfaces a permission-request event', async () => {
+ // fake CLI: reads the prompt, emits init + a control_request, then
+ // reads ONE more line from stdin (our control_response) and only
+ // then emits the terminal result. If the backend doesn't write the
+ // response, the script blocks on its second `read` until the
+ // 3-second test timeout fires — that's the silent-hang symptom
+ // we're fixing.
+ //
+ // We tee the response we received to stderr so the test can assert
+ // exactly what got written back to the CLI.
+ const fake = writeShellExecutable(tmpDir, 'claude', `#!/bin/sh
+read prompt
+cat <<'EOF'
+{"type":"system","subtype":"init","session_id":"sess-perm","cwd":"/x"}
+{"type":"control_request","request_id":"req-42","request":{"subtype":"can_use_tool","tool_name":"Bash","input":{"command":"ls"}}}
+EOF
+read response
+echo "GOT_RESPONSE: $response" 1>&2
+cat <<'EOF'
+{"type":"result","subtype":"success","result":"ok"}
+EOF
+`);
+ const events: any[] = [];
+ await claudeBackend.run({
+ binPath: fake,
+ prompt: 'run ls',
+ cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ timeoutMs: 3000,
+ });
+ const types = events.map(e => e.type);
+ expect(types).toContain('permission-request');
+ const perm = events.find(e => e.type === 'permission-request');
+ expect(perm).toMatchObject({ id: 'req-42', tool: 'Bash', autoDecided: 'allow', reason: 'bypass' });
+ // Verify the response we wrote back is a valid control_response
+ // referencing the same request_id (the fake CLI tees it to stderr).
+ const stderrLines = events
+ .filter(e => e.type === 'stderr-line')
+ .map(e => (e as any).line as string);
+ const responseEcho = stderrLines.find(l => l.startsWith('GOT_RESPONSE:'));
+ expect(responseEcho).toBeDefined();
+ expect(responseEcho).toMatch(/"control_response"/);
+ expect(responseEcho).toMatch(/"req-42"/);
+ expect(responseEcho).toMatch(/"behavior":"allow"/);
+ const done = events[events.length - 1];
+ expect(done.status).toBe('completed');
+ });
});
diff --git a/test/main/features/local_agents/claude_parser.test.ts b/test/main/features/local_agents/claude_parser.test.ts
index a60e465e..9d0984a0 100644
--- a/test/main/features/local_agents/claude_parser.test.ts
+++ b/test/main/features/local_agents/claude_parser.test.ts
@@ -1,11 +1,11 @@
import { describe, it, expect } from 'vitest';
-import { mapClaudeEvent } from '../../../../src/main/features/local_agents/backends/claude';
+import { mapClaudeEvent, extractClaudeUsage } from '../../../../src/main/features/local_agents/backends/claude';
describe('local_agents/backends/claude › mapClaudeEvent', () => {
- it('captures session id from system/init', () => {
+ it('captures session id AND emits status:running on system/init (parity with multica)', () => {
const r = mapClaudeEvent({ type: 'system', subtype: 'init', session_id: 'sess-1', cwd: '/x' }, undefined);
expect(r?.captureSession).toBe(true);
- expect(r?.event).toBeUndefined();
+ expect(r?.event).toEqual({ type: 'status', status: 'running' });
});
it('emits text-delta for assistant text content (fallback when no stream_event)', () => {
@@ -42,12 +42,16 @@ describe('local_agents/backends/claude › mapClaudeEvent', () => {
expect(r?.event).toEqual({ type: 'thinking', text: 'pondering' });
});
- it('emits tool-event(use) from stream_event content_block_start', () => {
+ it('drops stream_event content_block_start tool_use (input arrives empty there; assistant block re-emits with full input)', () => {
+ // claude streams tool input via input_json_delta after content_block_start;
+ // emitting at start produced a duplicate `■ tool · 开始 · {}` row visually.
+ // The assistant block (test below) is the single source of truth for
+ // tool-use events.
const r = mapClaudeEvent({
type: 'stream_event',
- event: { type: 'content_block_start', content_block: { type: 'tool_use', id: 't1', name: 'Read', input: { file: 'x.md' } } },
+ event: { type: 'content_block_start', content_block: { type: 'tool_use', id: 't1', name: 'Read', input: {} } },
}, undefined);
- expect(r?.event).toMatchObject({ type: 'tool-event', tool: 'Read', callId: 't1', phase: 'use' });
+ expect(r).toBeUndefined();
});
it('emits tool-event(use) for assistant tool_use block', () => {
@@ -93,4 +97,101 @@ describe('local_agents/backends/claude › mapClaudeEvent', () => {
expect(mapClaudeEvent({ type: 'unknown' }, undefined)).toBeUndefined();
expect(mapClaudeEvent({ type: 'assistant', message: { content: [] } }, undefined)).toBeUndefined();
});
+
+ it('emits log event for {type:"log"} records (verbose mode)', () => {
+ const r = mapClaudeEvent({ type: 'log', log: { level: 'warn', message: 'mcp slow' } }, 'sess');
+ expect(r?.event).toMatchObject({
+ type: 'log',
+ level: 'warn',
+ message: 'mcp slow',
+ source: 'claude',
+ });
+ });
+
+ it('folds an unknown log level to info', () => {
+ const r = mapClaudeEvent({ type: 'log', log: { level: 'banana', message: 'huh' } }, 'sess');
+ expect(r?.event).toMatchObject({ type: 'log', level: 'info', message: 'huh' });
+ });
+
+ it('drops log records with no message body', () => {
+ const r = mapClaudeEvent({ type: 'log', log: { level: 'info' } }, 'sess');
+ expect(r).toBeUndefined();
+ });
+
+ it('attaches usage to BOTH the terminal record AND the status event so the rail can render tokens', () => {
+ const r = mapClaudeEvent({
+ type: 'result',
+ subtype: 'success',
+ result: 'final',
+ usage: {
+ input_tokens: 1234,
+ output_tokens: 567,
+ cache_read_input_tokens: 800,
+ cache_creation_input_tokens: 12,
+ },
+ message: { model: 'claude-sonnet-4-6' },
+ }, 'sess');
+ const expected = {
+ input: 1234,
+ output: 567,
+ cacheRead: 800,
+ cacheCreate: 12,
+ model: 'claude-sonnet-4-6',
+ };
+ expect(r?.terminal?.usage).toEqual(expected);
+ // Status event also carries usage so the rail renders
+ // "● result · in=1234 out=567 cache=800" — without this the
+ // last row is a bare `● result` with no token signal.
+ expect((r?.event as any)?.usage).toEqual(expected);
+ });
+
+ it('omits usage from the status event when result has no usage block', () => {
+ const r = mapClaudeEvent({ type: 'result', subtype: 'success', result: 'final' }, 'sess');
+ expect((r?.event as any)?.usage).toBeUndefined();
+ });
+
+ it('omits terminal.usage when the result record carries no usage block (older claude)', () => {
+ const r = mapClaudeEvent({ type: 'result', subtype: 'success', result: 'final' }, 'sess');
+ expect(r?.terminal?.usage).toBeUndefined();
+ });
+
+ it('extractClaudeUsage tolerates partial usage records (only some keys present)', () => {
+ const u = extractClaudeUsage({ usage: { input_tokens: 10 } });
+ expect(u).toEqual({ input: 10 });
+ });
+
+ it('extractClaudeUsage returns undefined when nothing recognizable is present', () => {
+ expect(extractClaudeUsage({})).toBeUndefined();
+ expect(extractClaudeUsage({ usage: { foo: 'bar' } })).toBeUndefined();
+ });
+
+ it('extractClaudeUsage pulls cost from total_cost_usd', () => {
+ const u = extractClaudeUsage({
+ usage: { input_tokens: 1, output_tokens: 2 },
+ total_cost_usd: 0.0234,
+ });
+ expect(u).toMatchObject({ input: 1, output: 2, cost: 0.0234 });
+ });
+
+ it('extractClaudeUsage still returns a record when only cost is present (no token block)', () => {
+ // Defensive: future claude versions might drop the usage block when
+ // the user opted out of token reporting; cost alone is still useful.
+ const u = extractClaudeUsage({ total_cost_usd: 0.5 });
+ expect(u).toEqual({ cost: 0.5 });
+ });
+
+ it('returns undefined for control_request (handled out-of-band by backend)', () => {
+ // The mapper is a pure translator; the stdin write-back for
+ // control_request lives in claude.ts so the mapper stays
+ // side-effect-free. The backend short-circuits before calling
+ // mapClaudeEvent for this type, so it MUST NOT also produce an
+ // event here — that would double-emit or hide a bug if the
+ // short-circuit ever regresses.
+ const r = mapClaudeEvent({
+ type: 'control_request',
+ request_id: 'req-1',
+ request: { subtype: 'can_use_tool', tool_name: 'Bash', input: { command: 'ls' } },
+ }, 'sess');
+ expect(r).toBeUndefined();
+ });
});
diff --git a/test/main/features/local_agents/codex_parser.test.ts b/test/main/features/local_agents/codex_parser.test.ts
index cf146026..dc26df06 100644
--- a/test/main/features/local_agents/codex_parser.test.ts
+++ b/test/main/features/local_agents/codex_parser.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { extractThreadId } from '../../../../src/main/features/local_agents/backends/codex';
+import { extractThreadId, extractCodexUsage } from '../../../../src/main/features/local_agents/backends/codex';
describe('local_agents/backends/codex › extractThreadId', () => {
it('returns top-level threadId when present', () => {
@@ -23,3 +23,53 @@ describe('local_agents/backends/codex › extractThreadId', () => {
expect(extractThreadId({ threadId: 'top', thread: { id: 'nested' } })).toBe('top');
});
});
+
+describe('local_agents/backends/codex › extractCodexUsage', () => {
+ it('pulls usage from a flat snake_case params block', () => {
+ const u = extractCodexUsage({
+ threadId: 't1',
+ input_tokens: 100,
+ output_tokens: 50,
+ cache_read_input_tokens: 30,
+ });
+ expect(u).toEqual({ input: 100, output: 50, cacheRead: 30 });
+ });
+
+ it('pulls usage from camelCase variants codex sometimes emits', () => {
+ const u = extractCodexUsage({
+ inputTokens: 100,
+ outputTokens: 50,
+ cacheReadInputTokens: 30,
+ cacheCreationInputTokens: 12,
+ model: 'gpt-5',
+ });
+ expect(u).toEqual({
+ input: 100, output: 50, cacheRead: 30, cacheCreate: 12, model: 'gpt-5',
+ });
+ });
+
+ it('reads from params.info.totalTokenUsage nested shape', () => {
+ const u = extractCodexUsage({
+ info: {
+ model: 'gpt-5',
+ totalTokenUsage: {
+ input_tokens: 1, output_tokens: 2, cache_read_input_tokens: 3,
+ },
+ },
+ });
+ expect(u).toMatchObject({ input: 1, output: 2, cacheRead: 3, model: 'gpt-5' });
+ });
+
+ it('falls back to lastTokenUsage when totalTokenUsage is absent', () => {
+ const u = extractCodexUsage({
+ info: { lastTokenUsage: { input_tokens: 9, output_tokens: 8 } },
+ });
+ expect(u).toMatchObject({ input: 9, output: 8 });
+ });
+
+ it('returns undefined when no recognizable numeric fields are present', () => {
+ expect(extractCodexUsage({})).toBeUndefined();
+ expect(extractCodexUsage({ usage: { unknownKey: 'foo' } })).toBeUndefined();
+ expect(extractCodexUsage(null)).toBeUndefined();
+ });
+});
diff --git a/test/main/features/local_agents/openclaw_parser.test.ts b/test/main/features/local_agents/openclaw_parser.test.ts
index 6ceca1f2..7de96cb4 100644
--- a/test/main/features/local_agents/openclaw_parser.test.ts
+++ b/test/main/features/local_agents/openclaw_parser.test.ts
@@ -77,4 +77,38 @@ describe('local_agents/backends/openclaw › parseOpenclawReply', () => {
const r = parseOpenclawReply(stderr);
expect(r?.text).toBe('code: { foo: { bar } }');
});
+
+ it('extracts usage when meta.agentMeta.usage is present', () => {
+ const stderr = `{
+ "payloads": [{ "text": "ok" }],
+ "meta": {
+ "agentMeta": {
+ "sessionId": "s1",
+ "model": "claude-sonnet-4-6",
+ "usage": {
+ "input_tokens": 1200,
+ "output_tokens": 450,
+ "cache_read_input_tokens": 800
+ }
+ }
+ }
+}`;
+ const r = parseOpenclawReply(stderr);
+ expect(r?.usage).toEqual({
+ input: 1200,
+ output: 450,
+ cacheRead: 800,
+ model: 'claude-sonnet-4-6',
+ });
+ });
+
+ it('returns no usage field when the envelope has none (legacy openclaw builds)', () => {
+ const stderr = `{
+ "payloads": [{ "text": "ok" }],
+ "meta": { "agentMeta": { "sessionId": "s1" } }
+}`;
+ const r = parseOpenclawReply(stderr);
+ expect(r?.text).toBe('ok');
+ expect((r as any).usage).toBeUndefined();
+ });
});
diff --git a/test/main/features/local_agents/opencode_parser.test.ts b/test/main/features/local_agents/opencode_parser.test.ts
new file mode 100644
index 00000000..551bf551
--- /dev/null
+++ b/test/main/features/local_agents/opencode_parser.test.ts
@@ -0,0 +1,98 @@
+import { describe, it, expect } from 'vitest';
+import {
+ mapOpencodeEvent,
+ extractOpencodeUsage,
+} from '../../../../src/main/features/local_agents/backends/opencode';
+
+describe('local_agents/backends/opencode › mapOpencodeEvent', () => {
+ it('captures sessionID at the top level', () => {
+ const r = mapOpencodeEvent({ type: 'step_start', sessionID: 's1' });
+ expect(r?.captureSessionId).toBe('s1');
+ expect((r?.event as any)?.status).toBe('running');
+ });
+
+ it('captures sessionID nested under .part', () => {
+ const r = mapOpencodeEvent({ type: 'text', part: { sessionID: 's2', text: 'hi' } });
+ expect(r?.captureSessionId).toBe('s2');
+ expect(r?.event).toEqual({ type: 'text-delta', text: 'hi' });
+ });
+
+ it('maps tool_use in-progress to phase:use with input', () => {
+ const r = mapOpencodeEvent({
+ type: 'tool_use',
+ part: { tool: 'read_file', callID: 'c1', state: { status: 'pending', input: { path: 'x.md' } } },
+ });
+ expect(r?.event).toMatchObject({ type: 'tool-event', tool: 'read_file', phase: 'use', callId: 'c1' });
+ expect((r?.event as any).input).toEqual({ path: 'x.md' });
+ });
+
+ it('maps tool_use completed to phase:result with output', () => {
+ const r = mapOpencodeEvent({
+ type: 'tool_use',
+ part: { tool: 'read_file', callID: 'c1', state: { status: 'completed', output: 'file body' } },
+ });
+ expect(r?.event).toMatchObject({ type: 'tool-event', phase: 'result', output: 'file body' });
+ });
+
+ it('stringifies non-string tool outputs', () => {
+ const r = mapOpencodeEvent({
+ type: 'tool_use',
+ part: { tool: 'kb_search', callID: 'c1', state: { status: 'completed', output: { hits: 4 } } },
+ });
+ expect((r?.event as any).output).toBe('{"hits":4}');
+ });
+
+ it('error type produces a terminal failed status with message', () => {
+ const r = mapOpencodeEvent({ type: 'error', error: { data: { message: 'auth fail' } } });
+ expect(r?.terminal).toEqual({ status: 'failed', error: 'auth fail' });
+ });
+
+ it('step_finish with extractable usage produces status:usage (not log)', () => {
+ const r = mapOpencodeEvent({
+ type: 'step_finish',
+ part: { tokens: { input: 100, output: 50, cache: 25 }, model: 'gpt-5' },
+ });
+ expect(r?.event).toEqual({
+ type: 'status',
+ status: 'usage',
+ usage: { input: 100, output: 50, cacheRead: 25, model: 'gpt-5' },
+ });
+ });
+
+ it('step_finish without usage falls back to a debug log so the row is still visible', () => {
+ const r = mapOpencodeEvent({ type: 'step_finish', part: { foo: 'bar' } });
+ expect((r?.event as any).type).toBe('log');
+ expect((r?.event as any).level).toBe('debug');
+ expect((r?.event as any).message).toContain('step_finish');
+ });
+
+ it('unknown event type becomes an info log so wire-format drift is visible', () => {
+ const r = mapOpencodeEvent({ type: 'mystery_new_event', payload: 1 });
+ expect((r?.event as any).type).toBe('log');
+ expect((r?.event as any).level).toBe('info');
+ expect((r?.event as any).message).toContain('mystery_new_event');
+ });
+});
+
+describe('local_agents/backends/opencode › extractOpencodeUsage', () => {
+ it('reads from part.tokens nested block (canonical shape)', () => {
+ const u = extractOpencodeUsage({ tokens: { input: 10, output: 20, cache: 5 } });
+ expect(u).toEqual({ input: 10, output: 20, cacheRead: 5 });
+ });
+
+ it('also accepts a flat shape with snake_case keys', () => {
+ const u = extractOpencodeUsage({ input_tokens: 10, output_tokens: 20 });
+ expect(u).toEqual({ input: 10, output: 20 });
+ });
+
+ it('attaches model when present', () => {
+ const u = extractOpencodeUsage({ tokens: { input: 1, output: 1 }, model: 'gpt-5' });
+ expect(u?.model).toBe('gpt-5');
+ });
+
+ it('returns undefined when no numeric counter is present', () => {
+ expect(extractOpencodeUsage({})).toBeUndefined();
+ expect(extractOpencodeUsage({ tokens: {} })).toBeUndefined();
+ expect(extractOpencodeUsage(null)).toBeUndefined();
+ });
+});
diff --git a/test/main/features/local_agents/runner.test.ts b/test/main/features/local_agents/runner.test.ts
index cc81f4ad..f7f550d9 100644
--- a/test/main/features/local_agents/runner.test.ts
+++ b/test/main/features/local_agents/runner.test.ts
@@ -179,6 +179,123 @@ describe('local_agents/runner', () => {
expect(result.error).toMatch(/timeout/);
});
+ it('emits idle events when the backend goes quiet beyond the threshold', async () => {
+ // Use real timers but shrink the threshold via env vars. The
+ // ORKAS_LOCAL_AGENT_IDLE_MIN_MS escape hatch exists exactly so
+ // unit tests can exercise the heartbeat at ~100ms rather than
+ // the 30s production floor.
+ const prevIdleMs = process.env.ORKAS_LOCAL_AGENT_IDLE_MS;
+ const prevIdleMin = process.env.ORKAS_LOCAL_AGENT_IDLE_MIN_MS;
+ process.env.ORKAS_LOCAL_AGENT_IDLE_MIN_MS = '50';
+ process.env.ORKAS_LOCAL_AGENT_IDLE_MS = '120'; // threshold 120ms
+ try {
+ mockDetect.mockResolvedValue({ type: 'claude', available: true, path: '/fake/claude', version: '2.0.0' });
+ let onEventCb: ((e: any) => void) | null = null;
+ let resolveBackend!: () => void;
+ mockBackendImpl = async ({ onEvent }) => {
+ onEventCb = onEvent;
+ onEvent({ type: 'process-info', pid: 42, cwd: '/x', cmd: 'claude', args: [] });
+ await new Promise<void>(resolve => { resolveBackend = resolve; });
+ onEvent({ type: 'done', status: 'completed', output: '', durationMs: 0 });
+ };
+
+ const runner = await loadRunner();
+ const events: any[] = [];
+ const promise = runner.run({
+ uid: TEST_UID, cid: 'c', agentId: 'a',
+ cli: 'claude', prompt: 'p', cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ });
+
+ // Threshold=120ms, tick = max(50, 120/3=40) → 50ms. Wait ~250ms:
+ // at least 2 idle pulses should fire after the 120ms quiet period.
+ await new Promise(r => setTimeout(r, 250));
+ const idleCount1 = events.filter(e => e.type === 'idle').length;
+ expect(idleCount1).toBeGreaterThanOrEqual(1);
+
+ // Continue waiting → steady drumbeat (more idle events).
+ await new Promise(r => setTimeout(r, 150));
+ const idleCount2 = events.filter(e => e.type === 'idle').length;
+ expect(idleCount2).toBeGreaterThan(idleCount1);
+
+ // Backend emits a real event — deadline should reset, so no new
+ // idle pulse during the next sub-threshold window.
+ onEventCb!({ type: 'text-delta', text: 'still here' });
+ const beforeReset = events.filter(e => e.type === 'idle').length;
+ await new Promise(r => setTimeout(r, 80)); // less than 120ms threshold
+ const afterReset = events.filter(e => e.type === 'idle').length;
+ expect(afterReset).toBe(beforeReset); // no new idle fired
+
+ resolveBackend();
+ await promise;
+ } finally {
+ if (prevIdleMs === undefined) delete process.env.ORKAS_LOCAL_AGENT_IDLE_MS;
+ else process.env.ORKAS_LOCAL_AGENT_IDLE_MS = prevIdleMs;
+ if (prevIdleMin === undefined) delete process.env.ORKAS_LOCAL_AGENT_IDLE_MIN_MS;
+ else process.env.ORKAS_LOCAL_AGENT_IDLE_MIN_MS = prevIdleMin;
+ }
+ });
+
+ it('spills oversized tool-event results to disk and rewrites output + outputPath', async () => {
+ const { PERSIST_THRESHOLD } = await import('../../../../src/main/util/tool-result-cap');
+ const big = 'X'.repeat(PERSIST_THRESHOLD + 200);
+ mockDetect.mockResolvedValue({ type: 'claude', available: true, path: '/fake/claude', version: '2.0.0' });
+ mockBackendImpl = async ({ onEvent }) => {
+ onEvent({ type: 'process-info', pid: 1, cwd: '/x', cmd: 'claude', args: [] });
+ // Tool-event with massive output — the runner must intercept and
+ // spill this before it lands in events.jsonl or reaches the caller.
+ onEvent({
+ type: 'tool-event', tool: 'bash', callId: 'c1', phase: 'result', output: big,
+ });
+ onEvent({ type: 'done', status: 'completed', output: '', durationMs: 0 });
+ };
+
+ const runner = await loadRunner();
+ const events: any[] = [];
+ const result = await runner.run({
+ uid: TEST_UID, cid: 'c', agentId: 'a',
+ cli: 'claude', prompt: 'p', cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ });
+ expect(result.status).toBe('completed');
+
+ const toolEvent = events.find(e => e.type === 'tool-event' && e.phase === 'result');
+ expect(toolEvent).toBeDefined();
+ expect(toolEvent.outputPath).toBeTruthy();
+ expect(typeof toolEvent.output).toBe('string');
+ // Output is now the preview marker, not the full payload.
+ expect(toolEvent.output.length).toBeLessThan(big.length);
+ expect(toolEvent.output).toMatch(/<persisted-output/);
+ // The full content is on disk at the reported path.
+ expect(fs.existsSync(toolEvent.outputPath)).toBe(true);
+ expect(fs.readFileSync(toolEvent.outputPath, 'utf8')).toBe(big);
+ // Spill landed under the expected per-session directory shape:
+ // <uid>/local/tool-results/<uid>-cli-claude-<runId>/bash.<id>.txt
+ expect(toolEvent.outputPath).toContain(`${TEST_UID}-cli-claude-${result.runId}`);
+ expect(toolEvent.outputPath).toMatch(/bash\.[0-9a-f]+\.txt$/);
+ });
+
+ it('does not spill small tool-event outputs', async () => {
+ mockDetect.mockResolvedValue({ type: 'claude', available: true, path: '/fake/claude', version: '2.0.0' });
+ mockBackendImpl = async ({ onEvent }) => {
+ onEvent({ type: 'tool-event', tool: 'bash', callId: 'c1', phase: 'result', output: 'small output' });
+ onEvent({ type: 'done', status: 'completed', output: '', durationMs: 0 });
+ };
+ const runner = await loadRunner();
+ const events: any[] = [];
+ await runner.run({
+ uid: TEST_UID, cid: 'c', agentId: 'a',
+ cli: 'claude', prompt: 'p', cwd: tmpDir,
+ signal: new AbortController().signal,
+ onEvent: e => events.push(e),
+ });
+ const toolEvent = events.find(e => e.type === 'tool-event' && e.phase === 'result');
+ expect(toolEvent.output).toBe('small output');
+ expect(toolEvent.outputPath).toBeUndefined();
+ });
+
it('rejects unregistered CLI types cleanly', async () => {
const runner = await loadRunner();
const events: any[] = [];
diff --git a/test/main/ipc/local_agents-read-tool-result.test.ts b/test/main/ipc/local_agents-read-tool-result.test.ts
new file mode 100644
index 00000000..2539adf7
--- /dev/null
+++ b/test/main/ipc/local_agents-read-tool-result.test.ts
@@ -0,0 +1,159 @@
+/**
+ * Tests for the `localAgents.readToolResult` IPC handler.
+ *
+ * Security invariants the handler MUST hold (CLAUDE.md §5 boundary):
+ * - active uid only, path must resolve under <uid>/local/tool-results/
+ * - reject ENOENT, symlink-escape, traversal (`../`), non-file targets
+ * - byte-cap reads at 256 KB; signal truncation via `{truncated:true}`
+ *
+ * Never throws across the IPC boundary — all failure modes return
+ * `{ok:false, error}` so a UI bug can't crash the renderer.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+let tmpDir: string;
+let prevWs: string | undefined;
+const TEST_UID = 'u1';
+
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-readtoolresult-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ // Each test gets a fresh module graph so users.activateUser doesn't
+ // bleed across.
+ const { vi } = await import('vitest');
+ vi.resetModules();
+ const users = await import('../../../src/main/features/users');
+ users.activateUser(TEST_UID);
+});
+
+afterEach(() => {
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+async function callHandler(input: unknown): Promise<any> {
+ const mod = await import('../../../src/main/ipc/local_agents');
+ return (mod.invokeHandlers as any)['localAgents.readToolResult'](input as any);
+}
+
+function sessionDir(): string {
+ // Mirror sessionToolResultsDir(uid, '<uid>-cli-claude-runX') so we
+ // can drop fixtures into the same shape the runner spills into.
+ const dir = path.join(
+ tmpDir, TEST_UID, 'local', 'tool-results', `${TEST_UID}-cli-claude-runtest`,
+ );
+ fs.mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+describe('ipc/local_agents.readToolResult', () => {
+ it('rejects when path is missing / not a string', async () => {
+ expect(await callHandler({})).toMatchObject({ ok: false });
+ expect(await callHandler({ path: 42 })).toMatchObject({ ok: false });
+ expect(await callHandler({ path: '' })).toMatchObject({ ok: false });
+ });
+
+ it('reads a small spill file when path is inside tool-results/', async () => {
+ const dir = sessionDir();
+ const filePath = path.join(dir, 'bash.abc.txt');
+ fs.writeFileSync(filePath, 'hello world');
+ const r = await callHandler({ path: filePath });
+ expect(r.ok).toBe(true);
+ expect(r.content).toBe('hello world');
+ expect(r.truncated).toBe(false);
+ });
+
+ it('rejects an absolute path outside the active uid tool-results dir', async () => {
+ const outside = path.join(tmpDir, 'evil.txt');
+ fs.writeFileSync(outside, 'leaked');
+ const r = await callHandler({ path: outside });
+ expect(r.ok).toBe(false);
+ expect(String(r.error)).toMatch(/outside tool-results scope/);
+ });
+
+ it('rejects a `..` traversal that escapes via path concat', async () => {
+ const dir = sessionDir();
+ // Construct a path that, before realpath, includes `..` segments
+ // pointing OUT of tool-results/. realpath collapses them; the
+ // handler then sees the canonical out-of-scope path and rejects.
+ // tmpDir on macOS may itself be a symlink (/var → /private/var),
+ // so we put the file at a known sibling-of-sessionDir absolute
+ // location and reach it through `..` from sessionDir.
+ const outsideDir = path.join(tmpDir, 'evil-sibling');
+ fs.mkdirSync(outsideDir, { recursive: true });
+ const outsideFile = path.join(outsideDir, 'evil.txt');
+ fs.writeFileSync(outsideFile, 'leaked');
+ // sessionDir is <tmpDir>/u1/local/tool-results/<session>;
+ // 4 `..` go back to tmpDir, then into the sibling.
+ const escapingPath = path.join(dir, '..', '..', '..', '..', 'evil-sibling', 'evil.txt');
+ const r = await callHandler({ path: escapingPath });
+ expect(r.ok).toBe(false);
+ expect(String(r.error)).toMatch(/outside tool-results scope/);
+ });
+
+ it('rejects ENOENT cleanly without throwing', async () => {
+ const dir = sessionDir();
+ const r = await callHandler({ path: path.join(dir, 'never-existed.txt') });
+ expect(r.ok).toBe(false);
+ expect(String(r.error)).toMatch(/no longer exists/);
+ });
+
+ it('rejects when the resolved target is a directory, not a file', async () => {
+ const dir = sessionDir();
+ const r = await callHandler({ path: dir });
+ expect(r.ok).toBe(false);
+ expect(String(r.error)).toMatch(/not a regular file/);
+ });
+
+ it('truncates files larger than the 256 KB cap and reports truncated:true', async () => {
+ const dir = sessionDir();
+ const filePath = path.join(dir, 'huge.txt');
+ // Write 300 KB of A's.
+ const huge = 'A'.repeat(300 * 1024);
+ fs.writeFileSync(filePath, huge);
+ const r = await callHandler({ path: filePath });
+ expect(r.ok).toBe(true);
+ expect(r.truncated).toBe(true);
+ expect(r.content.length).toBe(256 * 1024);
+ expect(r.content.startsWith('A')).toBe(true);
+ });
+
+ it('rejects when a symlink points OUT of tool-results/', async () => {
+ const dir = sessionDir();
+ const outside = path.join(tmpDir, 'evil-target.txt');
+ fs.writeFileSync(outside, 'should not leak');
+ const linkPath = path.join(dir, 'innocent-looking.txt');
+ try {
+ fs.symlinkSync(outside, linkPath);
+ } catch (err) {
+ // Some sandboxed CI envs forbid symlinks; skip this case
+ // rather than fail the test on platform constraints.
+ if ((err as NodeJS.ErrnoException).code === 'EPERM') return;
+ throw err;
+ }
+ const r = await callHandler({ path: linkPath });
+ expect(r.ok).toBe(false);
+ expect(String(r.error)).toMatch(/outside tool-results scope/);
+ });
+
+ it('allows a symlink that resolves WITHIN tool-results/', async () => {
+ const dir = sessionDir();
+ const real = path.join(dir, 'real.txt');
+ fs.writeFileSync(real, 'inside content');
+ const linkPath = path.join(dir, 'alias.txt');
+ try {
+ fs.symlinkSync(real, linkPath);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'EPERM') return;
+ throw err;
+ }
+ const r = await callHandler({ path: linkPath });
+ expect(r.ok).toBe(true);
+ expect(r.content).toBe('inside content');
+ });
+});
diff --git a/test/main/ipc/produced-readText.test.ts b/test/main/ipc/produced-readText.test.ts
new file mode 100644
index 00000000..ff65ff5b
--- /dev/null
+++ b/test/main/ipc/produced-readText.test.ts
@@ -0,0 +1,199 @@
+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';
+
+// Mock electron — the IPC router imports `shell` / `dialog` / `ipcMain` at
+// module load, none of which are exercised by the readText handler.
+vi.mock('electron', () => ({
+ ipcMain: { handle: vi.fn(), on: vi.fn() },
+ dialog: { showOpenDialog: vi.fn(async () => ({ canceled: true, filePaths: [] })) },
+ BrowserWindow: { getFocusedWindow: vi.fn(() => null) },
+ shell: { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') },
+}));
+
+let tmpDir: string;
+let prevWs: string | undefined;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-readText-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ vi.resetModules();
+});
+
+afterEach(() => {
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+// The IPC table in ipc/index.ts isn't exported per-handler, so — same
+// pattern as workspace-reveal.test.ts — reproduce the handler body
+// inline using the same modules the real handler imports. If the source
+// drifts the test must drift with it; the unit-test triage explicitly
+// covers this kind of multi-branch decision function (CLAUDE.md §9).
+async function callReadText(
+ userId: string,
+ input: { path?: unknown; cid?: unknown },
+): Promise<{ ok: boolean; error?: string; size?: number; cap?: number; text?: string }> {
+ const userWorkspace = await import('../../../src/main/features/user_workspace');
+ const { chatAttachmentDir } = await import('../../../src/main/paths');
+ const { safeId } = await import('../../../src/main/storage');
+
+ const target = input?.path;
+ if (typeof target !== 'string' || !target) return { ok: false, error: 'missing path' };
+ const ws = userWorkspace.getWorkspacePath(userId);
+ const norm = path.resolve(target);
+ const wsNorm = path.resolve(ws);
+ const cidRaw = input?.cid;
+ const attachmentScope = (typeof cidRaw === 'string' && cidRaw && safeId(cidRaw))
+ ? path.resolve(chatAttachmentDir(userId, cidRaw))
+ : null;
+ const inAttachment = !!attachmentScope &&
+ (norm === attachmentScope || norm.startsWith(attachmentScope + path.sep));
+ const inWorkspace = norm === wsNorm || norm.startsWith(wsNorm + path.sep);
+ if (!inWorkspace && !inAttachment) {
+ return { ok: false, error: 'path is outside the user workspace' };
+ }
+ let st: fs.Stats;
+ try { st = fs.statSync(norm); }
+ catch { return { ok: false, error: 'not_found' }; }
+ if (!st.isFile()) return { ok: false, error: 'not_found' };
+ const MAX_TEXT_BYTES = 2 * 1024 * 1024;
+ if (st.size > MAX_TEXT_BYTES) {
+ return { ok: false, error: 'too_large', size: st.size, cap: MAX_TEXT_BYTES };
+ }
+ let text = fs.readFileSync(norm, 'utf8');
+ if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1);
+ return { ok: true, text, size: st.size };
+}
+
+describe('produced.readText › scope', () => {
+ it('reads a markdown file inside the user workspace', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const dir = path.join(tmpDir, 'ws');
+ fs.mkdirSync(dir, { recursive: true });
+ ws.setWorkspacePath('u1', dir);
+ const file = path.join(dir, 'note.md');
+ fs.writeFileSync(file, '# hi');
+
+ const res = await callReadText('u1', { path: file });
+ expect(res.ok).toBe(true);
+ expect(res.text).toBe('# hi');
+ });
+
+ it('reads a file under the per-cid attachment dir when cid is provided', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const { chatAttachmentDir } = await import('../../../src/main/paths');
+ const dir = path.join(tmpDir, 'ws');
+ fs.mkdirSync(dir, { recursive: true });
+ ws.setWorkspacePath('u2', dir);
+
+ const cid = 'conv-abc';
+ const attachDir = chatAttachmentDir('u2', cid);
+ fs.mkdirSync(attachDir, { recursive: true });
+ const file = path.join(attachDir, 'doc.txt');
+ fs.writeFileSync(file, 'hello attachment');
+
+ const res = await callReadText('u2', { path: file, cid });
+ expect(res.ok).toBe(true);
+ expect(res.text).toBe('hello attachment');
+ });
+
+ it('rejects an attachment-dir path when cid is omitted', async () => {
+ // Without cid the scope unions to workspace only. Files in
+ // chat_attachments/<cid>/ are not visible — even though the user owns them.
+ const ws = await import('../../../src/main/features/user_workspace');
+ const { chatAttachmentDir } = await import('../../../src/main/paths');
+ const dir = path.join(tmpDir, 'ws');
+ fs.mkdirSync(dir, { recursive: true });
+ ws.setWorkspacePath('u3', dir);
+ const cid = 'conv-xyz';
+ const attachDir = chatAttachmentDir('u3', cid);
+ fs.mkdirSync(attachDir, { recursive: true });
+ const file = path.join(attachDir, 'doc.txt');
+ fs.writeFileSync(file, 'hi');
+
+ const res = await callReadText('u3', { path: file });
+ expect(res.ok).toBe(false);
+ expect(res.error).toMatch(/outside/);
+ });
+
+ it('rejects a path outside the workspace AND outside the attachment dir', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const dir = path.join(tmpDir, 'ws');
+ fs.mkdirSync(dir, { recursive: true });
+ ws.setWorkspacePath('u4', dir);
+ const outside = path.join(tmpDir, 'elsewhere.txt');
+ fs.writeFileSync(outside, 'leak me');
+
+ const res = await callReadText('u4', { path: outside, cid: 'conv-aaa' });
+ expect(res.ok).toBe(false);
+ expect(res.error).toMatch(/outside/);
+ });
+
+ it('rejects a missing path argument', async () => {
+ const res = await callReadText('u5', {});
+ expect(res.ok).toBe(false);
+ expect(res.error).toMatch(/missing path/);
+ });
+});
+
+describe('produced.readText › size cap', () => {
+ it('rejects files over the 2 MB cap with too_large + size + cap', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const dir = path.join(tmpDir, 'ws');
+ fs.mkdirSync(dir, { recursive: true });
+ ws.setWorkspacePath('u6', dir);
+ const file = path.join(dir, 'big.md');
+ fs.writeFileSync(file, Buffer.alloc(2 * 1024 * 1024 + 1));
+
+ const res = await callReadText('u6', { path: file });
+ expect(res.ok).toBe(false);
+ expect(res.error).toBe('too_large');
+ expect(res.size).toBe(2 * 1024 * 1024 + 1);
+ expect(res.cap).toBe(2 * 1024 * 1024);
+ });
+
+ it('accepts files exactly at the cap boundary', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const dir = path.join(tmpDir, 'ws');
+ fs.mkdirSync(dir, { recursive: true });
+ ws.setWorkspacePath('u7', dir);
+ const file = path.join(dir, 'edge.md');
+ fs.writeFileSync(file, Buffer.alloc(2 * 1024 * 1024));
+
+ const res = await callReadText('u7', { path: file });
+ expect(res.ok).toBe(true);
+ });
+});
+
+describe('produced.readText › content', () => {
+ it('strips a leading UTF-8 BOM so it doesn\'t render as an invisible char', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const dir = path.join(tmpDir, 'ws');
+ fs.mkdirSync(dir, { recursive: true });
+ ws.setWorkspacePath('u8', dir);
+ const file = path.join(dir, 'bom.md');
+ //  prepended to typical content.
+ fs.writeFileSync(file, '# Title\n');
+
+ const res = await callReadText('u8', { path: file });
+ expect(res.ok).toBe(true);
+ expect(res.text?.charCodeAt(0)).not.toBe(0xFEFF);
+ expect(res.text).toBe('# Title\n');
+ });
+
+ it('returns not_found for a directory path even inside the workspace', async () => {
+ const ws = await import('../../../src/main/features/user_workspace');
+ const dir = path.join(tmpDir, 'ws');
+ fs.mkdirSync(dir, { recursive: true });
+ ws.setWorkspacePath('u9', dir);
+ const sub = path.join(dir, 'sub');
+ fs.mkdirSync(sub);
+
+ const res = await callReadText('u9', { path: sub });
+ expect(res.ok).toBe(false);
+ expect(res.error).toBe('not_found');
+ });
+});
diff --git a/test/main/model/event-mapper.test.ts b/test/main/model/event-mapper.test.ts
index 438aa821..bb60de6f 100644
--- a/test/main/model/event-mapper.test.ts
+++ b/test/main/model/event-mapper.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
mapCoreAgentEvents,
friendlyRetryReason,
+ extractPersistedOutputPath,
} from '../../../src/main/model/core-agent/event-mapper';
type AgentRunEvent =
@@ -106,6 +107,64 @@ describe('event-mapper › tool_start / tool_end emit a single structured event'
expect(endEvent.event.data.isError).toBe(true);
expect(endEvent.event.data.result_preview).toContain('exit 1');
});
+
+ it('tool_end with small raw result → end event carries `output` (in-memory expand path)', async () => {
+ const body = 'line A\nline B\nline C';
+ const out = await collect([
+ { type: 'tool_start', name: 'read_file', id: 'c1', input: { path: 'x.md' } },
+ { type: 'tool_end', name: 'read_file', id: 'c1', result: body },
+ { type: 'done', result: { text: '', meta: { error: null } } },
+ ]);
+ const endEvent = out.find((e) => e.type === 'event' && e.event?.data?.phase === 'end');
+ expect(endEvent.event.data.output).toBe(body);
+ expect(endEvent.event.data.result_path).toBeUndefined();
+ });
+
+ it('tool_end with spilled <persisted-output> result → end event carries `result_path`', async () => {
+ // tool-result-cap.ts rewrites oversized tool results into this
+ // marker shape; the model + the event mapper both consume it. The
+ // renderer's click-to-expand uses `result_path` to IPC-read the
+ // full body off disk.
+ const marker =
+ `<persisted-output tool="bash" size="71234" path="/Users/x/.orkas/data/u1/local/tool-results/u1-conv-cid/bash.abc123.txt">\n` +
+ `first 2000 chars …\n\n... [69234 chars omitted] ...\n\nlast 500 chars\n` +
+ `[Full content saved to: /Users/x/.orkas/data/u1/local/tool-results/u1-conv-cid/bash.abc123.txt. Use read_file(path) to retrieve verbatim.]\n` +
+ `</persisted-output>`;
+ const out = await collect([
+ { type: 'tool_start', name: 'bash', id: 'c2', input: { command: 'curl big' } },
+ { type: 'tool_end', name: 'bash', id: 'c2', result: marker },
+ { type: 'done', result: { text: '', meta: { error: null } } },
+ ]);
+ const endEvent = out.find((e) => e.type === 'event' && e.event?.data?.phase === 'end');
+ expect(endEvent.event.data.result_path)
+ .toBe('/Users/x/.orkas/data/u1/local/tool-results/u1-conv-cid/bash.abc123.txt');
+ expect(endEvent.event.data.result_size).toBe(71234);
+ // When spilled, we do NOT also stuff `output` — the renderer's
+ // click handler exclusively goes through the IPC path. Avoids
+ // duplicating the (potentially large) marker text on the wire.
+ expect(endEvent.event.data.output).toBeUndefined();
+ });
+});
+
+describe('event-mapper › extractPersistedOutputPath', () => {
+ it('pulls path + size from a tool-result-cap marker', () => {
+ const r = extractPersistedOutputPath(
+ '<persisted-output tool="bash" size="123" path="/a/b/c.txt">\npreview\n</persisted-output>'
+ );
+ expect(r).toEqual({ path: '/a/b/c.txt', size: 123 });
+ });
+
+ it('returns null when the result is not a marker (small tool output)', () => {
+ expect(extractPersistedOutputPath('plain bash output')).toBeNull();
+ expect(extractPersistedOutputPath('')).toBeNull();
+ expect(extractPersistedOutputPath(null as unknown as string)).toBeNull();
+ });
+
+ it('returns null for malformed markers (defensive parse)', () => {
+ // Missing size attr — we require BOTH to parse, otherwise the
+ // renderer's expand IPC would have no `size` to report.
+ expect(extractPersistedOutputPath('<persisted-output path="/a/b.txt">x</persisted-output>')).toBeNull();
+ });
});
describe('event-mapper › friendlyRetryReason', () => {
diff --git a/test/main/util/tool-result-cap.test.ts b/test/main/util/tool-result-cap.test.ts
index baa699f8..b5b41ede 100644
--- a/test/main/util/tool-result-cap.test.ts
+++ b/test/main/util/tool-result-cap.test.ts
@@ -8,6 +8,7 @@ import {
persistToolResult,
buildPersistedOutputMarker,
sweepToolResults,
+ maybeSpillToolResult,
MAX_RESULT_CHARS_BY_TOOL,
DEFAULT_MAX_RESULT_CHARS,
PERSIST_THRESHOLD,
@@ -215,3 +216,61 @@ describe('tool-result-cap › persistToolResult', () => {
expect(fs.readFileSync(b, 'utf8')).toBe('content B');
});
});
+
+describe('tool-result-cap › maybeSpillToolResult (CLI side)', () => {
+ let dir: string;
+ beforeEach(() => { dir = makeTmpDir(); });
+ afterEach(() => cleanup(dir));
+
+ it('passes through unchanged when under the persist threshold', () => {
+ const r = maybeSpillToolResult({
+ toolResultsDir: dir,
+ toolName: 'bash',
+ callId: 'c1',
+ output: 'small output',
+ });
+ expect(r.output).toBe('small output');
+ expect(r.outputPath).toBeUndefined();
+ // Did NOT create the directory — under-threshold means no IO.
+ expect(fs.existsSync(path.join(dir, 'bash.txt'))).toBe(false);
+ });
+
+ it('spills to disk and returns marker + path when above threshold', () => {
+ const big = 'X'.repeat(PERSIST_THRESHOLD + 100);
+ const r = maybeSpillToolResult({
+ toolResultsDir: dir,
+ toolName: 'bash',
+ callId: 'c1',
+ output: big,
+ });
+ expect(r.outputPath).toBeTruthy();
+ expect(r.outputPath!.startsWith(dir)).toBe(true);
+ expect(fs.existsSync(r.outputPath!)).toBe(true);
+ expect(fs.readFileSync(r.outputPath!, 'utf8')).toBe(big);
+ // Marker preview wraps the path + sizes (same shape as in-process
+ // tool spill so the renderer can treat both identically).
+ expect(r.output).toMatch(/<persisted-output/);
+ expect(r.output).toContain(r.outputPath!);
+ expect(r.output.length).toBeLessThan(big.length);
+ });
+
+ it('returns the same shape as buildPersistedOutputMarker so renderers can normalize', () => {
+ const big = 'A'.repeat(PERSIST_THRESHOLD + 50);
+ const r = maybeSpillToolResult({
+ toolResultsDir: dir, toolName: 'bash', callId: 'c1', output: big,
+ });
+ const marker = buildPersistedOutputMarker(r.outputPath!, 'bash', big);
+ // Marker text differs only by the path (which we just substituted),
+ // so the prefix must match.
+ expect(r.output.startsWith('<persisted-output')).toBe(true);
+ expect(marker.startsWith('<persisted-output')).toBe(true);
+ });
+
+ it('handles empty output without touching disk', () => {
+ const r = maybeSpillToolResult({
+ toolResultsDir: dir, toolName: 'bash', callId: 'c1', output: '',
+ });
+ expect(r.output).toBe('');
+ expect(r.outputPath).toBeUndefined();
+ });
+});
diff --git a/test/renderer/chat-file-viewer.test.ts b/test/renderer/chat-file-viewer.test.ts
new file mode 100644
index 00000000..2ac5256b
--- /dev/null
+++ b/test/renderer/chat-file-viewer.test.ts
@@ -0,0 +1,104 @@
+// Lock in the kind-classifier behaviour of chat-file-viewer.js. The viewer
+// dispatches by `_kindOf(name)` — every misclassification surfaces as
+// "I clicked a .md but it tried to load in an iframe" or vice versa, which
+// is hard to spot in code review. This is the multi-branch decision
+// function category from PC/CLAUDE.md §9.
+
+import { describe, it, expect } from 'vitest';
+// eslint-disable-next-line @typescript-eslint/no-var-requires
+const viewer = require('../../src/renderer/modules/chat-file-viewer.js');
+const { _kindOf, _extOf, _chatMediaLocalUrl } = viewer as {
+ _kindOf: (name: string) => string;
+ _extOf: (name: string) => string;
+ _chatMediaLocalUrl: (abs: string) => string;
+};
+
+describe('chat-file-viewer › _kindOf', () => {
+ // Set A — known kinds. One representative per ext set; the lists in the
+ // module are the contract, so coverage of one ext per kind is enough
+ // (the Set membership check makes per-ext coverage redundant).
+ it.each([
+ ['photo.png', 'image'],
+ ['art.jpg', 'image'],
+ ['art.jpeg', 'image'],
+ ['art.webp', 'image'],
+ ['art.gif', 'image'],
+ ['report.pdf', 'pdf'],
+ ['page.html', 'html'],
+ ['old.htm', 'html'],
+ ['note.md', 'markdown'],
+ ['old.markdown', 'markdown'],
+ ['plain.txt', 'text'],
+ ['data.json', 'text'],
+ ['table.csv', 'text'],
+ ['script.py', 'text'],
+ ['app.ts', 'text'],
+ ['style.css', 'text'],
+ ['log.log', 'text'],
+ ])('classifies "%s" as %s', (name, kind) => {
+ expect(_kindOf(name)).toBe(kind);
+ });
+
+ // Set B — unsupported / look-alike shapes. These specifically check
+ // that the classifier doesn't promote "looks like text" → text or
+ // "html-ish" → html when the actual ext doesn't match.
+ it.each([
+ ['archive.zip', 'unsupported'],
+ ['workbook.xlsx', 'unsupported'],
+ ['slides.pptx', 'unsupported'],
+ ['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'],
+ ['file.UPPER', 'unsupported'],
+ ])('refuses "%s" → fallback dialog', (name, kind) => {
+ expect(_kindOf(name)).toBe(kind);
+ });
+
+ it('is case-insensitive on the extension portion', () => {
+ expect(_kindOf('REPORT.PDF')).toBe('pdf');
+ expect(_kindOf('Note.MD')).toBe('markdown');
+ expect(_kindOf('Page.Html')).toBe('html');
+ });
+
+ it('handles paths with directories — only the basename ext matters', () => {
+ expect(_kindOf('/Users/me/Documents/note.md')).toBe('markdown');
+ expect(_kindOf('C:\\\\work\\\\report.pdf')).toBe('pdf');
+ });
+});
+
+describe('chat-file-viewer › _extOf', () => {
+ it('returns lowercased trailing extension', () => {
+ expect(_extOf('note.MD')).toBe('.md');
+ expect(_extOf('report.pdf')).toBe('.pdf');
+ });
+ it('returns "" for names with no dot', () => {
+ expect(_extOf('README')).toBe('');
+ });
+ it('uses the LAST dot, not the first', () => {
+ expect(_extOf('a.b.tar.gz')).toBe('.gz');
+ });
+});
+
+describe('chat-file-viewer › _chatMediaLocalUrl', () => {
+ // The URL has to round-trip cleanly through new URL() + the main-side
+ // `_pathnameToAbsPath`, so it must encode spaces / non-ASCII but
+ // preserve `/` separators. encodeURI does both.
+ it('builds chat-media://local/ + path for a unix abs path', () => {
+ expect(_chatMediaLocalUrl('/Users/me/file.pdf')).toBe('chat-media://local/Users/me/file.pdf');
+ });
+ it('URL-encodes spaces in the path', () => {
+ expect(_chatMediaLocalUrl('/Users/me/has space.pdf')).toBe('chat-media://local/Users/me/has%20space.pdf');
+ });
+ it('preserves "/" separators (doesn\'t use encodeURIComponent)', () => {
+ const url = _chatMediaLocalUrl('/a/b/c/d.pdf');
+ expect(url).not.toContain('%2F');
+ expect(url).toContain('/a/b/c/d.pdf');
+ });
+ it('converts Windows-style "\\\\" to "/" so URL parsing stays well-formed', () => {
+ expect(_chatMediaLocalUrl('C:\\Users\\me\\file.pdf')).toBe('chat-media://local/C:/Users/me/file.pdf');
+ });
+});