Compare commits

...
91 Commits
Author SHA1 Message Date
paisley 32a4fbf525 release 0.5.4 (#1243) 2026-08-13 16:44:46 +08:00
paisley db82834c1c fix(channels): repair Windows plugin peer links and restart Gateway when link repair fails (#1242) 2026-08-13 16:34:07 +08:00
ZHUO Xu b780c46be3 fix: preserve ACP lineage in runs recovery across gateway restarts; avoid false gateway disconnect status (#1240) 2026-08-13 10:18:33 +08:00
paisley b99b136c2a fix(channels): avoid duplicate gateway restart on plugin save (#1239) 2026-08-12 18:27:02 +08:00
paisley d4060c6dcc docs: align Gateway heartbeat recovery threshold to four misses (#1238) 2026-08-12 15:06:34 +08:00
paisley df53de94df chore: lower gateway heartbeat restart threshold to 4 consecutive misses (#1237) 2026-08-12 14:14:54 +08:00
paisley d5168842de upgrade openclaw to 7.1-2 (#1236) 2026-08-12 11:53:53 +08:00
paisley 68705d96de chore: disable internal control-plane and goal tools by default (#1235) 2026-08-11 17:59:26 +08:00
paisley d4c8ae5f77 fix(channels): restore supported channel connectivity (#1232) 2026-08-11 15:40:48 +08:00
ZHUO Xu e23d3e1723 fix: pass Gateway token to ACP child directly instead of reading from openclaw.json; make e2e tests faster; restructure docs (#1230) 2026-08-10 13:30:50 +08:00
paisley 0909120b03 fix(gateway): restart after 10 missed heartbeats (#1231) 2026-08-07 17:44:53 +08:00
paisley 46ff98c219 release 0.5.3 (#1229) 2026-08-06 11:10:16 +08:00
paisley 813746f5cc fix(gateway): make heartbeat observability-only (#1227) 2026-08-06 10:43:44 +08:00
ZHUO Xu c4346a4b02 fix: preserve generated images during pending tasks and refactor image part styles (#1228) 2026-08-06 10:13:28 +08:00
paisley a9088496f5 feat: disable web search in ClawX (#1226) 2026-08-05 18:20:44 +08:00
paisley 1875dac040 chore(chat): simplify composer gateway status and toolbar agent label (#1225) 2026-08-05 17:16:45 +08:00
ZHUO Xu 3f2cd9345f refactor: migrate to Streamdown and restore GPU rendering for performance, reduce Gateway restarts via optimized OpenClaw config delivery (#1224) 2026-08-05 10:25:17 +08:00
HazeandCursor bbbf6d5bb8 fix(cron): keep scheduled task message editable after inserting a skill (#1223)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 14:48:59 +08:00
paisley 6dd39e8f7c fix(cron): show full run reply from transcript instead of truncated summary (#1222) 2026-08-04 14:38:51 +08:00
paisley d5ac6ca5e5 chore: Remove ClawX Dreams integration while leaving OpenClaw memory-core config unchanged. (#1221) 2026-08-04 13:36:33 +08:00
paisley cdf75da7ce fix provider validation to use configured model (#1220) 2026-08-04 11:14:47 +08:00
paisley 8508c0cd8c fix stable turn duration across conversation switches (#1219) 2026-08-03 17:56:14 +08:00
paisley 164489da97 fix(chat): display OpenClaw transcript attachments (#1218) 2026-08-03 17:12:24 +08:00
paisley f7e025cb20 feat(chat): make question directory float over conversation (#1217) 2026-08-03 15:28:39 +08:00
paisley b564d4a57a fix(attachments): keep directory attachments available for system open (#1216) 2026-08-03 14:40:32 +08:00
paisley 0f152e022b chore:remove chat refresh button (#1215) 2026-08-03 11:59:27 +08:00
Haze 8335ca329c feat: Enhance model context window handling and improve inference logic for custom models (#1214) 2026-08-03 11:38:39 +08:00
paisley d0dfe84463 fix(chat): fix multiline composer layout and skill caret alignment (#1213) 2026-08-03 11:09:58 +08:00
paisley 2679dc7aee release v0.5.2 (#1206) 2026-07-31 11:14:19 +08:00
paisley 76f22a0e8e feat: Enable FTS-only memory search when no OpenAI embedding key is configured. (#1205) 2026-07-30 18:40:45 +08:00
paisley 9591deba7e feat: improve file previews and link opening behavior (#1204) 2026-07-30 11:20:09 +08:00
paisley 04f57b286e feat: update OpenAI OAuth default model to gpt-5.6-sol (#1203) 2026-07-29 16:10:55 +08:00
paisley 2a4426d4ff feat: Improve chat title and copy button layout on Windows (#1202) 2026-07-29 15:48:19 +08:00
paisley 82b7f445af fix: use short folder names for imported workspaces (#1201) 2026-07-29 13:43:04 +08:00
paisley 230ac15cbf fix: restore ACP slash command replies such as /status (#1200) 2026-07-28 18:36:14 +08:00
paisley 3a241cf09f fix: prevent plugin cleanup from deleting bundled OpenClaw runtime (#1197) 2026-07-28 17:30:12 +08:00
paisley 863f9caf0f fix markdown display (#1199) 2026-07-28 16:46:13 +08:00
paisley 017749b169 feat: Collapse ACP tool calls into a grouped summary after turn completes (#1198) 2026-07-28 13:13:32 +08:00
paisley 4318fdc3f1 Revert "[codex] Add runtime abstraction and cc-connect provider" (#1196) 2026-07-27 17:28:33 +08:00
Lingxuan Zuo 960f6b298d [codex] Add runtime abstraction and cc-connect provider (#1103) 2026-07-26 23:43:55 +08:00
paisley 8034c5ad31 fix: harden OpenClaw upgrade snapshot backup scope and cleanup (#1194) 2026-07-24 11:56:21 +08:00
paisley 1f26cd205d feat:upgrade openclaw to 7.1 (#1193) 2026-07-24 10:38:57 +08:00
paisley 9cdd501a80 release 0.5.1 (#1192) 2026-07-23 14:10:40 +08:00
paisley 26d20fdb35 fix: disable model ID editing for existing providers (#1191) 2026-07-23 13:43:53 +08:00
paisley 378e01ee1e feat(gateway): improve startup timing diagnostics (#1190) 2026-07-23 11:06:29 +08:00
ZHUO Xu 7cb6eb240c feat: enhance session status, file previews, open-with feature, web browser, and turn timing (#1189) 2026-07-23 11:06:01 +08:00
paisley cd0d95ad69 fix chat workspace menu and session fallback titles (#1187) 2026-07-22 15:20:52 +08:00
paisley d501bad05d fix(chat): inherit workspace when creating a new chat (#1186) 2026-07-22 14:03:02 +08:00
paisley 5d0099abaa feat: improve unavailable workspace recovery and cleanup (#1183) 2026-07-20 18:27:09 +08:00
paisley 951ca13db8 fix: keep @agent first send on target workspace Prevent reactive ACP loads from cancelling new-agent prompts by binding the target workspace on session switch and creating the target main session when missing. (#1184) 2026-07-20 17:54:31 +08:00
paisley c96b2336c6 fix(chat): preserve image generation thinking state across sessions (#1180) 2026-07-20 10:50:41 +08:00
paisley a42a7e4256 feat: support renaming imported workspaces (#1179) 2026-07-17 16:25:37 +08:00
paisley ff61f5dd72 fix: prevent model reload from interrupting ACP startup (#1178) 2026-07-17 15:16:44 +08:00
paisley 91836cd6bc fix chat follow-up auto-scroll (#1177) 2026-07-16 16:30:24 +08:00
paisley fb19cc61c5 fix markdown code highlighting (#1176) 2026-07-16 15:48:52 +08:00
paisley 0fa869f1cc release v0.5.0 (#1175) 2026-07-16 11:53:03 +08:00
paisley 33bcf654eb fix(chat): hide disabled workspace selector border (#1174) 2026-07-16 11:51:09 +08:00
Felix 7774d89c66 Revert "fix: raise default LLM idle timeout to 240 seconds to reduce false timeouts on slow providers" (#1172) 2026-07-16 11:33:04 +08:00
ZHUO Xu d741364c74 fix: resolve attachment unavailability, buffer unfinished streams, and show file paths in cards (#1171) 2026-07-16 10:10:50 +08:00
paisley 502d9d5367 fix: raise default LLM idle timeout to 240 seconds to reduce false timeouts on slow providers (#1170) 2026-07-15 18:58:43 +08:00
Haze 1e52b0048a refactor: update styling and remove unused status classes in AcpToolCallCard component (#1169) 2026-07-15 17:32:23 +08:00
fc87e00323 feat(providers): add Z.AI CN/Global with Coding Plan support (#1167)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Haze <hazeone@users.noreply.github.com>
2026-07-15 16:28:18 +08:00
greg dohertyandClaude Fable 5 a9d9376fe0 fix: preserve agent model fallbacks when switching models (#1160)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 16:14:49 +08:00
1a46e1f1d5 chore: update OpenRouter default model to openai/gpt-5.6-sol (#1168)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Haze <hazeone@users.noreply.github.com>
2026-07-15 16:04:34 +08:00
51655b91e1 chore: update Anthropic default model to Claude Opus 4.8 (#1166)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Haze <hazeone@users.noreply.github.com>
2026-07-15 15:12:19 +08:00
ZHUO Xu 702f03e055 fix: resolve a batch of problems after migrating to ACP (#1165) 2026-07-15 14:36:17 +08:00
Felix c7d4345b6e Revert "feat(auth): deny subagent tools for ClawX desktop" (#1164) 2026-07-15 13:21:36 +08:00
paisley b598e2482d fix: hide empty new chats from sidebar until first message (#1162) 2026-07-14 18:17:32 +08:00
paisley 3d134a563a fix: remove stale OAuth models from chat picker (#1161) 2026-07-14 17:04:45 +08:00
ZHUO Xuandpaisley ff9024fb5d feat: Use ACP to refactor chat UI and session management; add workspace feature (#1158)
Co-authored-by: paisley <8197966+su8su@users.noreply.github.com>
2026-07-13 11:03:37 +08:00
paisley 4a74b22796 release v0.4.16 (#1155) 2026-07-10 18:26:47 +08:00
paisley bcec47f600 fix: set default compaction reserveTokensFloor to 50000 (#1154) 2026-07-10 18:04:59 +08:00
paisley d7671a42e6 release 0.4.15 (#1151) 2026-07-07 18:56:31 +08:00
paisley f44c2250fb chore: remove unused preinstalled skills (#1150) 2026-07-07 18:09:40 +08:00
paisley d6c770e4a5 chore: bump version to 0.4.14 (#1149) 2026-07-07 17:26:49 +08:00
paisley e84f13c876 fix: seed memorySearch disabled when no user embedding config (#1148) 2026-07-07 16:41:00 +08:00
Felix a0509b9b54 feat(auth): deny subagent tools for ClawX desktop (#1147) 2026-07-07 15:44:45 +08:00
paisley e09dd289db fix: add contextWindow defaults and compaction safeguard for custom providers (#1146) 2026-07-07 15:25:46 +08:00
Felix 2a1e2adde3 docs: surface uv guidance in ClawX agents context (#1142) 2026-07-03 17:17:40 +08:00
paisley 6ea53bdeb1 chore: bump version to 0.4.13 (#1141) 2026-07-02 16:56:46 +08:00
paisley f3689894bf fix: persist trusted plugin install records to SQLite for packaged WhatsApp (#1140) 2026-07-02 11:25:09 +08:00
paisley 33694efe84 Fix whatsapp login (#1139) 2026-07-01 18:54:34 +08:00
paisley 22af7468d7 Upgrade openclaw to 6.10 (#1138) 2026-06-30 18:29:35 +08:00
Felix cb8c3cfd02 chore: bump version to 0.4.12 (#1135) 2026-06-26 13:48:35 +08:00
Felix e42307cbd3 feature: support multi-model provider accounts (#1133) 2026-06-25 14:07:52 +08:00
Felix ffe50ff8a5 fix: deny built-in skill workshop tool (#1131) 2026-06-23 13:30:10 +08:00
Felix d223af5747 chore: bump bundled Windows node to 22.19.0 (#1129) 2026-06-22 12:33:11 +08:00
Haze b0db926874 release: v0.4.11 (#1126) 2026-06-17 10:13:53 +08:00
Haze 05ea50a834 opt(cron): cron job status (#1125) 2026-06-15 19:46:40 +08:00
Haze 808f4a840d feat(cron): opt cron task job (#1124) 2026-06-15 17:54:06 +08:00
ZHUO Xu d9ffbca856 refactor: chat markdown list and heading styles (#1121) 2026-06-15 16:55:27 +08:00
570 changed files with 75650 additions and 34255 deletions
+38
View File
@@ -33,6 +33,41 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
# The runtime compatibility test executes Electron to assert its embedded
# Node and SQLite versions, so this job cannot rely on the package alone.
# Use the same extraction path as Electron E2E because install.js can
# leave a partially extracted dist directory on GitHub-hosted runners.
- name: Install Electron binary for runtime compatibility test
shell: bash
env:
force_no_cache: 'true'
run: |
set -euo pipefail
unset ELECTRON_SKIP_BINARY_DOWNLOAD
ELECTRON_DIR="$(node -p "require('path').dirname(require.resolve('electron/package.json'))")"
echo "Electron package dir: $ELECTRON_DIR"
rm -rf "$ELECTRON_DIR/dist" "$ELECTRON_DIR/path.txt"
mkdir -p "$ELECTRON_DIR/dist"
ZIP="$(cd "$ELECTRON_DIR" && node -e "
const { downloadArtifact } = require('@electron/get');
const { version } = require('./package.json');
downloadArtifact({ version, artifactName: 'electron', force: true })
.then((z) => { process.stdout.write(z); process.exit(0); })
.catch((e) => { console.error(e); process.exit(1); });
")"
ZIP_SIZE="$(stat -c%s "$ZIP")"
echo "Downloaded zip: $ZIP ($ZIP_SIZE bytes)"
unzip -oq "$ZIP" -d "$ELECTRON_DIR/dist"
echo "Extracted top-level entries: $(ls -1 "$ELECTRON_DIR/dist" | wc -l | tr -d ' ')"
if [ -f "$ELECTRON_DIR/dist/electron.d.ts" ]; then
mv "$ELECTRON_DIR/dist/electron.d.ts" "$ELECTRON_DIR/electron.d.ts"
fi
test -f "$ELECTRON_DIR/dist/electron"
chmod +x "$ELECTRON_DIR/dist/electron"
printf '%s' 'electron' > "$ELECTRON_DIR/path.txt"
- name: Generate extension bridge
run: pnpm run ext:bridge
@@ -82,6 +117,9 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Test Windows attachment open-with bridge
run: pnpm exec vitest run tests/unit/attachment-open-with.test.ts tests/unit/attachment-open-with-native.test.ts tests/unit/safe-fs.test.ts
- name: Generate extension bridge
run: pnpm run ext:bridge
+1
View File
@@ -23,6 +23,7 @@ jobs:
- windows-latest
env:
CI: 'true'
CLAWX_E2E_WORKERS: '2'
# Linux runners cannot use Electron's setuid chrome-sandbox; harmless on macOS/Windows.
ELECTRON_DISABLE_SANDBOX: '1'
+4
View File
@@ -84,3 +84,7 @@ playground/
# ClawX-biz bridge workspace artifacts
resources/enterprise-skills/
resources/openclaw-plugins/skillshub/
.opencode
.superpowers
.playwright-mcp
+3 -3
View File
@@ -2,6 +2,6 @@
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100
}
"trailingComma": "all",
"printWidth": 120
}
+5
View File
@@ -21,12 +21,16 @@ Standard dev commands are in `package.json` scripts and `README.md`. Key ones:
| Comms baseline refresh | `pnpm run comms:baseline` |
| Comms regression compare | `pnpm run comms:compare` |
| E2E tests (Playwright) | `pnpm run test:e2e` |
| Chat performance profiles | `pnpm run perf:chat` |
| Electron Main inspector | `pnpm run profile:main` |
| Build frontend only | `pnpm run build:vite` |
### Non-obvious caveats
- **pnpm version**: The exact pnpm version is pinned via `packageManager` in `package.json`. Use `corepack enable && corepack prepare` to activate the correct version before installing.
- **Electron on headless Linux**: The dbus errors (`Failed to connect to the bus`) are expected and harmless in a headless/cloud environment. The app still runs fine with `$DISPLAY` set (e.g., `:1` via Xvfb/VNC).
- **Performance profiling**: `pnpm run perf:chat` writes synthetic Renderer/Main CPU profiles and versioned metrics under ignored Playwright `test-results/`. For live Renderer CDP use `CLAWX_REMOTE_DEBUGGING_PORT=9223 pnpm dev`; for live Main inspection use `pnpm run profile:main` and port 9229.
- **E2E parallel isolation**: Functional Electron specs run concurrently with `CLAWX_E2E_WORKERS=2` by default. Keep tests parallel-safe and test-scoped; apply `E2E_EXCLUSIVE_TAG` from `tests/e2e/parallel-policy.ts` to tests that use the real clipboard or other OS-global state, and `E2E_PERFORMANCE_TAG` to host performance profiles. Extend `tests/unit/e2e-parallel-policy.test.ts` for recognizable new global APIs.
- **`pnpm run lint` race condition**: If `pnpm run uv:download` was recently run, ESLint may fail with `ENOENT: no such file or directory, scandir '/workspace/temp_uv_extract'` because the temp directory was created and removed during download. Simply re-run lint after the download script finishes.
- **Build scripts warning**: `pnpm install` may warn about ignored build scripts for `@discordjs/opus` and `koffi`. These are optional messaging-channel dependencies and the warnings are safe to ignore.
- **`pnpm run init`**: This is a convenience script that runs `pnpm install` followed by `pnpm run uv:download`. Either run `pnpm run init` or run the two steps separately.
@@ -48,3 +52,4 @@ Standard dev commands are in `package.json` scripts and `README.md`. Key ones:
- **Spec-driven harness rule**: AI Coding tasks that touch backend communication must start from a task spec under `harness/specs/tasks/` and reference `gateway-backend-communication` when the change involves renderer/Main/host-api/api-client/Gateway/OpenClaw runtime paths. Run `pnpm harness validate --spec <task-spec>` before implementation review, and `pnpm harness run --spec <task-spec>` or `--dry-run` when checking the selected validation flow.
- **Spec/rule growth rule**: When adding a new feature, user-visible OpenClaw scenario, or recurring AI Coding constraint, add or update the relevant harness scenario spec and rule spec in the same PR so future AI work can validate the behavior instead of relying on tribal knowledge.
- **Harness CI/local parity**: Run `pnpm run harness:ci` to exercise the same baseline harness checks used by GitHub Actions. Real task specs should be validated without `--no-diff`; `--no-diff` is only for structural checks of checked-in examples.
- **Harness reference docs**: Keep durable, non-executable architecture and compatibility details under `harness/reference/`. Link them from the relevant scenario, rule, and task specs, but do not pass reference documents to `harness validate` or `harness run`.
+99 -324
View File
@@ -10,8 +10,7 @@
</p>
<p align="center">
<a href="#機能">機能</a> •
<a href="#なぜclawxなのか">なぜClawXなのか</a> •
<a href="#clawxを選ぶ理由">ClawXを選ぶ理由</a> •
<a href="#はじめに">はじめに</a> •
<a href="#アーキテクチャ">アーキテクチャ</a> •
<a href="#開発">開発</a> •
@@ -37,127 +36,78 @@
## 概要
**ClawX**は、強力なAIエージェントと日常のユーザーとの間のギャップを埋めます。[OpenClaw](https://github.com/OpenClaw)をベースに構築されており、コマンドラインによるAIオーケストレーションを、アクセスしやすく美しいデスクトップ体験に変換します。ターミナルは不要です
**ClawX**は、強力なAIエージェントと日常のユーザーとの間のギャップを埋めます。[OpenClaw](https://github.com/OpenClaw)をベースに構築されており、コマンドラインによるAIオーケストレーションを、使いやすく美しいデスクトップ体験に変換します。ターミナルは必要ありません
ワークフローの自動化、AI搭載チャネルの管理、インテリジェントなタスクのスケジューリングなど、ClawXはAIエージェントを効果的に活用するために必要なインターフェースを提供します。
ClawXはベストプラクティスモデルプロバイダーが事前設定されており、Windowsおよび多言語設定をネイティブにサポートしています。もちろん、**設定 → 詳細設定 → 開発者モード**から高度な設定を微調整することもできます。
ClawXはベストプラクティスに基づくモデルプロバイダーがあらかじめ設定されており、Windows多言語設定をネイティブにサポートしています。高度な設定は **設定 → 詳細設定 → 開発者モード** から調整できます。
<p align="center"><strong style="font-size:1.1em; text-decoration: underline;">完全なエンタープライズ版、専用サービスサポート、または御社のビジネスシナリオに合わせた導入支援が必要な場合は、<a href="mailto:public@valuecell.ai">public@valuecell.ai</a> までお問い合わせください。</strong></p>
<p align="center"><strong style="font-size:1.1em; text-decoration: underline;">完全なエンタープライズ版、専用サービスサポート、またはビジネスシナリオに合わせた導入支援が必要な場合は、<a href="mailto:public@valuecell.ai">public@valuecell.ai</a> までお問い合わせください。</strong></p>
---
## スクリーンショット
<p align="center">
<img src="resources/screenshot/jp/chat.png" style="width: 100%; height: auto;">
</p>
<table>
<tr>
<td align="center"><img src="resources/screenshot/jp/chat.png" alt="Chat"><br><em>チャット</em></td>
<td align="center"><img src="resources/screenshot/jp/cron.png" alt="Cron"><br><em>スケジュールタスク</em></td>
</tr>
<tr>
<td align="center"><img src="resources/screenshot/jp/skills.png" alt="Skills"><br><em>スキル</em></td>
<td align="center"><img src="resources/screenshot/jp/channels.png" alt="Channels"><br><em>チャネル</em></td>
</tr>
<tr>
<td align="center"><img src="resources/screenshot/jp/models.png" alt="Models"><br><em>モデル</em></td>
<td align="center"><img src="resources/screenshot/jp/settings.png" alt="Settings"><br><em>設定</em></td>
</tr>
</table>
<p align="center">
<img src="resources/screenshot/jp/cron.png" style="width: 100%; height: auto;">
</p>
## ClawXを選ぶ理由
<p align="center">
<img src="resources/screenshot/jp/skills.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/jp/channels.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/jp/models.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/jp/settings.png" style="width: 100%; height: auto;">
</p>
---
## なぜClawXなのか
AIエージェントの構築にコマンドラインの習得は不要であるべきです。ClawXはシンプルな哲学のもとに設計されました:**強力な技術には、あなたの時間を尊重するインターフェースがふさわしい。**
AIエージェントの構築にコマンドラインの習得は不要であるべきです。ClawXはシンプルな哲学のもとに設計されました:**強力な技術には、あなたの時間を尊重するインターフェースがふさわしい。** ClawXは公式の **OpenClaw** コアを直接ベースに構築されています。別途インストールする必要はなく、ランタイムをアプリケーション内に組み込むことで、シームレスな「すべて込み」の体験を提供します。上流のOpenClawと緊密に連携し、公式の最新機能、安定性の改善、エコシステムとの互換性を利用できるようにしています。
| 課題 | ClawXのソリューション |
|------|----------------------|
| 複雑なCLIセットアップ | ワンクリックインストールとガイド付きセットアップウィザード |
| 設定ファイル | リアルタイムバリデーション付きのビジュアル設定 |
| プロセス管理 | ゲートウェイライフサイクルの自動管理 |
| アプリ更新 | 起動時に更新を確認し、ダウンロードインストール前に通知 |
| 複雑なCLIセットアップ | ガイド付きセットアップウィザードによるワンクリックインストール |
| 設定ファイル | リアルタイム検証付きのビジュアル設定 |
| プロセス管理 | Gatewayライフサイクルの自動管理 |
| アプリ更新 | 起動時に更新を確認し、ダウンロードまたはインストール前に通知 |
| 複数のAIプロバイダー | 統合プロバイダー設定パネル |
| スキル/プラグインのインストール | 組み込みのスキルマーケットプレイスと管理機能 |
| スキル/プラグインのインストール | オプションの拡張機能マーケットプレイスにも対応したローカル優先のスキル管理 |
### OpenClaw内蔵
### 機能
ClawXは公式の**OpenClaw**コアを直接ベースに構築されています。別途インストールを必要とせず、アプリケーション内にランタイムを組み込むことで、シームレスな「バッテリー同梱」体験を提供します。
- **🎯 ゼロ設定バリア**:直感的なグラフィカルインターフェースでセットアップを完了できます。ターミナルコマンド、YAMLファイル、環境変数の探索は不要です。
- **💬 インテリジェントチャットインターフェース**:複数セッションのコンテキストと履歴、シンタックスハイライト付きストリーミングMarkdown、CJK対応解析、テーブル、KaTeX数式、`@agent` による直接ルーティング、インライン `/skill` カード、ワークスペース優先のセッション、Markdown・`.docx``.pptx`・ローカルHTMLの読み取り専用プレビューに対応します。
- **📡 マルチチャネル管理**:複数アカウント、アカウント単位のAgent紐付け、既定アカウントの切り替え、Tencent公式個人WeChatチャネルプラグインを備えた独立したAIチャネルを設定・監視できます。
- **⏰ Cronベースの自動化**:繰り返しまたは1回限りのスケジュールを定義し、スケジュール済みプロンプトにスキルを挿入し、結果を外部チャネルへ配信できます。
- **🧩 拡張可能なスキルシステム**:Gatewayに依存せずスキルをローカルで管理できます。複数のOpenClawソースからスキルを検出し、`pdf``xlsx``docx``pptx` の文書処理スキルも利用できます。
- **🔐 セキュアなプロバイダー統合**OpenAI、Anthropic、Z.AI / GLMなどに接続し、認証情報をOSのネイティブキーチェーンに安全に保存できます。OAuth、カスタムプロバイダー、画像生成エンドポイント、互換性フォールバックにも対応します。
- **🌙 アダプティブテーマ**:ライト、ダーク、システム同期テーマを選択できます。
- **🚀 自動起動設定**:**設定 → 一般** で **システム起動時に自動起動** を有効にできます。
- **🔔 更新通知**:起動時に新しいバージョンを確認し、ダウンロードまたはインストールするかを選択できます。
私たちはアップストリームのOpenClawプロジェクトとの厳密な整合性を維持することにコミットしており、公式リリースが提供する最新の機能、安定性の改善、エコシステムの互換性に常にアクセスできることを保証します
> 機能の詳細は [docs/ja-JP/features.md](docs/ja-JP/features.md) を参照してください
開発者モードを有効にすると、サイドバーにはネイティブの Dreams ページも表示され、ClawX 内で OpenClaw の記憶レビュー、夢日記、基本メンテナンス操作を扱えます。詳細な診断が必要な場合は、そのページから完全版の OpenClaw Dreams UI も開けます。
### 主なユースケース
---
## 機能
### 🎯 ゼロ設定バリア
インストールから最初のAIインタラクションまで、すべてのセットアップを直感的なグラフィカルインターフェースで完了できます。ターミナルコマンド不要、YAMLファイル不要、環境変数の探索も不要です。
### 💬 インテリジェントチャットインターフェース
モダンなチャット体験を通じてAIエージェントとコミュニケーションできます。複数の会話コンテキスト、メッセージ履歴、Markdownによるリッチコンテンツレンダリング(GitHub 風テーブルや KaTeX による LaTeX 数式 `$インライン$``$$ブロック$$``\(インライン\)``\[ブロック\]` を含む)に加え、マルチエージェント構成ではメイン入力欄の `@agent` から対象エージェントへ直接ルーティングできます。
コンポーザーから挿入した Skill は `/skill-name` 形式のチップとして表示され、チップをクリックすると右側のプレビュー側欄でその Skill の `SKILL.md` を開けます。
`@agent` で別のエージェントを選ぶと、ClawX はデフォルトエージェントを経由せず、そのエージェント自身の会話コンテキストへ直接切り替えます。各エージェントのワークスペースは既定で分離されていますが、より強い実行時分離は OpenClaw の sandbox 設定に依存します。
各 Agent は `provider/model` の実行時設定を個別に上書きできます。上書きしていない Agent は引き続きグローバルの既定モデルを継承します。
### 📡 マルチチャネル管理
複数のAIチャネルを同時に設定・監視できます。各チャネルは独立して動作するため、異なるタスクに特化したエージェントを実行できます。
現在は各チャンネルで複数アカウントを扱え、Channels ページでアカウントの Agent 紐付けやデフォルトアカウント切替を直接管理できます。
カスタムのチャンネルアカウント ID には、ルーティング不一致を防ぐため OpenClaw 互換の正規形式(`[a-z0-9_-]`、英小文字、最大 64 文字、先頭は英小文字または数字)を必須にしています。
ClawX には Tencent 公式の個人 WeChat チャンネルプラグインも同梱されており、Channels ページからアプリ内 QR フローで直接 WeChat を連携できます。
### ⏰ Cronベースの自動化
AIタスクを自動的に実行するようスケジュール設定できます。トリガーを定義し、間隔を設定することで、手動介入なしにAIエージェントを24時間稼働させることができます。
定期タスク画面では外部配信を「送信アカウント」と「受信先ターゲット」の 2 段階セレクターで設定できるようになりました。対応チャネルでは、受信先候補をチャネルのディレクトリ機能や既知セッション履歴から自動検出するため、`jobs.json` を手で編集する必要はありません。
### 🧩 拡張可能なスキルシステム
事前構築されたスキルでAIエージェントを拡張できます。統合 Skills ページはローカル優先で、管理ディレクトリや workspace のスキルをスキャンし、Gateway に依存せず有効/無効を切り替えられます。エンタープライズ拡張がある場合は、その拡張が提供する marketplace も表示できます。
ClawX はドキュメント処理スキル(`pdf``xlsx``docx``pptx`)もフル内容で同梱し、起動時に管理スキルディレクトリ(既定 `~/.openclaw/skills`)へ自動配備し、初回インストール時に既定で有効化します。追加の同梱スキル(`find-skills``self-improving-agent``tavily-search`)も既定で有効化されますが、必要な API キーが未設定の場合は OpenClaw が実行時に設定エラーを表示します。
Skills ページでは OpenClaw の複数ソース(管理ディレクトリ、workspace、追加スキルディレクトリ)から検出されたスキルを表示でき、各スキルの実際のパスを確認して実フォルダを直接開けます。OpenClaw 同梱の bundled skill については、コミュニティ版ではパッケージにも表示にも `skill-creator` のみを残し、dev 起動時と packaged 起動時の両方で他の bundled skill を物理的に削除します。さらに、削除済み bundled skill の古い `openclaw.json` エントリも一緒に掃除します。
主な検索スキルで必要な環境変数:
- `TAVILY_API_KEY`: `tavily-search` 用(上流ランタイムで OAuth 対応の場合あり)
### 🔐 セキュアなプロバイダー統合
複数のAIプロバイダー(OpenAI、Anthropicなど)に接続でき、資格情報はシステムのネイティブキーチェーンに安全に保存されます。OpenAI は API キーとブラウザ OAuth(Codex サブスクリプション)の両方に対応しています。
開発者モードでは、専用の Image Generation ページで、独立した OpenAI 互換の画像生成エンドポイント(Base URL、API キー、`gpt-image-2` などのモデル名)を設定でき、画像生成だけ専用の `/v1/images/generations` サービスを使い、チャットは通常の OpenAI Provider のまま継続できます。
OpenAI-compatible ゲートウェイを **Custom プロバイダー** で使う場合、**設定 → AI Providers → Provider 編集** でカスタム `User-Agent` を設定でき、互換性が必要なエンドポイントで有効です。
プロバイダーの編集や切り替え時、ClawX は `input: ["text", "image"]` など既存のモデル単位の能力メタデータを保持します。新しく選択した Custom プロバイダーのモデルには OpenClaw onboarding と同等の画像入力推論を適用し、不明なモデルはテキスト専用として扱います。
互換ゲートウェイで `/models` が認証以外の理由で使えない場合、ClawX は API キー検証時に軽量な `/chat/completions` または `/responses` プローブへ自動フォールバックします。
### 🌙 アダプティブテーマ
ライトモード、ダークモード、またはシステム同期テーマ。ClawXはあなたの好みに自動的に適応します。
### 🚀 自動起動設定
**設定 → 通用** から **システム起動時に自動起動** を有効化すると、ログイン後に ClawX が自動的に起動します。
### 🔔 更新通知
ClawX は起動時に新しいバージョンを自動確認できます。更新が見つかるとアプリ内通知を表示し、ダウンロードやインストールはユーザーが選択した後にのみ実行されます。
---
- **🤖 パーソナルAIアシスタント**:質問への回答、メールの下書き、ドキュメントの要約、日常タスクの支援を行う汎用AIエージェントを、クリーンなデスクトップインターフェースから設定できます。
- **📊 自動モニタリング**:ニュースフィード、価格、特定のイベントを監視するスケジュールエージェントを設定し、結果を希望する通知チャネルへ届けられます。
- **💻 開発者の生産性向上**:AIを開発ワークフローに統合し、コードレビュー、ドキュメント生成、繰り返しのコーディング作業を行えます。
- **🔄 ワークフロー自動化**:複数のスキルをビジュアルな自動化パイプラインに組み合わせ、データ処理、コンテンツ変換、アクションの実行を行えます。
## はじめに
### システム要件
- **オペレーティングシステム**: macOS 11以上、Windows 10以上、またはLinuxUbuntu 20.04以上)
- **メモリ**: 最低4GB RAM8GB推奨)
- **ストレージ**: 1GBの空きディスク容量
- **オペレーティングシステム**macOS 11以上、Windows 10以上、またはLinuxUbuntu 20.04以上)
- **メモリ**最低4GB RAM8GB推奨)
- **ストレージ**1GBの空きディスク容量
### インストール
#### ビルド済みリリース(推奨)
[Releases](https://github.com/ValueCell-ai/ClawX/releases)ページから、お使いのプラットフォーム向けの最新リリースをダウンロードしてください。
[Releases](https://github.com/ValueCell-ai/ClawX/releases) ページから、お使いのプラットフォーム向けの最新リリースをダウンロードしてください。
#### ソースからビルド
@@ -166,301 +116,126 @@ ClawX は起動時に新しいバージョンを自動確認できます。更
git clone https://github.com/ValueCell-ai/ClawX.git
cd ClawX
# プロジェクト初期化
# プロジェクト初期化
pnpm run init
# 開発モードで起動
pnpm dev
```
### 初回起動
ClawXを初めて起動すると、**セットアップウィザード**が以下の手順をガイドします
ClawXを初めて起動すると、**セットアップウィザード**がの手順を案内します
1. **言語と地域** 使用する言語・地域の設定
2. **AIプロバイダー** APIキーまたは OAuthブラウザ/デバイスログイン対応プロバイダーで追加
3. **スキルバンドル** 一般的なユースケース向けの事前設定スキルを選択
4. **検証** メインインターフェースに入る前に設定をテスト
1. **言語と地域**使用するロケールを設定
2. **AIプロバイダー**ブラウザまたはデバイスログイン対応したプロバイダーでは、APIキーまたはOAuthで追加
3. **スキルバンドル**一般的なユースケース向けの事前設定スキルを選択
4. **検証**メインインターフェースに入る前に設定をテスト
サポート対象のシステム言語がある場合、ウィザードはその言語を初期選択し、対応場合は英語にフォールバックします。
サポートされている場合、ウィザードはシステム言語を初期選択し、対応していない場合は英語にフォールバックします。
> Web検索について:ClawXはAgentとGatewayの両方のポリシーレイヤーで、OpenClawの汎用 `web_search` ツールを無効にします。Moonshot(Kimi)検索も対象です。管理対象のブラウザ自動化と `web_fetch` は引き続き利用できます。
>
> 内部ツールについて:ClawXは両方のポリシーレイヤーで、Agentに対して `gateway`、`nodes`、`create_goal`、`get_goal`、`update_goal` も無効にします。ClawXアプリケーション自身のGateway RPCに加え、メッセージング、セッションオーケストレーション、Agent検出ツールは引き続き利用できます。
### プロキシ設定
ClawXには、Electron、OpenClaw Gateway、またはTelegramなどのチャネルがローカルプロキシクライアントを介してインターネットにアクセスする必要がある環境向け、組み込みプロキシ設定が含まれています。
ClawXには、Electron、OpenClaw Gateway、Telegramなどのチャネルがローカルプロキシクライアント経由でインターネットにアクセスする必要がある環境向け、組み込みプロキシ設定があります。
**設定 → ゲートウェイ → プロキシ**を開いて以下を設定します:
**設定 → Gateway → プロキシ**を開き、既定のプロキシ、バイパスルール、開発者モードでのHTTP・HTTPS・`ALL_PROXY` / SOCKSの上書きを設定します。ローカル設定の例は `http://127.0.0.1:7890` です。
- **プロキシサーバー**: すべてのリクエストのデフォルトプロキシ
- **バイパスルール**: 直接接続すべきホスト(セミコロン、カンマ、または改行で区切る)
- **開発者モード**では、オプションで以下をオーバーライドできます:
- **HTTP プロキシ**
- **HTTPS プロキシ**
- **ALL_PROXY / SOCKS**
推奨されるローカル設定例:
```text
プロキシサーバー: http://127.0.0.1:7890
```
注意事項:
- `host:port`のみの値はHTTPとして扱われます。
- 高度なプロキシフィールドが空の場合、ClawXは`プロキシサーバー`にフォールバックします。
- プロキシ設定を保存すると、Electronのネットワーク設定が即座に再適用され、ゲートウェイが自動的に再起動されます。
- ClawXはTelegramが有効な場合、プロキシをOpenClawのTelegramチャネル設定にも同期します。
- ClawXのプロキシが無効な状態では、Gatewayの通常再起動時に既存のTelegramチャネルプロキシ設定を保持します。
- OpenClaw設定のTelegramプロキシを明示的に消したい場合は、プロキシ無効の状態で一度「保存」を実行してください。
- **設定 → 詳細 → 開発者** では **OpenClaw Doctor** を実行でき、`openclaw doctor --json` の診断出力をアプリ内で確認できます。
- Windows のパッケージ版では、同梱された `openclaw` CLI/TUI は端末入力を安定させるため、同梱の `node.exe` エントリーポイント経由で実行されます。
---
> プロキシのフォールバック動作、Telegramとの同期、**OpenClaw Doctor**については [docs/ja-JP/proxy-settings.md](docs/ja-JP/proxy-settings.md) を参照してください。
## アーキテクチャ
ClawXは**デュアルプロセス + Host API 統一アクセス**構成を採用しています。Renderer は単一クライアント抽象を呼び出し、プロトコル選択とライフサイクルは Main が管理します
ClawXは **Host API統一レイヤーを備えたデュアルプロセスアーキテクチャ**を採用しています。React Rendererは単一クライアント抽象を呼び出し、Electron Mainがプロトコル選択、Gatewayのライフサイクル、ACP Chatのstdio bridgeを管理します
```
┌────────────────────────────────────────────────────────────────────┐
│ ClawX デスクトップアプリ │
│ │
│ ┌──────────────────────────────────────────────────────────────┐ │
│ │ Electron メインプロセス │ │
│ │ • ウィンドウ&アプリケーションライフサイクル管理 │ │
│ │ • ゲートウェイプロセスの監視 │ │
│ │ • システム統合(トレイ、通知、キーチェーン) │ │
│ │ • 自動アップデートオーケストレーション │ │
│ └──────────────────────────────────────────────────────────────┘ │
│ │ │
│ │ IPC(権威ある制御プレーン) │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────────┐ │
│ │ React レンダラープロセス │ │
│ │ • モダンなコンポーネントベースUI(React 19) │ │
│ │ • Zustandによるステート管理 │ │
│ │ • 統一 host-api/api-client 呼び出し │ │
│ │ • リッチなMarkdownレンダリング │ │
│ └──────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬─────────────────────────────────────┘
│ 型付き IPC リクエスト
┌─────────────────────────────────────────────────────────────────┐
│ Main Host Services と Gateway Manager │
│ │
│ • host:invoke 型付きサービスディスパッチ │
│ • 設定、ファイル、セッション、スキル、プロバイダー、診断サービス │
│ • Main が Gateway WebSocket とプロセス監視を所有 │
└──────────────────────────────┬──────────────────────────────────┘
│ Main 所有 WebSocket
┌─────────────────────────────────────────────────────────────────┐
│ OpenClaw ゲートウェイ │
│ │
│ • AIエージェントランタイムとオーケストレーション │
│ • メッセージチャネル管理 │
│ • スキル/プラグイン実行環境 │
│ • プロバイダー抽象化レイヤー │
└─────────────────────────────────────────────────────────────────┘
```
### 設計原則
- **プロセスモデル**Electron Mainがウィンドウ、Gateway監視、システム統合、更新を管理します。OpenClaw GatewayはAIオーケストレーション、チャネル、スキル機能を提供し、Rendererはローカルエンドポイントへ直接アクセスしません。
- **設定の配信**Gateway実行中は `config.get` / `config.set` を使い、停止中または起動中は解決済みJSON5設定を更新します。通常のプロバイダー、Agent、スキル、モデル変更ではプロセスを置き換えず、認証情報は `secrets.reload` でホットリロードされます。ハートビートが4回連続で失敗した場合は、ライフサイクルで保護された復旧を要求します。
- **ACP Chat**Chat UIは [ACPAgent Client Protocol](https://agentclientprotocol.com) を介してOpenClawとやり取りし、頻繁に反復されるOpenClawの前に比較的安定したチャットプロトコル面を確保します。ACPはMainが所有するstdio bridge経由で動作し、設定リロード後の認証済み履歴リプレイ、ページ移動中のストリーミング、Mainが検証したメディア・添付ファイル・ファイルアクティビティに対応します。保護されたGateway再起動によって受理済みターンが中断された場合、パッチ済みOpenClawランタイムは復旧runを元のACP promptへ明示的に関連付け、後続のテキストとツールアクティビティを同じメモリ内ターンで継続します。その後の履歴リプレイでも、永続化されたツール境界をネイティブACP updateとして復元します。
- **設計原則**:フロントエンドの単一入口、Mainによるトランスポート管理、再接続・タイムアウト・バックオフによるグレースフルリカバリ、安全なストレージ、CORSセーフな境界を採用しています。
- **プロセス分離**: AIランタイムは別プロセスで動作し、重い計算処理中でもUIの応答性を確保します
- **フロントエンド呼び出しの単一入口**: Renderer は host-api/api-client を通じて呼び出し、下位プロトコルに依存しません
- **Mainによるトランスポート制御**: Gateway WebSocket は Electron Main のみが所有し、Renderer は型付き IPC で Main と通信します
- **拡張 IPC コントリビューション**: Main プロセス拡張は HTTP route ではなく、型付き IPC レジストリを通じて host-api action を提供します
- **グレースフルリカバリ**: 再接続・タイムアウト・バックオフで一時的障害を自動処理します
- **セキュアストレージ**: APIキーや機密データは、OSのネイティブセキュアストレージ機構を活用します
- **CORSセーフ設計**: Renderer はローカル Gateway や Host API HTTP エンドポイントを直接呼び出しません
### プロセスモデルと Gateway トラブルシューティング
- ClawX は Electron アプリのため、**1つのアプリインスタンスでも複数プロセス(main/renderer/zygote/utility)が表示される**のが正常です。
- 単一起動保護は Electron のロックに加え、ローカルのプロセスロックファイルも併用し、デスクトップ IPC / セッションバスが不安定な環境でも重複起動を防ぎます。
- ローリングアップグレード中に旧版/新版が混在すると、単一起動保護の挙動が非対称になる場合があります。安定運用のため、デスクトップクライアントは可能な限り同一バージョンへ揃えてください。
- ただし OpenClaw Gateway の待受は常に**単一**であるべきです。`127.0.0.1:18789` を Listen しているプロセスは1つだけです。
- Gateway の readiness は `system-presence``health``status` などの OpenClaw コア信号を基準にし、memory、Dreams、チャネルの失敗はグローバルな Gateway 障害ではなく capability degradation として表示します。
- Listen プロセスの確認例:
- macOS/Linux: `lsof -nP -iTCP:18789 -sTCP:LISTEN`
- Windows (PowerShell): `Get-NetTCPConnection -LocalPort 18789 -State Listen`
- ウィンドウの閉じるボタン(`X`)は既定でトレイへ最小化する動作で、完全終了ではありません。完全終了する場合はトレイメニューの **Quit ClawX** を使用してください。
---
## ユースケース
### 🤖 パーソナルAIアシスタント
質問への回答、メールの下書き、ドキュメントの要約、日常タスクのサポートなど、汎用的なAIエージェントを設定できます。すべてクリーンなデスクトップインターフェースから操作できます。
### 📊 自動モニタリング
ニュースフィード、価格追跡、特定イベントの監視などを行うスケジュールエージェントを設定できます。結果はお好みの通知チャネルに配信されます。
### 💻 開発者の生産性向上
AI を開発ワークフローに統合できます。エージェントを使用して、コードレビュー、ドキュメント生成、反復的なコーディングタスクの自動化が可能です。
### 🔄 ワークフロー自動化
複数のスキルを連鎖させて、高度な自動化パイプラインを作成できます。データの処理、コンテンツの変換、アクションのトリガーを、すべてビジュアルにオーケストレーションできます。
---
> プロセス図、設定の調整、ACPファイルアクティビティのセマンティクス、Gatewayのトラブルシューティングについては [docs/ja-JP/architecture.md](docs/ja-JP/architecture.md) を参照してください。
## 開発
### 前提条件
- **Node.js**: 22以上(LTS推奨)
- **パッケージマネージャー**: pnpm 9以上(推奨)またはnpm
- **LinuxUbuntu/Debian**: Electron を実行する前に必要なシステムライブラリをインストールしてください:
```bash
sudo apt-get install -y libnss3 libgtk-3-0 libxss1 libxtst6 libatspi2.0-0 libnotify4 xdg-utils
```
Ubuntu 24.04以降では、一部のパッケージに `t64` サフィックスが付いています。上記コマンドを実行すると `apt` が自動的に適切なバリアントを選択します。
- **Node.js**:対応するメジャー系列の22.22.3以上、24.15.0以上、または25.9.0以上(Node 24 LTS推奨)
- **パッケージマネージャー**pnpm 9以上(npmも対応)
- **LinuxUbuntu/Debian**Electronの実行前に必要なシステムライブラリをインストールしてください。詳細は [docs/ja-JP/development.md](docs/ja-JP/development.md) を参照してください。
### プロジェクト構成
```ClawX/
├── electron/ # Electron メインプロセス
│ ├── services/ # 型付き Host API、Provider/Secrets/ランタイムサービス
│ │ ├── providers/ # provider/account モデル同期ロジック
│ │ └── secrets/ # OS キーチェーンと秘密情報管理
│ ├── shared/ # 共通 Provider スキーマ/定数
│ │ └── providers/
│ ├── main/ # アプリ入口、ウィンドウ、IPC 登録
│ ├── gateway/ # OpenClaw ゲートウェイプロセスマネージャー
│ ├── preload/ # セキュア IPC ブリッジ
│ └── utils/ # ユーティリティ(ストレージ、認証、パス)
├── src/ # React レンダラープロセス
│ ├── lib/ # フロントエンド統一 API とエラーモデル
│ ├── stores/ # Zustand ストア(settings/chat/gateway
│ ├── components/ # 再利用可能な UI コンポーネント
│ ├── pages/ # Setup/Dashboard/Chat/Channels/Skills/Cron/Settings
│ ├── i18n/ # ローカライズリソース
│ └── types/ # TypeScript 型定義
├── tests/
│ ├── e2e/ # Playwright による Electron E2E スモークテスト
│ └── unit/ # Vitest ユニット/統合寄りテスト
├── resources/ # 静的アセット(アイコン、画像)
└── scripts/ # ビルド/ユーティリティスクリプト
```
### 利用可能なコマンド
### よく使うコマンド
```bash
# 開発
pnpm run init # 依存関係のインストール + バンドルバイナリ(uv、agent-browser)のダウンロード
pnpm dev # ホットリロードで起動(不足時は同梱スキルを自動準備)
# コード品質
pnpm lint # ESLintを実行
pnpm typecheck # TypeScriptの型チェック
# テスト
pnpm test # ユニットテストを実行
pnpm run test:e2e # Electron E2E スモークテストを実行
pnpm run test:e2e:headed # 表示付きウィンドウで Electron E2E を実行
pnpm run comms:replay # 通信リプレイ指標を算出
pnpm run comms:baseline # 通信ベースラインを更新
pnpm run comms:compare # リプレイ指標をベースライン閾値と比較
# ビルド&パッケージ
pnpm run build:vite # フロントエンドのみビルド
pnpm build # フルプロダクションビルド(パッケージアセット含む)
pnpm package # 現在のプラットフォーム向けにパッケージ化(同梱プリインストールスキルを含む)
pnpm package:mac # macOS向けにパッケージ化
pnpm package:win # Windows向けにパッケージ化
pnpm package:linux # Linux向けにパッケージ化
pnpm run init # 依存関係をインストールし、バンドルランタイムをダウンロード
pnpm dev # ホットリロード付きで開発モードを起動
pnpm lint # ESLintを実行
pnpm typecheck # TypeScriptを検証
pnpm test # ユニットテストを実行
pnpm run test:e2e # Electron E2Eスモークテストを実行
pnpm build # 本番ビルドを実行
pnpm package # 現在のプラットフォーム向けにパッケージ化(:mac / :win / :linux
```
ヘッドレス Linux では Electron テストに表示サーバーが必要です。`xvfb-run -a pnpm run test:e2e` を利用してください。
### 通信回帰チェック
PR が通信経路(Gateway イベント、Chat 送受信フロー、Channel 配信、トランスポートのフォールバック)に触れる場合は、次を実行してください。
```bash
pnpm run comms:replay
pnpm run comms:compare
```
CI の `comms-regression` が必須シナリオと閾値を検証します。
### 技術スタック
| レイヤー | 技術 |
|---------|------|
| ランタイム | Electron 40以上 |
| UIフレームワーク | React 19 + TypeScript |
| スタイリング | Tailwind CSS + shadcn/ui |
| ステート管理 | Zustand |
| ビルド | Vite + electron-builder |
| テスト | Vitest + Playwright |
| アニメーション | Framer Motion |
| アイコン | Lucide React |
---
> プロジェクト構成、完全なコマンド一覧、E2Eの並列実行ポリシー、パフォーマンス診断、通信回帰チェック、技術スタックについては [docs/ja-JP/development.md](docs/ja-JP/development.md) を参照してください。
## コントリビューション
コミュニティからのコントリビューションを歓迎しますバグ修正、新機能、ドキュメントの改善、翻訳など、あらゆる貢献がClawXをより良くするのに役立ちます。
コミュニティからの貢献を歓迎しますバグ修正、新機能、ドキュメントの改善、翻訳など、あらゆる貢献がClawXをより良くます。
### コントリビューション方法
### 貢献方法
1. リポジトリを**フォーク**する
2. フィーチャーブランチを**作成**する(`git checkout -b feature/amazing-feature`
3. 明確なメッセージで変更を**コミット**する
4. ブランチに**プッシュ**する
5. **プルリクエスト**を作成する
5. **Pull Request**を作成する
### ガイドライン
- 既存のコードスタイルに従うESLint + Prettier
- 既存のコードスタイル(ESLint + Prettierに従う
- 新機能にはテストを書く
- 必要に応じてドキュメントを更新する
- コミットはアトミックかつ説明的に保つ
---
## 謝辞
ClawXは優れたオープンソースプロジェクトの上に構築されています
ClawXは次の優れたオープンソースプロジェクトの上に構築されています
- [OpenClaw](https://github.com/OpenClaw) AIエージェントランタイム
- [Electron](https://www.electronjs.org/) クロスプラットフォームデスクトップフレームワーク
- [React](https://react.dev/) UIコンポーネントライブラリ
- [shadcn/ui](https://ui.shadcn.com/) 美しくデザインされたコンポーネント
- [Zustand](https://github.com/pmndrs/zustand) 軽量ステート管理
---
- [OpenClaw](https://github.com/OpenClaw) - AIエージェントランタイム
- [Electron](https://www.electronjs.org/) - クロスプラットフォームデスクトップフレームワーク
- [React](https://react.dev/) - UIコンポーネントライブラリ
- [shadcn/ui](https://ui.shadcn.com/) - 美しく設計されたコンポーネント
- [Zustand](https://github.com/pmndrs/zustand) - 軽量な状態管理
## コミュニティ
コミュニティに参加して、他のユーザーとつながり、サポートを受け、体験を共有しましょう。
コミュニティに参加して、他のユーザーと交流し、サポートを受け、体験を共有しましょう。
| 企業微信 | Feishuグループ | Discord |
| 企業WeChat | Feishuグループ | Discord |
| :---: | :---: | :---: |
| <img src="src/assets/community/wecom-qr.png" width="150" alt="WeChat QRコード" /> | <img src="src/assets/community/feishu-qr.png" width="150" alt="Feishu QRコード" /> | <img src="src/assets/community/20260212-185822.png" width="150" alt="Discord QRコード" /> |
### ClawX パートナープログラム 🚀
### ClawXパートナープログラム
ClawX パートナープログラムを開始します。特にカスタム AI エージェントや自動化ニーズを持つより多くの顧客に ClawX を紹介してくださるパートナーを募集しています。
ClawXをより多くのお客様、特にカスタムAIエージェントや自動化ニーズを持つお客様に紹介してくださるパートナーを募集しています。
パートナーの皆さまには、見込みユーザーや案件との接点づくりを担っていただき、ClawX チームは技術サポート、カスタマイズ、統合を全面的に提供します。
パートナー見込みユーザーやプロジェクトとの接点づくりを担、ClawXチームは技術サポート、カスタマイズ、統合を全面的に提供します。AIツールや自動化に関心のあるお客様と仕事をされている方は、ぜひご一緒ください。
AI ツールや自動化に関心のある顧客とお仕事をされている方は、ぜひご一緒できればうれしいです
詳細はDM、または [public@valuecell.ai](mailto:public@valuecell.ai) までお問い合わせください
詳細は DM いただくか、[public@valuecell.ai](mailto:public@valuecell.ai) までメールでご連絡ください。
---
## スター履歴
## Star History
<p align="center">
<img src="https://api.star-history.com/svg?repos=ValueCell-ai/ClawX&type=Date" alt="スター履歴チャート" />
<img src="https://api.star-history.com/svg?repos=ValueCell-ai/ClawX&type=Date" alt="Star History Chart" />
</p>
---
## ライセンス
ClawXは[MITライセンス](LICENSE)の下でリリースされています。本ソフトウェア使用、変更、配布は自由に行えます。
ClawXは [MITライセンス](LICENSE) のもとで公開されています。本ソフトウェアは自由に使用、変更、配布できます。
---
<hr>
<p align="center">
<sub>ValueCell Teamが❤️を込めて開発</sub>
+76 -327
View File
@@ -10,7 +10,6 @@
</p>
<p align="center">
<a href="#features">Features</a> •
<a href="#why-clawx">Why ClawX</a> •
<a href="#getting-started">Getting Started</a> •
<a href="#architecture">Architecture</a> •
@@ -37,114 +36,64 @@
## Overview
**ClawX** bridges the gap between powerful AI agents and everyday users. Built on top of [OpenClaw](https://github.com/OpenClaw), it transforms command-line AI orchestration into an accessible, beautiful desktop experienceno terminal required.
**ClawX** bridges the gap between powerful AI agents and everyday users. Built on top of [OpenClaw](https://github.com/OpenClaw), it transforms command-line AI orchestration into an accessible, beautiful desktop experience - no terminal required.
Whether you're automating workflows, managing AI-powered channels, or scheduling intelligent tasks, ClawX provides the interface you need to harness AI agents effectively.
ClawX comes pre-configured with best-practice model providers and natively supports Windows as well as multi-language settings. Of course, you can also fine-tune advanced configurations via **Settings Advanced Developer Mode**.
ClawX comes pre-configured with best-practice model providers and natively supports Windows as well as multi-language settings. You can also fine-tune advanced configurations via **Settings -> Advanced -> Developer Mode**.
<p align="center"><strong style="font-size:1.1em; text-decoration: underline;">For a full enterprise edition, dedicated service support, or tailored deployment guidance for your business scenario, contact us at <a href="mailto:public@valuecell.ai">public@valuecell.ai</a>.</strong></p>
---
## Screenshot
## Screenshots
<p align="center">
<img src="resources/screenshot/en/chat.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/en/cron.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/en/skills.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/en/channels.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/en/models.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/en/settings.png" style="width: 100%; height: auto;">
</p>
---
<table>
<tr>
<td align="center"><img src="resources/screenshot/en/chat.png" alt="Chat"><br><em>Chat</em></td>
<td align="center"><img src="resources/screenshot/en/cron.png" alt="Cron"><br><em>Scheduled tasks</em></td>
</tr>
<tr>
<td align="center"><img src="resources/screenshot/en/skills.png" alt="Skills"><br><em>Skills</em></td>
<td align="center"><img src="resources/screenshot/en/channels.png" alt="Channels"><br><em>Channels</em></td>
</tr>
<tr>
<td align="center"><img src="resources/screenshot/en/models.png" alt="Models"><br><em>Models</em></td>
<td align="center"><img src="resources/screenshot/en/settings.png" alt="Settings"><br><em>Settings</em></td>
</tr>
</table>
## Why ClawX
Building AI agents shouldn't require mastering the command line. ClawX was designed with a simple philosophy: **powerful technology deserves an interface that respects your time.**
Building AI agents shouldn't require mastering the command line. ClawX was designed with a simple philosophy: **powerful technology deserves an interface that respects your time.** ClawX is built directly upon the official **OpenClaw** core. Instead of requiring a separate installation, we embed the runtime within the application for a seamless, battery-included experience. We stay closely aligned with upstream OpenClaw so you can benefit from the latest official capabilities, stability improvements, and ecosystem compatibility.
| Challenge | ClawX Solution |
|-----------|----------------|
| Complex CLI setup | One-click installation with guided setup wizard |
| Complex CLI setup | One-click installation with a guided setup wizard |
| Configuration files | Visual settings with real-time validation |
| Process management | Automatic gateway lifecycle management |
| Process management | Automatic Gateway lifecycle management |
| App updates | Startup update checks with a prompt before downloading or installing |
| Multiple AI providers | Unified provider configuration panel |
| Skill/plugin installation | Local-first skill management with optional extension-provided marketplace |
| Skill/plugin installation | Local-first skill management with an optional extension-provided marketplace |
### OpenClaw Inside
### Features
ClawX is built directly upon the official **OpenClaw** core. Instead of requiring a separate installation, we embed the runtime within the application to provide a seamless "battery-included" experience.
- **🎯 Zero Configuration Barrier**: Complete setup through an intuitive graphical interface - no terminal commands, YAML files, or environment-variable hunting.
- **💬 Intelligent Chat Interface**: Multi-session context and history, streaming Markdown with syntax highlighting, CJK-aware parsing, tables, KaTeX math, direct `@agent` routing, inline `/skill` cards, workspace-first sessions, and read-only previews for Markdown, `.docx`, `.pptx`, and local HTML.
- **📡 Multi-Channel Management**: Configure and monitor independent AI channels with multiple accounts, per-account agent binding, default-account switching, and the bundled official Tencent personal WeChat channel plugin.
- **⏰ Cron-Based Automation**: Define recurring or one-time schedules, insert skills into scheduled prompts, and deliver results to external channels.
- **🧩 Extensible Skill System**: Manage skills locally without depending on the Gateway, discover skills from multiple OpenClaw sources, and use bundled document-processing skills for `pdf`, `xlsx`, `docx`, and `pptx`.
- **🔐 Secure Provider Integration**: Connect OpenAI, Anthropic, Z.AI / GLM, and other providers with credentials stored in the native system keychain; supports OAuth, custom providers, image-generation endpoints, and compatibility fallbacks.
- **🌙 Adaptive Theming**: Choose light mode, dark mode, or system-synchronized themes.
- **🚀 Startup Launch Control**: Enable **Launch at system startup** in **Settings -> General**.
- **🔔 Update Prompts**: Check for new versions at startup and choose whether to download or install them.
We are committed to maintaining strict alignment with the upstream OpenClaw project, ensuring that you always have access to the latest capabilities, stability improvements, and ecosystem compatibility provided by the official releases.
> For full feature details, see [docs/en-US/features.md](docs/en-US/features.md).
When Developer Mode is enabled, the sidebar also provides a native Dreams page for OpenClaw memory review, dream diary inspection, and basic maintenance actions. The full upstream OpenClaw Dreams UI remains available from that page when deeper diagnostics are needed.
### Typical Use Cases
---
## Features
### 🎯 Zero Configuration Barrier
Complete the entire setup—from installation to your first AI interaction—through an intuitive graphical interface. No terminal commands, no YAML files, no environment variable hunting.
### 💬 Intelligent Chat Interface
Communicate with AI agents through a modern chat experience. Support for multiple conversation contexts, message history, rich content rendering with Markdown (including GitHub-flavored tables and KaTeX-powered LaTeX math: `$inline$`, `$$block$$`, `\(inline\)`, and `\[block\]`), and direct `@agent` routing in the main composer for multi-agent setups.
Skills you insert from the composer appear as `/skill-name` chips; click a chip to open the preview sidebar and read that skill's `SKILL.md`.
When you target another agent with `@agent`, ClawX switches into that agent's own conversation context directly instead of relaying through the default agent. Agent workspaces stay separate by default, and stronger isolation depends on OpenClaw sandbox settings.
Each agent can also override its own `provider/model` runtime setting; agents without overrides continue inheriting the global default model.
### 📡 Multi-Channel Management
Configure and monitor multiple AI channels simultaneously. Each channel operates independently, allowing you to run specialized agents for different tasks.
Each channel now supports multiple accounts, per-account agent binding, and switching the channel default account directly from the Channels page.
For custom channel account IDs, ClawX enforces OpenClaw-compatible canonical IDs (`[a-z0-9_-]`, lowercase, max 64 chars, must start with a letter/number) to prevent routing mismatches.
ClawX now also bundles Tencent's official personal WeChat channel plugin, so you can link WeChat directly from the Channels page with an in-app QR flow.
### ⏰ Cron-Based Automation
Schedule AI tasks to run automatically. Define triggers, set intervals, and let your AI agents work around the clock without manual intervention.
The Cron page now lets you configure external delivery directly in the task form with separate sender-account and recipient-target selectors. For supported channels, recipient targets are discovered automatically from channel directories or known session history, so you no longer need to edit `jobs.json` by hand.
### 🧩 Extensible Skill System
Extend your AI agents with pre-built skills. The integrated Skills page is local-first: it scans managed/workspace skill directories, lets you enable or disable skills without depending on the Gateway, and can optionally expose an extension-provided marketplace in enterprise builds.
ClawX also pre-bundles full document-processing skills (`pdf`, `xlsx`, `docx`, `pptx`), deploys them automatically to the managed skills directory (default `~/.openclaw/skills`) on startup, and enables them by default on first install. Additional bundled skills (`find-skills`, `self-improving-agent`, `tavily-search`) are also enabled by default; if required API keys are missing, OpenClaw will surface configuration errors in runtime.
The Skills page can display skills discovered from multiple OpenClaw sources (managed dir, workspace, and extra skill dirs), and now shows each skill's actual location so you can open the real folder directly. For bundled OpenClaw skills, community builds now ship and expose only `skill-creator`; non-allowlisted bundled skills are physically trimmed in both dev and packaged startup, and any stale `openclaw.json` entries left behind for those removed bundled skills are pruned.
Environment variables for bundled search skills:
- `TAVILY_API_KEY` for `tavily-search` (OAuth may also be supported by upstream skill runtime)
- `find-skills` and `self-improving-agent` do not require API keys
### 🔐 Secure Provider Integration
Connect to multiple AI providers (OpenAI, Anthropic, and more) with credentials stored securely in your system's native keychain. OpenAI supports both API key and browser OAuth (Codex subscription) sign-in.
In developer mode, the dedicated Image Generation page supports an independent OpenAI-compatible image-generation endpoint (Base URL, API key, and model name such as `gpt-image-2`) so image generation can use a dedicated `/v1/images/generations` service while chat continues using the normal OpenAI provider.
For **Custom** providers used with OpenAI-compatible gateways, you can set a custom `User-Agent` in **Settings → AI Providers → Edit Provider** for compatibility-sensitive endpoints.
When you edit or switch providers, ClawX preserves existing per-model capability metadata such as `input: ["text", "image"]`. Newly selected Custom-provider models use OpenClaw onboarding-compatible image-input inference, with unknown models defaulting to text-only.
When a compatible gateway rejects `/models` for non-auth reasons, ClawX automatically falls back to a lightweight `/chat/completions` or `/responses` probe during API key validation.
### 🌙 Adaptive Theming
Light mode, dark mode, or system-synchronized themes. ClawX adapts to your preferences automatically.
### 🚀 Startup Launch Control
In **Settings → General**, you can enable **Launch at system startup** so ClawX starts automatically after login.
### 🔔 Update Prompts
ClawX can automatically check for new versions on startup. When an update is available, it shows an in-app prompt; downloading and installing only happen after you choose the action.
---
- **🤖 Personal AI Assistant**: Configure a general-purpose AI agent to answer questions, draft emails, summarize documents, and help with everyday tasks from a clean desktop interface.
- **📊 Automated Monitoring**: Schedule agents to monitor news feeds, track prices, or watch for specific events, with results delivered to your preferred notification channel.
- **💻 Developer Productivity**: Integrate AI into your development workflow for code review, documentation generation, and repetitive coding tasks.
- **🔄 Workflow Automation**: Chain multiple skills into visual automation pipelines that process data, transform content, and trigger actions.
## Getting Started
@@ -173,257 +122,67 @@ pnpm run init
# Start in development mode
pnpm dev
```
### First Launch
When you launch ClawX for the first time, the **Setup Wizard** will guide you through:
1. **Language & Region** Configure your preferred locale
2. **AI Provider** Add providers with API keys or OAuth (for providers that support browser/device login)
3. **Skill Bundles** Select pre-configured skills for common use cases
4. **Verification** Test your configuration before entering the main interface
1. **Language & Region** - Configure your preferred locale
2. **AI Provider** - Add providers with API keys or OAuth for providers that support browser or device login
3. **Skill Bundles** - Select pre-configured skills for common use cases
4. **Verification** - Test your configuration before entering the main interface
The wizard preselects your system language when it is supported, and falls back to English otherwise.
> Note for Moonshot (Kimi): ClawX keeps Kimi web search enabled by default.
> When Moonshot is configured, ClawX also syncs Kimi web search to the China endpoint (`https://api.moonshot.cn/v1`) in OpenClaw config.
> Web search note: ClawX disables OpenClaw's general-purpose `web_search` tool at both the agent and Gateway policy layers. This includes Moonshot (Kimi) search; managed browser automation and `web_fetch` remain available.
>
> Internal tool note: ClawX also disables `gateway`, `nodes`, `create_goal`, `get_goal`, and `update_goal` for agents at both policy layers. Application-owned Gateway RPCs remain available, as do messaging, session orchestration, and agent discovery tools.
### Proxy Settings
ClawX includes built-in proxy settings for environments where Electron, the OpenClaw Gateway, or channels such as Telegram need to reach the internet through a local proxy client.
ClawX includes built-in proxy settings for Electron, the OpenClaw Gateway, and channels such as Telegram that need to reach the internet through a local proxy client.
Open **Settings Gateway Proxy** and configure:
Open **Settings -> Gateway -> Proxy** to configure the default proxy, bypass rules, and optional developer-mode overrides for HTTP, HTTPS, and `ALL_PROXY` / SOCKS. A local example is `http://127.0.0.1:7890`.
- **Proxy Server**: the default proxy for all requests
- **Bypass Rules**: hosts that should connect directly, separated by semicolons, commas, or new lines
- In **Developer Mode**, you can optionally override:
- **HTTP Proxy**
- **HTTPS Proxy**
- **ALL_PROXY / SOCKS**
Recommended local examples:
```text
Proxy Server: http://127.0.0.1:7890
```
Notes:
- A bare `host:port` value is treated as HTTP.
- If advanced proxy fields are left empty, ClawX falls back to `Proxy Server`.
- Saving proxy settings reapplies Electron networking immediately and restarts the Gateway automatically.
- ClawX also syncs the proxy to OpenClaw's Telegram channel config when Telegram is enabled.
- Gateway restarts preserve an existing Telegram channel proxy if ClawX proxy is currently disabled.
- To explicitly clear Telegram channel proxy from OpenClaw config, save proxy settings with proxy disabled.
- In **Settings → Advanced → Developer**, you can run **OpenClaw Doctor** to execute `openclaw doctor --json` and inspect the diagnostic output without leaving the app.
- On packaged Windows builds, the bundled `openclaw` CLI/TUI runs via the shipped `node.exe` entrypoint to keep terminal input behavior stable.
---
> For proxy fallback behavior, Telegram synchronization, and **OpenClaw Doctor**, see [docs/en-US/proxy-settings.md](docs/en-US/proxy-settings.md).
## Architecture
ClawX employs a **dual-process architecture** with a unified host API layer. The renderer talks to a single client abstraction, while Electron Main owns protocol selection and process lifecycle:
ClawX uses a **dual-process architecture with a unified Host API layer**: the React renderer calls one client abstraction, while Electron Main owns protocol selection, Gateway lifecycle, and the ACP Chat stdio bridge.
```
┌──────────────────────────────────────────────────────────────────┐
│ ClawX Desktop App │
│ │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ Electron Main Process │ │
│ │ • Window & application lifecycle management │ │
│ │ • Gateway process supervision │ │
│ │ • System integration (tray, notifications, keychain) │ │
│ │ • Auto-update orchestration │ │
│ └────────────────────────────────────────────────────────────┘ │
│ │ │
│ │ IPC (authoritative control plane) │
│ ▼ │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ React Renderer Process │ │
│ │ • Modern component-based UI (React 19) │ │
│ │ • State management with Zustand │ │
│ │ • Unified host-api/api-client calls │ │
│ │ • Rich Markdown rendering │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬───────────────────────────────────┘
│ Typed IPC requests
┌──────────────────────────────────────────────────────────────────┐
│ Main Host Services & Gateway Manager │
│ │
│ • host:invoke typed service dispatcher │
│ • Settings, files, sessions, skills, providers, diagnostics │
│ • Main-owned Gateway WebSocket and process supervision │
└──────────────────────────────┬───────────────────────────────────┘
│ Main-owned WebSocket
┌──────────────────────────────────────────────────────────────────┐
│ OpenClaw Gateway │
│ │
│ • AI agent runtime and orchestration │
│ • Message channel management │
│ • Skill/plugin execution environment │
│ • Provider abstraction layer │
└──────────────────────────────────────────────────────────────────┘
```
### Design Principles
- **Process model**: Electron Main owns the window, Gateway supervision, system integration, and updates; the OpenClaw Gateway provides AI orchestration, channel, and skill capabilities; the renderer does not access local endpoints directly.
- **Configuration delivery**: Main uses `config.get`/`config.set` while the Gateway is running and updates the resolved JSON5 config while it is stopped or starting; ordinary provider, agent, skill, and model changes do not replace the process, credentials are hot-reloaded through `secrets.reload`, and guarded recovery starts after four consecutive heartbeat misses.
- **ACP Chat**: Chat UI talks to OpenClaw via [ACP (Agent Client Protocol)](https://agentclientprotocol.com), providing a relatively stable chat protocol surface in front of the rapidly iterating OpenClaw. ACP runs through a Main-owned stdio bridge, supporting authenticated history replay after config reloads, streaming across navigation, and Main-validated media, attachments, and file activity. When a guarded Gateway restart interrupts an accepted turn, the patched OpenClaw runtime explicitly links its recovery run to the original ACP prompt so subsequent text and tool activity continue in the same in-memory turn; later history replay restores persisted tool boundaries as native ACP updates.
- **Design principles**: One frontend entry point, Main-owned transport, graceful recovery with reconnect/timeout/backoff, secure storage, and CORS-safe boundaries.
- **Process Isolation**: The AI runtime operates in a separate process, ensuring UI responsiveness even during heavy computation
- **Single Entry for Frontend Calls**: Renderer requests go through host-api/api-client; protocol details are hidden behind a stable interface
- **Main-Process Transport Ownership**: Electron Main owns the Gateway WebSocket; the renderer talks to Main over typed IPC
- **Extension IPC Contributions**: Main-process extensions contribute host-api actions through the typed IPC registry instead of HTTP routes
- **Graceful Recovery**: Built-in reconnect, timeout, and backoff logic handles transient failures automatically
- **Secure Storage**: API keys and sensitive data leverage the operating system's native secure storage mechanisms
- **CORS-Safe by Design**: The renderer does not call local Gateway or Host API HTTP endpoints directly
### Process Model & Gateway Troubleshooting
- ClawX is an Electron app, so **one app instance normally appears as multiple OS processes** (main/renderer/zygote/utility). This is expected.
- Single-instance protection uses Electron's lock plus a local process-file lock fallback, preventing duplicate app launch in environments where desktop IPC/session bus is unstable.
- During rolling upgrades, mixed old/new app versions can still have asymmetric protection behavior. For best reliability, upgrade all desktop clients to the same version.
- The OpenClaw Gateway listener should still be **single-owner**: only one process should listen on `127.0.0.1:18789`.
- Gateway readiness is based on OpenClaw core signals such as `system-presence`, `health`, and `status`; memory, Dreams, or channel failures are shown as capability degradation instead of global Gateway failure.
- To verify the active listener:
- macOS/Linux: `lsof -nP -iTCP:18789 -sTCP:LISTEN`
- Windows (PowerShell): `Get-NetTCPConnection -LocalPort 18789 -State Listen`
- Clicking the window close button (`X`) hides ClawX to tray; it does **not** fully quit the app. Use tray menu **Quit ClawX** for complete shutdown.
---
## Use Cases
### 🤖 Personal AI Assistant
Configure a general-purpose AI agent that can answer questions, draft emails, summarize documents, and help with everyday tasks—all from a clean desktop interface.
### 📊 Automated Monitoring
Set up scheduled agents to monitor news feeds, track prices, or watch for specific events. Results are delivered to your preferred notification channel.
### 💻 Developer Productivity
Integrate AI into your development workflow. Use agents to review code, generate documentation, or automate repetitive coding tasks.
### 🔄 Workflow Automation
Chain multiple skills together to create sophisticated automation pipelines. Process data, transform content, and trigger actions—all orchestrated visually.
---
> For the process diagram, configuration coordination, ACP file activity semantics, and Gateway troubleshooting, see [docs/en-US/architecture.md](docs/en-US/architecture.md).
## Development
### Prerequisites
- **Node.js**: 22+ (LTS recommended)
- **Package Manager**: pnpm 9+ (recommended) or npm
- **Linux (Ubuntu/Debian)**: Install required system libraries before running Electron:
```bash
sudo apt-get install -y libnss3 libgtk-3-0 libxss1 libxtst6 libatspi2.0-0 libnotify4 xdg-utils
```
On Ubuntu 24.04+, some packages use a `t64` suffix; run the above command and `apt` will automatically select the correct variant.
- **Node.js**: 22.22.3+, 24.15.0+, or 25.9.0+ within the corresponding supported major line (Node 24 LTS recommended)
- **Package Manager**: pnpm 9+ (npm is also supported)
- **Linux (Ubuntu/Debian)**: Install required system libraries before running Electron; see [docs/en-US/development.md](docs/en-US/development.md)
### Project Structure
```ClawX/
├── electron/ # Electron Main Process
│ ├── services/ # Typed host APIs, provider, secrets and runtime services
│ │ ├── providers/ # Provider/account model sync logic
│ │ └── secrets/ # OS keychain and secret storage
│ ├── shared/ # Shared provider schemas/constants
│ │ └── providers/
│ ├── main/ # App entry, windows, IPC registration
│ ├── gateway/ # OpenClaw Gateway process manager
│ ├── preload/ # Secure IPC bridge
│ └── utils/ # Utilities (storage, auth, paths)
├── src/ # React Renderer Process
│ ├── lib/ # Unified frontend API + error model
│ ├── stores/ # Zustand stores (settings/chat/gateway)
│ ├── components/ # Reusable UI components
│ ├── pages/ # Setup/Dashboard/Chat/Channels/Skills/Cron/Settings
│ ├── i18n/ # Localization resources
│ └── types/ # TypeScript type definitions
├── tests/
│ ├── e2e/ # Playwright Electron end-to-end smoke tests
│ └── unit/ # Vitest unit/integration-like tests
├── resources/ # Static assets (icons/images)
└── scripts/ # Build and utility scripts
```
### Available Commands
### Common Commands
```bash
# Development
pnpm run init # Install dependencies + download bundled binaries (uv, agent-browser)
pnpm dev # Start with hot reload (auto-prepares bundled skills if missing)
# Quality
pnpm lint # Run ESLint
pnpm typecheck # TypeScript validation
# Testing
pnpm test # Run unit tests
pnpm run test:e2e # Run Electron E2E smoke tests with Playwright
pnpm run test:e2e:headed # Run Electron E2E tests with a visible window
pnpm run comms:replay # Compute communication replay metrics
pnpm run comms:baseline # Refresh communication baseline snapshot
pnpm run comms:compare # Compare replay metrics against baseline thresholds
# Build & Package
pnpm run build:vite # Build frontend only
pnpm build # Full production build (with packaging assets)
pnpm package # Package for current platform (includes bundled preinstalled skills)
pnpm package:mac # Package for macOS
pnpm package:win # Package for Windows
pnpm package:linux # Package for Linux
pnpm run init # Install dependencies and download bundled runtimes
pnpm dev # Start in development mode with hot reload
pnpm lint # Run ESLint
pnpm typecheck # TypeScript validation
pnpm test # Run unit tests
pnpm run test:e2e # Run Electron E2E smoke tests
pnpm build # Full production build
pnpm package # Package for the current platform (:mac / :win / :linux)
```
On headless Linux, run Electron tests under a display server such as `xvfb-run -a pnpm run test:e2e`.
### Communication Regression Checks
When a PR changes communication paths (gateway events, chat runtime send/receive flow, channel delivery, or transport fallback), run:
```bash
pnpm run comms:replay
pnpm run comms:compare
```
`comms-regression` in CI enforces required scenarios and threshold checks.
### Electron E2E Tests
The Playwright Electron suite launches the packaged renderer and main process
from `dist/` and `dist-electron/`, so it does not require manually running
`pnpm dev` first.
`pnpm run test:e2e` automatically:
- builds the renderer and Electron bundles with `pnpm run build:vite`
- starts Electron in an isolated E2E mode with a temporary `HOME`
- uses a temporary ClawX `userData` directory
- skips heavy startup side effects such as gateway auto-start, bundled skill
installation, tray creation, and CLI auto-install
The first two baseline specs cover:
- first-launch setup wizard visibility on a fresh profile
- skipping setup and navigating to the Models page inside the Electron app
Add future Electron flows under `tests/e2e/` and reuse the shared fixture in
`tests/e2e/fixtures/electron.ts`.
### Tech Stack
| Layer | Technology |
|-------|------------|
| Runtime | Electron 40+ |
| UI Framework | React 19 + TypeScript |
| Styling | Tailwind CSS + shadcn/ui |
| State | Zustand |
| Build | Vite + electron-builder |
| Testing | Vitest + Playwright |
| Animation | Framer Motion |
| Icons | Lucide React |
---
> For the project structure, complete command list, E2E parallel policy, performance diagnostics, communication regression checks, and tech stack, see [docs/en-US/development.md](docs/en-US/development.md).
## Contributing
We welcome contributions from the community! Whether it's bug fixes, new features, documentation improvements, or translationsevery contribution helps make ClawX better.
We welcome contributions from the community! Whether it's bug fixes, new features, documentation improvements, or translations, every contribution helps make ClawX better.
### How to Contribute
@@ -440,19 +199,15 @@ We welcome contributions from the community! Whether it's bug fixes, new feature
- Update documentation as needed
- Keep commits atomic and descriptive
---
## Acknowledgments
ClawX is built on the shoulders of excellent open-source projects:
- [OpenClaw](https://github.com/OpenClaw) The AI agent runtime
- [Electron](https://www.electronjs.org/) Cross-platform desktop framework
- [React](https://react.dev/) UI component library
- [shadcn/ui](https://ui.shadcn.com/) Beautifully designed components
- [Zustand](https://github.com/pmndrs/zustand) Lightweight state management
---
- [OpenClaw](https://github.com/OpenClaw) - The AI agent runtime
- [Electron](https://www.electronjs.org/) - Cross-platform desktop framework
- [React](https://react.dev/) - UI component library
- [shadcn/ui](https://ui.shadcn.com/) - Beautifully designed components
- [Zustand](https://github.com/pmndrs/zustand) - Lightweight state management
## Community
@@ -462,31 +217,25 @@ Join our community to connect with other users, get support, and share your expe
| :---: | :---: | :---: |
| <img src="src/assets/community/wecom-qr.png" width="150" alt="WeChat QR Code" /> | <img src="src/assets/community/feishu-qr.png" width="150" alt="Feishu QR Code" /> | <img src="src/assets/community/20260212-185822.png" width="150" alt="Discord QR Code" /> |
### ClawX Partner Program 🚀
### ClawX Partner Program
We're launching the ClawX Partner Program and looking for partners who can help introduce ClawX to more clients, especially those with custom AI agent or automation needs.
Partners help connect us with potential users and projects, while the ClawX team provides full technical support, customization, and integration.
If you work with clients interested in AI tools or automation, we'd love to collaborate.
Partners help connect us with potential users and projects, while the ClawX team provides full technical support, customization, and integration. If you work with clients interested in AI tools or automation, we'd love to collaborate.
DM us or email [public@valuecell.ai](mailto:public@valuecell.ai) to learn more.
---
## Star History
<p align="center">
<img src="https://api.star-history.com/svg?repos=ValueCell-ai/ClawX&type=Date" alt="Star History Chart" />
</p>
---
## License
ClawX is released under the [MIT License](LICENSE). You're free to use, modify, and distribute this software.
---
<hr>
<p align="center">
<sub>Built with ❤️ by the ValueCell Team</sub>
+100 -337
View File
@@ -1,142 +1,99 @@
<p align="center">
<img src="src/assets/logo.svg" width="128" height="128" alt="ClawX Logo" />
<img src="src/assets/logo.svg" width="128" height="128" alt="ClawX Logo" />
</p>
<h1 align="center">ClawX</h1>
<p align="center">
<strong>Десктоп-интерфейс для AI-агентов OpenClaw</strong>
<strong>Десктоп-интерфейс для AI-агентов OpenClaw</strong>
</p>
<p align="center">
<a href="#возможности">Возможности</a> •
<a href="#почему-clawx">Почему ClawX</a> •
<a href="#быстрый-старт">Быстрый старт</a> •
<a href="#архитектура">Архитектура</a> •
<a href="#разработка">Разработка</a>
<a href="#участие">Участие</a>
<a href="#почему-clawx">Почему ClawX</a> •
<a href="#быстрый-старт">Быстрый старт</a> •
<a href="#архитектура">Архитектура</a> •
<a href="#разработка">Разработка</a> •
<a href="#участие">Участие</a>
</p>
<p align="center">
<img src="https://img.shields.io/badge/platform-MacOS%20%7C%20Windows%20%7C%20Linux-blue" alt="Platform" />
<img src="https://img.shields.io/badge/electron-40+-47848F?logo=electron" alt="Electron" />
<img src="https://img.shields.io/badge/react-19-61DAFB?logo=react" alt="React" />
<a href="https://discord.com/invite/84Kex3GGAh" target="_blank">
<img src="https://img.shields.io/discord/1399603591471435907?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb" alt="chat on Discord" />
</a>
<img src="https://img.shields.io/github/downloads/ValueCell-ai/ClawX/total?color=%23027DEB" alt="Downloads" />
<img src="https://img.shields.io/badge/license-MIT-green" alt="License" />
<img src="https://img.shields.io/badge/platform-MacOS%20%7C%20Windows%20%7C%20Linux-blue" alt="Platform" />
<img src="https://img.shields.io/badge/electron-40+-47848F?logo=electron" alt="Electron" />
<img src="https://img.shields.io/badge/react-19-61DAFB?logo=react" alt="React" />
<a href="https://discord.com/invite/84Kex3GGAh" target="_blank">
<img src="https://img.shields.io/discord/1399603591471435907?logo=discord&labelColor=%20%235462eb&logoColor=%20%23f5f5f5&color=%20%235462eb" alt="chat on Discord" />
</a>
<img src="https://img.shields.io/github/downloads/ValueCell-ai/ClawX/total?color=%23027DEB" alt="Downloads" />
<img src="https://img.shields.io/badge/license-MIT-green" alt="License" />
</p>
<p align="center">
<a href="README.md">English</a> | <a href="README.zh-CN.md">简体中文</a> | <a href="README.ja-JP.md">日本語</a> | Русский
<a href="README.md">English</a> | <a href="README.zh-CN.md">简体中文</a> | <a href="README.ja-JP.md">日本語</a> | Русский
</p>
---
## Обзор
**ClawX** — это мост между мощными AI-агентами и повседневными пользователями. Построенный на базе [OpenClaw](https://github.com/OpenClaw), он превращает управление AI через командную строку в доступный и красивый десктоп-опыт — терминал не нужен.
**ClawX** — это мост между мощными AI-агентами и повседневными пользователями. Построенный на базе [OpenClaw](https://github.com/OpenClaw), он превращает управление AI через командную строку в доступный и красивый десктопный интерфейс — терминал не нужен.
Автоматизация рабочих процессов, управление AI-каналами или планирование интеллектуальных задач — ClawX предоставляет интерфейс для эффективного использования AI-агентов.
ClawX поставляется с предустановленными лучшими практиками для провайдеров моделей и нативно поддерживает Windows, а также многоязычные настройки. Вы можете тонко настроить расширенные параметры через **Настройки → Дополнительно → Режим разработчика**.
ClawX поставляется с предварительно настроенными провайдерами моделей, соответствующими лучшим практикам, и нативно поддерживает Windows и многоязычные настройки. Расширенные параметры можно настроить через **Настройки → Дополнительно → Режим разработчика**.
<p align="center"><strong style="font-size:1.1em; text-decoration: underline;">Для получения полной корпоративной версии, специализированной поддержки или индивидуального сопровождения внедрения под ваш бизнес-сценарий, свяжитесь с нами по адресу <a href="mailto:public@valuecell.ai">public@valuecell.ai</a>.</strong></p>
---
<p align="center"><strong style="font-size:1.1em; text-decoration: underline;">Для получения полной корпоративной версии, специализированной поддержки или индивидуального сопровождения внедрения под ваш бизнес-сценарий свяжитесь с нами по адресу <a href="mailto:public@valuecell.ai">public@valuecell.ai</a>.</strong></p>
## Скриншоты
<p align="center">
<img src="resources/screenshot/ru/chat.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/ru/cron.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/ru/skills.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/ru/channels.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/ru/models.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/ru/settings.png" style="width: 100%; height: auto;">
</p>
---
<table>
<tr>
<td align="center"><img src="resources/screenshot/ru/chat.png" alt="Chat"><br><em>Чат</em></td>
<td align="center"><img src="resources/screenshot/ru/cron.png" alt="Cron"><br><em>Запланированные задачи</em></td>
</tr>
<tr>
<td align="center"><img src="resources/screenshot/ru/skills.png" alt="Skills"><br><em>Навыки</em></td>
<td align="center"><img src="resources/screenshot/ru/channels.png" alt="Channels"><br><em>Каналы</em></td>
</tr>
<tr>
<td align="center"><img src="resources/screenshot/ru/models.png" alt="Models"><br><em>Модели</em></td>
<td align="center"><img src="resources/screenshot/ru/settings.png" alt="Settings"><br><em>Настройки</em></td>
</tr>
</table>
## Почему ClawX
Создание AI-агентов не должно требовать владения командной строкой. Философия ClawX проста: **мощные технологии заслуживают интерфейса, который уважает ваше время.**
Создание AI-агентов не должно требовать владения командной строкой. Философия ClawX проста: **мощные технологии заслуживают интерфейса, который уважает ваше время.** ClawX построен непосредственно на официальном ядре **OpenClaw**. Вместо отдельной установки среда выполнения встроена в приложение, что обеспечивает бесшовный опыт «всё включено». Мы поддерживаем тесное соответствие с upstream-проектом OpenClaw, чтобы вы всегда имели доступ к официальным новейшим возможностям, улучшениям стабильности и совместимости с экосистемой.
| Проблема | Решение ClawX |
|----------|---------------|
| Сложная настройка через CLI | Установка в один клик с мастером настройки |
| Редактирование конфигурационных файлов | Визуальные настройки с проверкой в реальном времени |
| Управление процессами | Автоматическое управление жизненным циклом шлюза |
| Конфигурационные файлы | Визуальные настройки с проверкой в реальном времени |
| Управление процессами | Автоматическое управление жизненным циклом Gateway |
| Обновления приложения | Проверка обновлений при запуске с запросом перед скачиванием или установкой |
| Несколько AI-провайдеров | Единая панель настройки провайдеров |
| Установка навыков/плагинов | Встроенный маркетплейс и управление навыками |
| Установка навыков/плагинов | Локальное управление навыками с опциональным маркетплейсом от расширения |
### OpenClaw внутри
### Возможности
ClawX построен непосредственно на официальном ядре **OpenClaw**. Вместо отдельной установки мы встраиваем среду выполнения в приложение для бесшовного опыта "всё включено".
- **🎯 Нулевой порог настройки**: Весь процесс выполняется через интуитивный графический интерфейс — без терминальных команд, YAML-файлов и поиска переменных окружения.
- **💬 Интеллектуальный интерфейс чата**: Несколько контекстов и история разговоров, потоковый Markdown с подсветкой синтаксиса, разбором CJK, таблицами и формулами KaTeX, прямая маршрутизация через `@agent`, встроенные карточки `/skill`, рабочие пространства с приоритетом и предпросмотр только для чтения Markdown, `.docx`, `.pptx` и локального HTML.
- **📡 Управление несколькими каналами**: Настраивайте и отслеживайте независимые AI-каналы с несколькими аккаунтами, привязкой агента к аккаунту, переключением аккаунта по умолчанию и встроенным официальным плагином личного WeChat от Tencent.
- **⏰ Автоматизация по расписанию**: Создавайте повторяющиеся или одноразовые расписания, вставляйте навыки в запланированные запросы и доставляйте результаты во внешние каналы.
- **🧩 Расширяемая система навыков**: Управляйте навыками локально без зависимости от Gateway, обнаруживайте навыки из нескольких источников OpenClaw и используйте встроенные навыки обработки документов для `pdf`, `xlsx`, `docx` и `pptx`.
- **🔐 Безопасная интеграция провайдеров**: Подключайте OpenAI, Anthropic, Z.AI / GLM и другие провайдеры; учётные данные хранятся в нативном системном хранилище ключей. Поддерживаются OAuth, пользовательские провайдеры, эндпоинты генерации изображений и совместимые резервные проверки.
- **🌙 Адаптивные темы**: Выбирайте светлую, тёмную или синхронизированную с системой тему.
- **🚀 Управление автозапуском**: Включите **Запускать при старте системы** в разделе **Настройки → Общие**.
- **🔔 Уведомления об обновлениях**: Проверяйте новые версии при запуске и сами решайте, скачивать или устанавливать обновление.
Мы стремимся поддерживать строгое соответствие с проектом OpenClaw, чтобы вы всегда имели доступ к новейшим возможностям, улучшениям стабильности и совместимости с экосистемой.
> Полное описание возможностей доступно в [docs/ru-RU/features.md](docs/ru-RU/features.md).
---
### Типичные сценарии использования
## Возможности
### 🎯 Нулевой порог настройки
Весь процесс — от установки до первого взаимодействия с AI — выполняется через интуитивный графический интерфейс. Без терминальных команд, без YAML-файлов, без поиска переменных окружения.
### 💬 Интеллектуальный интерфейс чата
Общайтесь с AI-агентами через современный чат. Поддержка нескольких контекстов разговора, истории сообщений, рендеринга Markdown (включая таблицы GitHub-flavored и математические формулы LaTeX через KaTeX: `$строчные$`, `$$блочные$$`, `\(строчные\)` и `\[блочные\]`) и прямая маршрутизация через `@agent` в главном поле ввода для мультиагентных конфигураций.
Навыки, вставляемые из поля ввода, отображаются как чипы `/skill-name`; нажмите на чип, чтобы открыть боковую панель предпросмотра и прочитать `SKILL.md` соответствующего навыка.
При выборе другого агента через `@agent` ClawX переключается непосредственно в контекст этого агента вместо ретрансляции через агента по умолчанию. Рабочие пространства агентов по умолчанию разделены, но более строгая изоляция зависит от настроек песочницы OpenClaw.
Каждый агент может переопределить свои настройки `provider/model`; агенты без переопределения продолжают наследовать глобальную модель по умолчанию.
### 📡 Управление несколькими каналами
Настраивайте и отслеживайте несколько AI-каналов одновременно. Каждый канал работает независимо, позволяя запускать специализированных агентов для разных задач.
Каждый канал теперь поддерживает несколько учётных записей, привязку агента к учётной записи и переключение канала по умолчанию прямо на странице Каналы.
Для пользовательских идентификаторов учётных записей каналов ClawX требует совместимый с OpenClaw канонический формат (`[a-z0-9_-]`, строчные буквы, максимум 64 символа, должен начинаться с буквы или цифры) для предотвращения ошибок маршрутизации.
ClawX также включает официальный плагин личного WeChat от Tencent, позволяя подключить WeChat напрямую со страницы Каналы через встроенный QR-код.
### ⏰ Автоматизация по расписанию
Планируйте автоматический запуск AI-задач. Определяйте триггеры, устанавливайте интервалы и позволяйте AI-агентам работать круглосуточно без ручного вмешательства.
На странице Cron теперь можно настроить внешнюю доставку непосредственно в форме задачи с отдельными селекторами учётной записи отправителя и цели получателя. Для поддерживаемых каналов цели получателей автоматически обнаруживаются из каталогов каналов или известной истории сессий, поэтому больше не нужно редактировать `jobs.json` вручную.
### 🧩 Расширяемая система навыков
Расширяйте возможности AI-агентов готовыми навыками. Просматривайте, устанавливайте и управляйте навыками через встроенную панель — менеджеры пакетов не нужны.
ClawX также предварительно упаковывает полные навыки обработки документов (`pdf`, `xlsx`, `docx`, `pptx`), автоматически развёртывает их в управляемый каталог навыков (по умолчанию `~/.openclaw/skills`) при запуске и включает по умолчанию при первой установке. Дополнительные упакованные навыки (`find-skills`, `self-improving-agent`, `tavily-search`) также включены по умолчанию; если необходимые API-ключи отсутствуют, OpenClaw покажет ошибки конфигурации во время выполнения.
На странице Навыки отображаются навыки из нескольких источников OpenClaw (управляемый каталог, workspace и дополнительные каталоги навыков), а также показывается фактическое расположение каждого навыка для прямого открытия папки.
Переменные окружения для встроенных поисковых навыков:
- `TAVILY_API_KEY` для `tavily-search` (OAuth также может поддерживаться вышестоящей средой выполнения)
- `find-skills` и `self-improving-agent` не требуют API-ключей
### 🔐 Безопасная интеграция провайдеров
Подключайтесь к нескольким AI-провайдерам (OpenAI, Anthropic и др.) с учётными данными, безопасно хранящимися в системной связке ключей. OpenAI поддерживает как API-ключи, так и OAuth через браузер (подписка Codex).
Для провайдеров **Custom**, используемых с OpenAI-совместимыми шлюзами, вы можете установить пользовательский `User-Agent` в **Настройки → AI Провайдеры → Редактировать провайдера** для совместимости с чувствительными эндпоинтами.
Когда совместимый шлюз отклоняет `/models` по причинам, не связанным с аутентификацией, ClawX автоматически переключается на легковесный зонд `/chat/completions` или `/responses` при проверке API-ключа.
### 🌙 Адаптивные темы
Светлая тема, тёмная тема или синхронизация с системой. ClawX автоматически адаптируется к вашим предпочтениям.
### 🚀 Управление автозапуском
В **Настройки → Общие** вы можете включить **Запускать при старте системы**, чтобы ClawX автоматически запускался после входа в систему.
---
- **🤖 Персональный AI-ассистент**: Настройте универсального AI-агента для ответов на вопросы, составления писем, резюмирования документов и помощи с повседневными задачами через чистый десктопный интерфейс.
- **📊 Автоматизированный мониторинг**: Планируйте агентов для отслеживания новостных лент, цен или определённых событий и доставляйте результаты в предпочитаемый канал уведомлений.
- **💻 Производительность разработчика**: Интегрируйте AI в рабочий процесс разработки для проверки кода, генерации документации и автоматизации повторяющихся задач.
- **🔄 Автоматизация рабочих процессов**: Объединяйте несколько навыков в визуальные конвейеры, которые обрабатывают данные, преобразуют контент и запускают действия.
## Быстрый старт
@@ -168,255 +125,71 @@ pnpm dev
### Первый запуск
При первом запуске ClawX **Мастер настройки** проведёт вас через:
При первом запуске ClawX **Мастер настройки** проведёт вас через следующие шаги:
1. **Язык и регион** — настройка предпочтительного языка и региона
2. **AI-провайдер** — добавление провайдеров с API-ключами или OAuth (для провайдеров, поддерживающих вход через браузер/устройство)
1. **Язык и регион** — настройка предпочитаемой локали
2. **AI-провайдер** — добавление провайдеров с API-ключами или OAuth для провайдеров, поддерживающих вход через браузер или устройство
3. **Пакеты навыков** — выбор предустановленных навыков для распространённых сценариев
4. **Проверка** — тестирование конфигурации перед входом в основной интерфейс
Мастер предварительно выбирает системный язык, если он поддерживается, иначе переключается на английский.
> Примечание о веб-поиске: ClawX отключает универсальный инструмент OpenClaw `web_search` на уровнях политик агента и Gateway. Это также относится к поиску Moonshot (Kimi); управляемая автоматизация браузера и `web_fetch` остаются доступными.
>
> Примечание о внутренних инструментах: ClawX также отключает для агентов `gateway`, `nodes`, `create_goal`, `get_goal` и `update_goal` на обоих уровнях политик. RPC Gateway самого приложения ClawX, а также инструменты сообщений, оркестрации сессий и обнаружения агентов остаются доступными.
### Настройки прокси
ClawX включает встроенные настройки прокси для сред, где Electron, шлюз OpenClaw или каналы вроде Telegram должны выходить в интернет через локальный прокси-клиент.
ClawX включает встроенные настройки прокси для Electron, OpenClaw Gateway и таких каналов, как Telegram, которым требуется доступ в интернет через локальный прокси-клиент.
Откройте **Настройки → Шлюз → Прокси** и настройте:
Откройте **Настройки → Gateway → Прокси**, чтобы настроить прокси по умолчанию, правила обхода и дополнительные переопределения HTTP, HTTPS и `ALL_PROXY` / SOCKS в режиме разработчика. Пример локального адреса: `http://127.0.0.1:7890`.
- **Прокси-сервер**: прокси по умолчанию для всех запросов
- **Правила обхода**: хосты, которые должны подключаться напрямую, разделённые точкой с запятой, запятыми или новыми строками
- В **Режиме разработчика** можно дополнительно переопределить:
- **HTTP Прокси**
- **HTTPS Прокси**
- **ALL_PROXY / SOCKS**
Рекомендуемые примеры локальных настроек:
```text
Прокси-сервер: http://127.0.0.1:7890
```
Примечания:
- Значение `host:port` рассматривается как HTTP.
- Если расширенные поля прокси пусты, ClawX использует `Прокси-сервер`.
- Сохранение настроек прокси немедленно повторно применяет сеть Electron и автоматически перезапускает шлюз.
- ClawX также синхронизирует прокси с конфигурацией канала Telegram в OpenClaw, когда Telegram включён.
- При перезапуске шлюза существующий прокси канала Telegram сохраняется, если прокси ClawX отключен.
- Чтобы явно очистить прокси Telegram из конфигурации OpenClaw, сохраните настройки прокси с отключенным прокси.
- В **Настройки → Дополнительно → Разработчик** можно запустить **OpenClaw Doctor** для выполнения `openclaw doctor --json` и просмотра диагностического вывода, не покидая приложение.
- В упакованных сборках Windows встроенный `openclaw` CLI/TUI запускается через поставляемый `node.exe` для стабильного поведения ввода в терминале.
---
> Подробности о резервном поведении прокси, синхронизации с Telegram и **OpenClaw Doctor** см. в [docs/ru-RU/proxy-settings.md](docs/ru-RU/proxy-settings.md).
## Архитектура
ClawX использует **двухпроцессную архитектуру с унифицированным уровнем Host API**. Рендерер обращается к единой абстракции клиента, а Electron Main управляет выбором протокола и жизненным циклом процессов:
ClawX использует **двухпроцессную архитектуру с унифицированным уровнем Host API**: React Renderer обращается к единой абстракции клиента, а Electron Main управляет выбором протокола, жизненным циклом Gateway и stdio bridge для ACP Chat.
```
┌─────────────────────────────────────────────────────────────────┐
│ Десктоп-приложение ClawX │
│ │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ Главный процесс Electron │ │
│ │ • Управление жизненным циклом окна и приложения │ │
│ │ • Наблюдение за процессом шлюза │ │
│ │ • Интеграция с системой (трей, уведомления, связка ключей)│ │
│ │ • Оркестрация автообновлений │ │
│ └────────────────────────────────────────────────────────────┘ │
│ │ │
│ IPC (авторитетная плоскость управления) │
│ ▼ │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ Процесс рендерера React │ │
│ │ • Современный UI на компонентах (React 19) │ │
│ │ • Управление состоянием с Zustand │ │
│ │ • Унифицированные вызовы host-api/api-client │ │
│ │ • Рендеринг Markdown │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬──────────────────────────────────┘
Стратегия транспорта, управляемая Main
(Сначала WS, затем HTTP, затем IPC)
┌──────────────────────────────────────────────────────────────────┐
│ Host API и прокси-уровень Main │
│ │
│ • hostapi:fetch (прокси Main, избегает CORS в dev/prod) │
│ • gateway:httpProxy (Рендерер не вызывает Gateway HTTP напрямую)│
│ • Унифицированное отображение ошибок и повторные попытки │
└──────────────────────────────┬───────────────────────────────────┘
Резерв WS / HTTP / IPC
┌─────────────────────────────────────────────────────────────────┐
│ Шлюз OpenClaw │
│ │
│ • Среда выполнения AI-агентов и оркестрация │
│ • Управление каналами сообщений │
│ • Среда выполнения навыков/плагинов │
│ • Уровень абстракции провайдеров │
└─────────────────────────────────────────────────────────────────┘
```
- **Модель процессов**: Electron Main управляет окном, наблюдением за Gateway, системной интеграцией и обновлениями; OpenClaw Gateway предоставляет возможности AI-оркестрации, каналов и навыков; Renderer не обращается к локальным эндпоинтам напрямую.
- **Доставка конфигурации**: изменения среды выполнения используют авторитетный снимок `config.set`, поэтому обычные изменения провайдера, агента, навыка и модели не заменяют процесс Gateway; учётные данные обновляются без перезапуска через `secrets.reload`, а защищённое восстановление запускается после четырёх последовательных пропусков heartbeat.
- **ACP Chat**: Chat UI взаимодействует с OpenClaw через [ACP (Agent Client Protocol)](https://agentclientprotocol.com), обеспечивая относительно стабильную поверхность чат-протокола поверх часто итерируемого OpenClaw. ACP работает через stdio bridge под управлением Main, поддерживая аутентифицированное воспроизведение истории после перезагрузки конфигурации, потоковую выдачу при навигации, а также медиа, вложения и файловые операции, проверенные Main. Если защищённый перезапуск Gateway прерывает уже принятый ход, исправленная среда OpenClaw явно связывает восстановительный run с исходным ACP prompt, чтобы последующий текст и активность инструментов продолжались в том же ходе в памяти; последующее воспроизведение истории восстанавливает сохранённые границы инструментов как нативные обновления ACP.
- **Принципы проектирования**: единая точка входа фронтенда, транспорт под управлением Main, корректное восстановление с переподключением/таймаутом/повтором, безопасное хранение и границы, защищённые от CORS.
### Принципы проектирования
- **Изоляция процессов**: Среда выполнения AI работает в отдельном процессе, обеспечивая отзывчивость UI даже при тяжёлых вычислениях
- **Единая точка входа для фронтенда**: Запросы рендерера проходят через host-api/api-client; детали протокола скрыты за стабильным интерфейсом
- **Владение транспортом в Main**: Electron Main управляет использованием WS/HTTP и откатом к IPC для надёжности
- **Корректное восстановление**: Встроенная логика переподключения, таймаутов и отката автоматически обрабатывает временные сбои
- **Безопасное хранение**: API-ключи и конфиденциальные данные используют нативные механизмы безопасного хранения ОС
- **Безопасность CORS**: Локальный HTTP-доступ проксируется через Main, предотвращая CORS-проблемы на стороне рендерера
### Модель процессов и устранение неполадок шлюза
- ClawX — это приложение Electron, поэтому **один экземпляр приложения обычно отображается как несколько процессов ОС** (main/renderer/zygote/utility). Это нормально.
- Защита единственного экземпляра использует блокировку Electron плюс локальный файл блокировки процессов, предотвращая дублирование запуска приложения в средах с нестабильным IPC/сессионной шиной.
- При последовательных обновлениях смешанные старые/новые версии могут иметь асимметричное поведение защиты. Для лучшей надёжности обновите все десктоп-клиенты до одной версии.
- Слушатель шлюза OpenClaw должен быть **единственным владельцем**: только один процесс должен слушать `127.0.0.1:18789`.
- Для проверки активного слушателя:
- macOS/Linux: `lsof -nP -iTCP:18789 -sTCP:LISTEN`
- Windows (PowerShell): `Get-NetTCPConnection -LocalPort 18789 -State Listen`
- Нажатие кнопки закрытия окна (`X`) скрывает ClawX в трей; это **не** полностью закрывает приложение. Используйте меню трея **Quit ClawX** для полного завершения.
---
## Варианты использования
### 🤖 Персональный AI-ассистент
Настройте универсального AI-агента, который может отвечать на вопросы, составлять письма, резюмировать документы и помогать с повседневными задачами — всё через чистый десктоп-интерфейс.
### 📊 Автоматизированный мониторинг
Настройте запланированных агентов для отслеживания новостных лент, цен или определённых событий. Результаты доставляются в ваш предпочтительный канал уведомлений.
### 💻 Производительность разработчика
Интегрируйте AI в рабочий процесс разработки. Используйте агентов для проверки кода, генерации документации или автоматизации повторяющихся задач кодирования.
### 🔄 Автоматизация рабочих процессов
Связывайте несколько навыков для создания сложных конвейеров автоматизации. Обрабатывайте данные, преобразовывайте контент и запускайте действия — всё визуально оркестрируется.
---
> Схема процессов, координация конфигурации, семантика файловых операций ACP и устранение неполадок Gateway описаны в [docs/ru-RU/architecture.md](docs/ru-RU/architecture.md).
## Разработка
### Требования
- **Node.js**: 22+ (рекомендуется LTS)
- **Менеджер пакетов**: pnpm 9+ (рекомендуется) или npm
- **Node.js**: 22.22.3+, 24.15.0+ или 25.9.0+ в пределах соответствующей основной версии (рекомендуется Node 24 LTS)
- **Менеджер пакетов**: pnpm 9+ (npm также поддерживается)
- **Linux (Ubuntu/Debian)**: перед запуском Electron установите необходимые системные библиотеки; см. [docs/ru-RU/development.md](docs/ru-RU/development.md)
### Структура проекта
```
ClawX/
├── electron/ # Главный процесс Electron
│ ├── api/ # Маршрутизатор API и обработчики Main
│ │ └── routes/ # Модули маршрутов RPC/HTTP прокси
│ ├── services/ # Службы провайдеров, секретов и среды выполнения
│ │ ├── providers/ # Логика синхронизации моделей provider/account
│ │ └── secrets/ # Связка ключей ОС и хранилище секретов
│ ├── shared/ # Общие схемы провайдеров и константы
│ │ └── providers/
│ ├── main/ # Точка входа приложения, окна, регистрация IPC
│ ├── gateway/ # Менеджер процесса шлюза OpenClaw
│ ├── preload/ # Безопасный IPC-мост
│ └── utils/ # Утилиты (хранилище, аутентификация, пути)
├── src/ # Процесс рендерера React
│ ├── lib/ # Унифицированный фронтенд API и модель ошибок
│ ├── stores/ # Хранилища Zustand (settings/chat/gateway)
│ ├── components/ # Переиспользуемые UI-компоненты
│ ├── pages/ # Setup/Dashboard/Chat/Channels/Skills/Cron/Settings
│ ├── i18n/ # Ресурсы локализации
│ └── types/ # Определения типов TypeScript
├── tests/
│ ├── e2e/ # Сквозные дымовые тесты Playwright Electron
│ └── unit/ # Модульные/интеграционные тесты Vitest
├── resources/ # Статические ресуры (иконки, изображения)
└── scripts/ # Скрипты сборки и утилит
```
### Доступные команды
### Основные команды
```bash
# Разработка
pnpm run init # Установить зависимости + скачать uv
pnpm dev # Запуск с горячей перезагрузкой (автоподготовка упакованных навыков при отсутствии)
# Качество кода
pnpm lint # Запустить ESLint
pnpm typecheck # Проверка типов TypeScript
# Тестирование
pnpm test # Запустить модульные тесты
pnpm run test:e2e # Запустить E2E дымовые тесты Electron с Playwright
pnpm run test:e2e:headed # Запустить E2E тесты Electron с видимым окном
pnpm run comms:replay # Вычислить метрики повторного воспроизведения коммуникаций
pnpm run comms:baseline # Обновить базовый снимок коммуникаций
pnpm run comms:compare # Сравнить метрики воспроизведения с базовыми порогами
# Сборка и упаковка
pnpm run build:vite # Собрать только фронтенд
pnpm build # Полная production-сборка (с ресурсами упаковки)
pnpm package # Упаковать для текущей платформы (включает предустановленные навыки)
pnpm package:mac # Упаковать для macOS
pnpm package:win # Упаковать для Windows
pnpm package:linux # Упаковать для Linux
pnpm run init # Установить зависимости и скачать встроенные среды выполнения
pnpm dev # Запустить режим разработки с горячей перезагрузкой
pnpm lint # Запустить ESLint
pnpm typecheck # Проверить типы TypeScript
pnpm test # Запустить модульные тесты
pnpm run test:e2e # Запустить дымовые E2E-тесты Electron
pnpm build # Выполнить полную production-сборку
pnpm package # Упаковать для текущей платформы (:mac / :win / :linux)
```
На headless Linux запускайте тесты Electron под сервером отображения, например `xvfb-run -a pnpm run test:e2e`.
### Проверка регрессии коммуникаций
Когда PR изменяет пути коммуникации (события шлюза, поток отправки/получения чата, доставка каналов или откат транспорта), запустите:
```bash
pnpm run comms:replay
pnpm run comms:compare
```
`comms-regression` в CI проверяет обязательные сценарии и пороги.
### E2E-тесты Electron
Сьют Playwright Electron запускает упакованный рендерер и главный процесс из `dist/` и `dist-electron/`, поэтому не требует предварительного ручного запуска `pnpm dev`.
`pnpm run test:e2e` автоматически:
- собирает рендерер и пакеты Electron с `pnpm run build:vite`
- запускает Electron в изолированном режиме E2E с временным `HOME`
- использует временный каталог `userData` ClawX
- пропускает тяжёлые побочные эффекты запуска, такие как автозапуск шлюза, установку упакованных навыков, создание трея и автоустановку CLI
Первые два базовых спецификации покрывают:
- видимость мастера настройки при первом запуске на чистом профиле
- пропуск настройки и навигация на страницу Models внутри приложения Electron
Добавляйте будущие потоки Electron в `tests/e2e/` и переиспользуйте общий fixture в `tests/e2e/fixtures/electron.ts`.
### Технологический стек
| Уровень | Технология |
|----------------|-------------------------------|
| Среда выполнения | Electron 40+ |
| UI-фреймворк | React 19 + TypeScript |
| Стилизация | Tailwind CSS + shadcn/ui |
| Состояние | Zustand |
| Сборка | Vite + electron-builder |
| Тестирование | Vitest + Playwright |
| Анимация | Framer Motion |
| Иконки | Lucide React |
---
> Структура проекта, полный список команд, политика параллельности E2E, диагностика производительности, проверки регрессий коммуникаций и технологический стек описаны в [docs/ru-RU/development.md](docs/ru-RU/development.md).
## Участие
Мы приветствуем вклад сообщества! Исправления багов, новые функции, улучшения документации или переводы — каждый вклад делает ClawX лучше.
Мы приветствуем вклад сообщества! Исправления ошибок, новые функции, улучшения документации и переводы помогают сделать ClawX лучше.
### Как внести вклад
1. **Сделайте форк** репозитория
2. **Создайте** ветку функции (`git checkout -b feature/amazing-feature`)
3. **Зафиксируйте** изменения с понятными сообщениями
4. **Отправьте** в свою ветку
4. **Отправьте** изменения в свою ветку
5. **Откройте** Pull Request
### Руководящие принципы
@@ -426,54 +199,44 @@ pnpm run comms:compare
- Обновляйте документацию по мере необходимости
- Держите коммиты атомарными и описательными
---
## Благодарности
ClawX построен на плечах отличных проектов с открытым исходным кодом:
ClawX построен на основе следующих отличных проектов с открытым исходным кодом:
- [OpenClaw](https://github.com/OpenClaw) Среда выполнения AI-агентов
- [Electron](https://www.electronjs.org/) Кроссплатформенный десктоп-фреймворк
- [React](https://react.dev/) Библиотека UI-компонентов
- [shadcn/ui](https://ui.shadcn.com/) Красиво спроектированные компоненты
- [Zustand](https://github.com/pmndrs/zustand) Легковесное управление состоянием
---
- [OpenClaw](https://github.com/OpenClaw) - Среда выполнения AI-агентов
- [Electron](https://www.electronjs.org/) - Кроссплатформенный десктоп-фреймворк
- [React](https://react.dev/) - Библиотека UI-компонентов
- [shadcn/ui](https://ui.shadcn.com/) - Красиво спроектированные компоненты
- [Zustand](https://github.com/pmndrs/zustand) - Лёгкое управление состоянием
## Сообщество
Присоединяйтесь к нашему сообществу, чтобы общаться с другими пользователями, получать поддержку и делиться опытом.
| WeChat Enterprise | Feishu Group | Discord |
| WeChat Enterprise | Группа Feishu | Discord |
| :---: | :---: | :---: |
| <img src="src/assets/community/wecom-qr.png" width="150" alt="WeChat QR Code" /> | <img src="src/assets/community/feishu-qr.png" width="150" alt="Feishu QR Code" /> | <img src="src/assets/community/20260212-185822.png" width="150" alt="Discord QR Code" /> |
### Партнёрская программа ClawX 🚀
### Партнёрская программа ClawX
Мы запускаем Партнёрскую программу ClawX и ищем партнёров, которые могут помочь представить ClawX большему числу клиентов, особенно тем, у кого есть потребности в кастомных AI-агентах или автоматизации.
Мы запускаем Партнёрскую программу ClawX и ищем партнёров, которые помогут представить ClawX большему числу клиентов, особенно клиентам с потребностями в кастомных AI-агентах или автоматизации.
Партнёры помогают связывать нас с потенциальными пользователями и проектами, а команда ClawX предоставляет полную техническую поддержку, кастомизацию и интеграцию.
Партнёры помогают связывать нас с потенциальными пользователями и проектами, а команда ClawX предоставляет полную техническую поддержку, кастомизацию и интеграцию. Если вы работаете с клиентами, заинтересованными в AI-инструментах или автоматизации, мы будем рады сотрудничеству.
Если вы работаете с клиентами, заинтересованными в AI-инструментах или автоматизации, мы будем рады сотрудничеству.
Напишите нам в DM или на [public@valuecell.ai](mailto:public@valuecell.ai) для получения дополнительной информации.
---
Напишите нам в DM или на [public@valuecell.ai](mailto:public@valuecell.ai), чтобы узнать больше.
## История звёзд
<p align="center">
<img src="https://api.star-history.com/svg?repos=ValueCell-ai/ClawX&type=Date" alt="Star History Chart" />
<img src="https://api.star-history.com/svg?repos=ValueCell-ai/ClawX&type=Date" alt="Star History Chart" />
</p>
---
## Лицензия
ClawX выпускается под [лицензией MIT](LICENSE). Вы можете свободно использовать, модифицировать и распространять это программное обеспечение.
ClawX выпускается под [лицензией MIT](LICENSE). Вы можете свободно использовать, изменять и распространять это программное обеспечение.
---
<hr>
<p align="center">
<sub>Создано с ❤️ командой ValueCell</sub>
<sub>Создано с ❤️ командой ValueCell</sub>
</p>
+62 -287
View File
@@ -10,7 +10,6 @@
</p>
<p align="center">
<a href="#功能特性">功能特性</a> •
<a href="#为什么选择-clawx">为什么选择 ClawX</a> •
<a href="#快速上手">快速上手</a> •
<a href="#系统架构">系统架构</a> •
@@ -45,39 +44,25 @@ ClawX 预置了最佳实践的模型供应商配置,原生支持 Windows 平
<p align="center"><strong style="font-size:1.1em; text-decoration: underline;">如需完整的企业版、专属服务支持或面向您业务场景的定制化落地辅导,请联系 <a href="mailto:public@valuecell.ai">public@valuecell.ai</a>。</strong></p>
---
## 截图预览
<p align="center">
<img src="resources/screenshot/zh/chat.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/zh/cron.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/zh/skills.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/zh/channels.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/zh/models.png" style="width: 100%; height: auto;">
</p>
<p align="center">
<img src="resources/screenshot/zh/settings.png" style="width: 100%; height: auto;">
</p>
---
<table>
<tr>
<td align="center"><img src="resources/screenshot/zh/chat.png" alt="Chat"><br><em>聊天界面</em></td>
<td align="center"><img src="resources/screenshot/zh/cron.png" alt="Cron"><br><em>定时任务</em></td>
</tr>
<tr>
<td align="center"><img src="resources/screenshot/zh/skills.png" alt="Skills"><br><em>技能管理</em></td>
<td align="center"><img src="resources/screenshot/zh/channels.png" alt="Channels"><br><em>频道管理</em></td>
</tr>
<tr>
<td align="center"><img src="resources/screenshot/zh/models.png" alt="Models"><br><em>模型配置</em></td>
<td align="center"><img src="resources/screenshot/zh/settings.png" alt="Settings"><br><em>设置</em></td>
</tr>
</table>
## 为什么选择 ClawX
构建 AI 智能体不应该需要精通命令行。ClawX 的设计理念很简单:**强大的技术值得拥有一个尊重用户时间的界面**
构建 AI 智能体不应该需要精通命令行。ClawX 的设计理念很简单:**强大的技术值得拥有一个尊重用户时间的界面**。ClawX 直接基于官方 OpenClaw 核心构建。无需单独安装,我们将运行时嵌入应用内部,提供开箱即用的无缝体验,并致力于与上游 OpenClaw 项目保持严格同步,确保你始终可以使用官方发布的最新功能、稳定性改进和生态兼容性。
| 痛点 | ClawX 解决方案 |
|------|----------------|
@@ -88,63 +73,26 @@ ClawX 预置了最佳实践的模型供应商配置,原生支持 Windows 平
| 多 AI 供应商切换 | 统一的供应商配置面板 |
| 技能/插件安装复杂 | 内置技能市场与管理界面 |
### 内置 OpenClaw 核心
### 功能特性
ClawX 直接基于官方 **OpenClaw** 核心构建。无需单独安装,我们将运行时嵌入应用内部,提供开箱即用的无缝体验
- **🎯 零配置门槛**:从安装到第一次 AI 对话,全程指引式图形界面,无需终端命令、YAML 配置或环境变量
- **💬 智能聊天界面**:多会话上下文与历史记录,流式 Markdown 渲染(语法高亮、CJK 排版、表格、KaTeX 公式)、`@agent` 直接路由与 `/技能` 内联卡片,工作空间优先的会话侧边栏,以及 Markdown、`.docx``.pptx` 和本地 HTML 的只读预览。
- **📡 多频道管理**:同时配置和监控多个 AI 频道,每个频道独立运行并支持多账号;内置腾讯官方个人微信渠道插件。
- **⏰ 定时任务自动化**:可视化定义触发器与时间间隔,让 AI 智能体 7×24 小时自动运行;支持周期(每小时/每天/工作日/每周/自定义 cron)与单次执行,并可将结果自动投递到外部频道。
- **🧩 可扩展技能系统**:本地优先的技能管理,扫描托管与 workspace 技能目录,无需依赖 Gateway 即可启用或停用技能;预装文档处理技能(`pdf``xlsx``docx``pptx`)。
- **🔐 安全的供应商集成**:支持 OpenAI、Anthropic、Z.AI / GLM 等供应商,凭证经系统原生密钥链安全存储;提供自定义 Provider、OAuth 登录、图像生成端点与兼容网关的降级探测。
- **🌙 自适应主题**:支持浅色、深色与跟随系统主题。
- **🚀 开机启动控制**:在 设置 → 通用 中开启开机自动启动。
- **🔔 更新提示**:启动时自动检查新版本,由你决定是否下载或安装更新。
我们致力于与上游 OpenClaw 项目保持严格同步,确保你始终可以使用官方发布的最新功能、稳定性改进和生态兼容性
> 对于功能细节的完整说明,请参阅 [docs/zh-CN/features.md](docs/zh-CN/features.md)
打开开发者模式后,侧边栏还会提供原生 Dreams 页面,可在 ClawX 内查看 OpenClaw 记忆回顾、梦境日记,并执行基础维护操作;需要更深诊断时仍可从该页面打开完整 OpenClaw Dreams UI。
### 典型使用场景
---
## 功能特性
### 🎯 零配置门槛
从安装到第一次 AI 对话,全程通过直观的图形界面完成。无需终端命令,无需 YAML 文件,无需到处寻找环境变量。
### 💬 智能聊天界面
通过现代化的聊天体验与 AI 智能体交互。支持多会话上下文、消息历史记录、Markdown 富文本渲染(包括 GitHub 风格表格以及由 KaTeX 渲染的 LaTeX 数学公式:`$行内$``$$块级$$``\(行内\)``\[块级\]`),以及在多 Agent 场景下通过主输入框中的 `@agent` 直接路由到目标智能体。
从输入框插入的技能会以 `/技能名` 卡片形式显示;点击卡片可在右侧预览栏打开并阅读该技能的 `SKILL.md`
当你使用 `@agent` 选择其他智能体时,ClawX 会直接切换到该智能体自己的对话上下文,而不是经过默认智能体转发。各 Agent 工作区默认彼此分离,但更强的运行时隔离仍取决于 OpenClaw 的 sandbox 配置。
每个 Agent 还可以单独覆盖自己的 `provider/model` 运行时设置;未覆盖的 Agent 会继续继承全局默认模型。
### 📡 多频道管理
同时配置和监控多个 AI 频道。每个频道独立运行,允许你为不同任务运行专门的智能体。
现在每个频道支持多个账号,并可在 Channels 页面直接完成账号绑定到 Agent 与默认账号切换。
对于自定义频道账号 ID,ClawX 现在会强制校验 OpenClaw 兼容的规范格式(`[a-z0-9_-]`、小写、最长 64 位、且必须以字母或数字开头),避免路由匹配异常。
ClawX 现在还内置了腾讯官方个人微信渠道插件,可直接在 Channels 页面通过内置二维码流程完成微信连接。
### ⏰ 定时任务自动化
调度 AI 任务自动执行。定义触发器、设置时间间隔,让 AI 智能体 7×24 小时不间断工作。
现在定时任务页面已经可以直接配置外部投递,统一拆成“发送账号”和“接收目标”两个下拉选择。对于已支持的通道,接收目标会从通道目录能力或已知会话历史中自动发现,不需要再手动修改 `jobs.json`
### 🧩 可扩展技能系统
通过预构建的技能扩展 AI 智能体的能力。集成的 Skills 页面采用“本地优先”方式:会扫描托管目录与 workspace 技能目录,并且无需依赖 Gateway 即可启用或停用技能;在企业扩展接管时,也可以显示扩展提供的 marketplace。
ClawX 还会内置预装完整的文档处理技能(`pdf``xlsx``docx``pptx`),在启动时自动部署到托管技能目录(默认 `~/.openclaw/skills`),并在首次安装时默认启用。额外预装技能(`find-skills``self-improving-agent``tavily-search`)也会默认启用;若缺少必需的 API Key,OpenClaw 会在运行时给出配置错误提示。
Skills 页面可展示来自多个 OpenClaw 来源的技能(托管目录、workspace、额外技能目录),并显示每个技能的实际路径,便于直接打开真实安装位置。对于 OpenClaw 自带的 bundled skills,社区版现在在打包产物里只保留并展示 `skill-creator`;开发模式和打包版启动时都会直接清理其它 bundled skill,同时把这些已删除 bundled skill 在 `openclaw.json` 中残留的旧配置一并移除。
重点搜索技能所需环境变量:
- `TAVILY_API_KEY`:用于 `tavily-search`(上游运行时也可能支持 OAuth
### 🔐 安全的供应商集成
连接多个 AI 供应商(OpenAI、Anthropic 等),凭证安全存储在系统原生密钥链中。OpenAI 同时支持 API Key 与浏览器 OAuthCodex 订阅)登录。
在开发者模式下,独立的“图像生成”页面支持配置 OpenAI 兼容生图端点(Base URL、API Key 和模型名,例如 `gpt-image-2`),生图请求会走专用的 `/v1/images/generations` 服务,聊天仍继续使用正常的 OpenAI Provider。
如果你通过 **自定义(CustomProvider** 对接 OpenAI-compatible 网关,可以在 **设置 → AI Providers → 编辑 Provider** 中配置自定义 `User-Agent`,以提高兼容性。
编辑或切换 Provider 时,ClawX 会保留已有的模型级能力元数据,例如 `input: ["text", "image"]`。新选择的自定义 Provider 模型会使用与 OpenClaw onboarding 一致的图片输入能力推断;未知模型默认按纯文本模型处理。
如果兼容网关的 `/models` 因非鉴权原因不可用,ClawX 会在校验 API Key 时自动降级为轻量的 `/chat/completions``/responses` 探测。
### 🌙 自适应主题
支持浅色模式、深色模式或跟随系统主题。ClawX 自动适应你的偏好设置。
### 🚀 开机启动控制
**设置 → 通用** 中,你可以开启 **开机自动启动**,让 ClawX 在系统登录后自动启动。
### 🔔 更新提示
ClawX 可以在启动时自动检查新版本。发现更新后会显示应用内提示;只有在你选择操作后,才会下载或安装更新。
---
- **🤖 个人 AI 助手**:配置一个通用 AI 智能体,可以回答问题、撰写邮件、总结文档并协助处理日常任务——全部通过简洁的桌面界面完成。
- **📊 自动化监控**:设置定时智能体来监控新闻动态、追踪价格变动或监听特定事件,结果将推送到你偏好的通知渠道。
- **💻 开发者效率工具**:将 AI 融入你的开发工作流,使用智能体进行代码审查、生成文档或自动化重复性编码任务。
- **🔄 工作流自动化**:将多个技能串联起来,创建复杂的自动化流水线——处理数据、转换内容、触发操作,全部通过可视化方式编排。
## 快速上手
@@ -160,7 +108,7 @@ ClawX 可以在启动时自动检查新版本。发现更新后会显示应用
从 [Releases](https://github.com/ValueCell-ai/ClawX/releases) 页面下载适用于你平台的最新版本。
#### 从源码构建
#### 从源码开始
```bash
# 克隆仓库
@@ -182,10 +130,10 @@ pnpm dev
3. **技能包** 选择适用于常见场景的预配置技能
4. **验证** 在进入主界面前测试你的配置
如果系统语言在支持列表中,向导会默认选中该语言;否则回退到英文
> MoonshotKimi)说明:ClawX 默认保持开启 Kimi 的 web search。
> 当配置 Moonshot 后,ClawX 也会将 OpenClaw 配置中的 Kimi web search 同步到中国区端点(`https://api.moonshot.cn/v1`
> Web search 说明:ClawX 会在 Agent 和 Gateway 两层策略中禁用 OpenClaw 的通用 `web_search` 工具
> 这也包括 Moonshot(Kimi)搜索;受管浏览器自动化和 `web_fetch` 仍然可用。
>
> 内部工具说明:ClawX 还会在两层策略中对 Agent 禁用 `gateway`、`nodes`、`create_goal`、`get_goal` 和 `update_goal`。ClawX 应用自身的 Gateway RPC 不受影响,消息、会话编排和 Agent 发现工具仍然可用
### 代理设置
@@ -193,211 +141,45 @@ ClawX 内置了代理设置,适用于需要通过本地代理客户端访问
打开 **设置 → 网关 → 代理**,配置以下内容:
- **代理服务器**:所有请求默认使用的代理
- **代理服务器**:所有请求默认使用的代理,填写例如 `http://127.0.0.1:7890`
- **绕过规则**:需要直连的主机,使用分号、逗号或换行分隔
-**开发者模式** 下,还可以单独覆盖:
- **HTTP 代理**
- **HTTPS 代理**
- **ALL_PROXY / SOCKS**
-**开发者模式** 下,还可以单独覆盖:HTTP 代理、HTTPS 代理、ALL_PROXY / SOCKS
本地代理的常见填写示例:
```text
代理服务器: http://127.0.0.1:7890
```
说明:
- 只填写 `host:port` 时,会按 HTTP 代理处理。
- 高级代理项留空时,会自动回退到“代理服务器”。
- 保存代理设置后,Electron 网络层会立即重新应用代理,并自动重启 Gateway。
- 如果启用了 TelegramClawX 还会把代理同步到 OpenClaw 的 Telegram 频道配置中。
- 当 ClawX 代理处于关闭状态时,Gateway 的常规重启会保留已有的 Telegram 频道代理配置。
- 如果你要明确清空 OpenClaw 中的 Telegram 代理,请在关闭代理后点一次“保存代理设置”。
-**设置 → 高级 → 开发者** 中,可以直接运行 **OpenClaw Doctor**,执行 `openclaw doctor --json` 并在应用内查看诊断输出。
- 在 Windows 打包版本中,内置的 `openclaw` CLI/TUI 会通过随包分发的 `node.exe` 入口运行,以保证终端输入行为稳定。
---
> 开发者模式覆盖项、Telegram 代理同步与 **OpenClaw Doctor** 等详细行为说明,请参阅 [docs/zh-CN/proxy-settings.md](docs/zh-CN/proxy-settings.md)。
## 系统架构
ClawX 采用 **双进程 + Host API 统一接入架构**。渲染进程只调用统一客户端抽象,协议选择与进程生命周期由 Electron 主进程统一管理
ClawX 采用 **双进程 + Host API 统一接入架构**:React 渲染进程只通过统一的 host-api/api-client 抽象与后端交互,协议选择、Gateway 生命周期与 ACP Chat stdio bridge 全部由 Electron 主进程统一管理
```
┌───────────────────────────────────────────────────────────────────┐
│ ClawX 桌面应用 │
│ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ Electron 主进程 │ │
│ │ • 窗口与应用生命周期管理 │ │
│ │ • 网关进程监控 │ │
│ │ • 系统集成(托盘、通知、密钥链) │ │
│ │ • 自动更新编排 │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │ │
│ │ IPC (权威控制面) │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ React 渲染进程 │ │
│ │ • 现代组件化 UI(React 19 │ │
│ │ • Zustand 状态管理 │ │
│ │ • 统一 host-api/api-client 调用 │ │
│ │ • Markdown 富文本渲染 │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬───────────────────────────────────┘
│ 类型化 IPC 请求
┌─────────────────────────────────────────────────────────────────┐
│ 主进程 Host Services 与 Gateway Manager │
│ │
│ • host:invoke 类型化服务分发 │
│ • 设置、文件、会话、技能、供应商、诊断服务 │
│ • 主进程持有 Gateway WebSocket 并负责进程监控 │
└──────────────────────────────┬──────────────────────────────────┘
│ 主进程持有 WebSocket
┌─────────────────────────────────────────────────────────────────┐
│ OpenClaw 网关 │
│ │
│ • AI 智能体运行时与编排 │
│ • 消息频道管理 │
│ • 技能/插件执行环境 │
│ • 供应商抽象层 │
└─────────────────────────────────────────────────────────────────┘
```
### 设计原则
- **进程模型**:Electron 主进程负责窗口、网关进程监控、系统集成与自动更新;OpenClaw Gateway 作为独立运行时进程提供 AI 编排、频道和技能能力;渲染层不直接访问本地端点。
- **配置交付**Gateway 运行时由 Main 使用 `config.get` / `config.set`,停止或启动中则更新解析后的 JSON5 配置;普通 Provider/Agent/Skill/模型修改不会替换进程,凭据通过 `secrets.reload` 热更新;连续 4 次心跳无响应后才会请求受生命周期保护的自动恢复。
- **ACP Chat**Chat UI 基于 ACP ([Agent Client Protocol](https://agentclientprotocol.com)) 与 OpenClaw 交互,从而在高速迭代的 OpenClaw 前找到相对稳定的聊天协议面。ACP 走 Main 持有的 stdio bridge,支持配置热重载后的历史回放认证、跨页面持续流式输出,以及由 Main 验证和加载的媒体/附件/文件活动(Changes)展示。当受保护的 Gateway 重启中断已接收的对话轮次时,补丁后的 OpenClaw 运行时会将恢复 run 显式关联到原 ACP prompt,使后续文本和工具活动继续进入同一个内存轮次;之后的历史回放也会以原生 ACP 更新恢复持久化的工具边界。
- **设计原则**:前端调用单一入口、Main 掌控传输策略、优雅恢复(重连/超时/退避)、安全存储与 CORS 安全。
- **进程隔离**:AI 运行时在独立进程中运行,确保即使在高负载计算期间 UI 也能保持响应
- **前端调用单一入口**:渲染层统一走 host-api/api-client,不感知底层协议细节
- **主进程掌控传输策略**Gateway WebSocket 只由 Electron Main 持有,渲染进程通过类型化 IPC 调用 Main
- **扩展 IPC 贡献点**:主进程扩展通过类型化 IPC 注册表贡献 host-api action,而不是挂载 HTTP route
- **优雅恢复**:内置重连、超时、退避逻辑,自动处理瞬时故障
- **安全存储**:API 密钥和敏感数据利用操作系统原生的安全存储机制
- **CORS 安全**:渲染进程不直接请求本地 Gateway 或 Host API HTTP 端点
### 进程模型与 Gateway 排障
- ClawX 基于 Electron,**单个应用实例出现多个系统进程是正常现象**main/renderer/zygote/utility)。
- 单实例保护同时使用 Electron 自带锁与本地进程文件锁回退机制,可在桌面会话总线异常时避免重复启动。
- 滚动升级期间若新旧版本混跑,单实例保护仍可能出现不对称行为。为保证稳定性,建议桌面客户端尽量统一升级到同一版本。
- 但 OpenClaw Gateway 监听应始终保持**单实例**:`127.0.0.1:18789` 只能有一个监听者。
- Gateway readiness 以 OpenClaw 的 `system-presence``health``status` 等核心信号为准;memory、Dreams 或频道失败会显示为能力降级,而不是全局 Gateway 故障。
- 可用以下命令确认监听进程:
- macOS/Linux`lsof -nP -iTCP:18789 -sTCP:LISTEN`
- WindowsPowerShell):`Get-NetTCPConnection -LocalPort 18789 -State Listen`
- 点击窗口关闭按钮(`X`)默认只是最小化到托盘,并不会完全退出应用。请在托盘菜单中选择 **Quit ClawX** 执行完整退出。
---
## 使用场景
### 🤖 个人 AI 助手
配置一个通用 AI 智能体,可以回答问题、撰写邮件、总结文档并协助处理日常任务——全部通过简洁的桌面界面完成。
### 📊 自动化监控
设置定时智能体来监控新闻动态、追踪价格变动或监听特定事件。结果将推送到你偏好的通知渠道。
### 💻 开发者效率工具
将 AI 融入你的开发工作流。使用智能体进行代码审查、生成文档或自动化重复性编码任务。
### 🔄 工作流自动化
将多个技能串联起来,创建复杂的自动化流水线。处理数据、转换内容、触发操作——全部通过可视化方式编排。
---
> 完整架构说明(进程图、配置协调、ACP 文件活动语义与 Gateway 排障)请参阅 [docs/zh-CN/architecture.md](docs/zh-CN/architecture.md)。
## 开发指南
### 前置要求
- **Node.js**22+(推荐 LTS 版本)
- **包管理器**pnpm 9+(推荐)或 npm
- **LinuxUbuntu/Debian**:运行 Electron 前,请先安装所需系统库
```bash
sudo apt-get install -y libnss3 libgtk-3-0 libxss1 libxtst6 libatspi2.0-0 libnotify4 xdg-utils
```
在 Ubuntu 24.04+ 上,部分软件包使用 `t64` 后缀,运行上述命令后 `apt` 会自动选择正确版本。
- **Node.js**22.22.3+ / 24.15.0+(推荐) / 25.9.0+
- **包管理器**pnpm 9+
- **LinuxUbuntu/Debian**:运行 Electron 前先安装系统库,见 [docs/zh-CN/development.md](docs/zh-CN/development.md)
### 项目结构
```ClawX/
├── electron/ # Electron 主进程
│ ├── services/ # 类型化 Host API、Provider、Secrets 与运行时服务
│ │ ├── providers/ # Provider/account 模型同步逻辑
│ │ └── secrets/ # 系统钥匙串与密钥存储
│ ├── shared/ # 共享 Provider schema/常量
│ │ └── providers/
│ ├── main/ # 应用入口、窗口、IPC 注册
│ ├── gateway/ # OpenClaw 网关进程管理
│ ├── preload/ # 安全 IPC 桥接
│ └── utils/ # 工具模块(存储、认证、路径)
├── src/ # React 渲染进程
│ ├── lib/ # 前端统一 API 与错误模型
│ ├── stores/ # Zustand 状态仓库(settings/chat/gateway
│ ├── components/ # 可复用 UI 组件
│ ├── pages/ # Setup/Dashboard/Chat/Channels/Skills/Cron/Settings
│ ├── i18n/ # 国际化资源
│ └── types/ # TypeScript 类型定义
├── tests/
│ ├── e2e/ # Playwright Electron 端到端冒烟测试
│ └── unit/ # Vitest 单元/集成型测试
├── resources/ # 静态资源(图标、图片)
└── scripts/ # 构建与工具脚本
```
### 常用命令
```bash
# 开发
pnpm run init # 安装依赖并下载捆绑二进制(uv、agent-browser
pnpm dev # 以热重载模式启动(若缺失会自动准备预装技能包)
# 代码质量
pnpm lint # 运行 ESLint 检查
pnpm typecheck # TypeScript 类型检查
# 测试
pnpm test # 运行单元测试
pnpm run test:e2e # 运行 Electron E2E 冒烟测试
pnpm run test:e2e:headed # 以可见窗口运行 Electron E2E 测试
pnpm run comms:replay # 计算通信回放指标
pnpm run comms:baseline # 刷新通信基线快照
pnpm run comms:compare # 将回放指标与基线阈值对比
# 构建与打包
pnpm run build:vite # 仅构建前端
pnpm build # 完整生产构建(含打包资源)
pnpm package # 为当前平台打包(包含预装技能资源)
pnpm package:mac # 为 macOS 打包
pnpm package:win # 为 Windows 打包
pnpm package:linux # 为 Linux 打包
pnpm run init # 初始化开发环境(安装依赖并下载捆绑运行时)
pnpm dev # 以热重载模式启动
pnpm lint # ESLint 检查
pnpm typecheck # TypeScript 类型检查
pnpm test # 单元测试
pnpm run test:e2e # Electron E2E 冒烟测试
pnpm build # 完整生产构建
pnpm package # 为当前平台打包(可用 :mac / :win / :linux 后缀)
```
在无头 Linux 环境下,Electron 测试需要显示服务;可使用 `xvfb-run -a pnpm run test:e2e`
### 通信回归检查
当 PR 涉及通信链路(Gateway 事件、Chat 收发流程、Channel 投递、传输回退)时,建议执行:
```bash
pnpm run comms:replay
pnpm run comms:compare
```
CI 中的 `comms-regression` 会校验必选场景与阈值。
### 技术栈
| 层级 | 技术 |
|------|------|
| 运行时 | Electron 40+ |
| UI 框架 | React 19 + TypeScript |
| 样式 | Tailwind CSS + shadcn/ui |
| 状态管理 | Zustand |
| 构建工具 | Vite + electron-builder |
| 测试 | Vitest + Playwright |
| 动画 | Framer Motion |
| 图标 | Lucide React |
---
> 项目结构、技术栈、完整命令列表、E2E 并行策略、性能诊断与通信回归检查等细节,请参阅 [docs/zh-CN/development.md](docs/zh-CN/development.md)
## 参与贡献
@@ -406,10 +188,8 @@ CI 中的 `comms-regression` 会校验必选场景与阈值。
### 如何贡献
1. **Fork** 本仓库
2. **创建** 功能分支(`git checkout -b feature/amazing-feature`
3. **提交** 清晰描述的变更
4. **推送** 到你的分支
5. **创建** Pull Request
2. **创建** 功能分支(`git checkout -b feature/amazing-feature`),进行开发
3. **提交** 清晰描述的变更,**推送** 到你的分支,并**创建** Pull Request
### 贡献规范
@@ -418,7 +198,6 @@ CI 中的 `comms-regression` 会校验必选场景与阈值。
- 按需更新文档
- 保持提交原子化且描述清晰
---
## 致谢
@@ -430,7 +209,6 @@ ClawX 构建于以下优秀的开源项目之上:
- [shadcn/ui](https://ui.shadcn.com/) 精美设计的组件库
- [Zustand](https://github.com/pmndrs/zustand) 轻量级状态管理
---
## 社区
@@ -444,13 +222,10 @@ ClawX 构建于以下优秀的开源项目之上:
我们正在启动 ClawX 合作伙伴计划,寻找能够帮助我们将 ClawX 介绍给更多客户的合作伙伴,尤其是那些有定制化 AI 智能体或自动化需求的客户。
合作伙伴负责帮助我们连接潜在用户和项目,ClawX 团队则提供完整的技术支持、定制开发与集成服务。
如果你服务的客户对 AI 工具或自动化方案感兴趣,欢迎与我们合作。
合作伙伴负责帮助我们连接潜在用户和项目,ClawX 团队则提供完整的技术支持、定制开发与集成服务。如果你服务的客户对 AI 工具或自动化方案感兴趣,欢迎与我们合作。
欢迎私信我们,或发送邮件至 [public@valuecell.ai](mailto:public@valuecell.ai) 了解更多。
---
## Stars 历史
@@ -458,13 +233,13 @@ ClawX 构建于以下优秀的开源项目之上:
<img src="https://api.star-history.com/svg?repos=ValueCell-ai/ClawX&type=Date" alt="Stars 历史图表" />
</p>
---
## 许可证
ClawX 基于 [MIT 许可证](LICENSE) 发布。你可以自由地使用、修改和分发本软件。
---
<hr>
<p align="center">
<sub>由 ValueCell 团队用 ❤️ 打造</sub>
+113
View File
@@ -0,0 +1,113 @@
# ClawX Architecture
This document provides the detailed version of the Architecture section in the README.
ClawX uses a **dual-process architecture with a unified Host API layer**. The renderer calls one client abstraction, while protocol selection and process lifecycle are managed by Electron Main:
OpenClaw configuration delivery is also managed by Electron Main. While the Gateway is running, ClawX uses the authoritative snapshot returned by `config.get` as its baseline and commits changes with `config.set`. While the Gateway is stopped or starting, the same coordinator updates the resolved JSON5 configuration file without starting the Gateway. Ordinary provider, agent, channel, binding, skill, and model changes therefore do not replace the Gateway process. Full restarts are reserved for process-launch environment changes such as proxy settings and explicit user actions. Confirmed process exits and WebSocket closes retain their existing automatic reconnect paths. The first three consecutive WebSocket heartbeat misses remain diagnostic-only so brief pong delays do not interrupt long-running work; a pong or any incoming message resets the count, while a fourth consecutive miss requests guarded automatic Gateway recovery when the lifecycle is in an auto-recoverable running state. After authentication configuration is written to SQLite, ClawX calls OpenClaw's `secrets.reload` so running agents can read new credentials without a process restart.
Chat uses an ACP stdio bridge owned by Electron Main. Main passes the same app-managed Gateway token to this local child through its private process environment, so ACP history replay remains authenticated when the runtime configuration reloads. If guarded Gateway recovery interrupts an accepted main-session run, the patched OpenClaw runtime starts a distinct recovery run carrying the interrupted run id as explicit lineage. Chat and agent events preserve that lineage; the reconnecting ACP bridge adopts the new run for its pending prompt, resets per-run stream cursors, and subscribes to session-scoped tool events. The renderer remains unaware of Gateway runtime identity and continues to receive typed host events for one in-memory ACP timeline. The Gateway remains responsible for non-Chat capabilities such as providers, models, skills, workspace, settings, diagnostics, and media configuration.
### ACP Semantic Authority
ACP is the preferred semantic authority for every Chat meaning and context that it exposes. This includes session identity and routing where applicable, workspace and execution `cwd`, prompt and timeline state, and standard resource or attachment semantics. When ACP provides a value or event, Main and Renderer must use it rather than replace it with a Gateway snapshot, transcript inference, local configuration, or a parallel projection.
A bypass is allowed only when upstream ACP has no equivalent. Such a compatibility path must be narrow, bounded, session- and generation-scoped, and documented with its rationale, source of truth, limits, reconciliation behavior, and removal condition in the relevant Harness reference or rule. It must not silently become a competing authority.
### ACP History Authority and Bounded Transcript Supplements
ACP `session/load` replay is the primary authority for Chat history. ClawX does not persist a second ACP ledger, reduced timeline, replay cache, or reconstructed tool history. If OpenClaw's structured ACP event ledger is unavailable, its ACP adapter reconstructs persisted transcript `toolCall` and `toolResult` records as native tool updates in transcript order, preserving text-tool-text boundaries; ClawX does not infer those records itself. Some OpenClaw capabilities do not yet have fully corresponding ACP implementations; for example, assistant media may be omitted from ACP and Gateway processing may remove assistant `MEDIA:` directives from the visible live reply. ClawX therefore keeps only bounded, marked, memory-only compatibility supplements:
- Asynchronous image-generation completions may be restored only when the same session has proven `image_generate` context and the completion evidence is trusted or approved transcript evidence.
- General attachments may be recovered from canonical persisted assistant `__openclaw.media` facts or explicit line-leading assistant `MEDIA:` directives. This recovers attachment references and declared metadata, not the surrounding assistant message.
- Main may add metadata-only whole-turn timing from bounded transcript JSONL records because ACP replay does not provide the original event timestamps. It can annotate only an already restored ACP turn.
- If a cron session has completely empty ACP replay, Main's typed cron-history API may provide the scheduled prompt and completion summary. When an identified run summary contains OpenClaw's truncation marker, Main may recover the final assistant text from that run's transcript only when the transcript is longer and shares the complete persisted summary prefix.
Historical reads are bounded to the newest 1000 transcript messages. A successful live prompt performs one immediate read and one retry after 1500 ms. Every supplement is scoped to the exact session, ACP generation, operation, and live user turn where applicable; stale, missing, duplicate, or ambiguous matches are discarded. These paths must not reconstruct ordinary assistant messages, thoughts, tools, plans, permissions, file activity, missing turns, or a parallel Chat history, and Main must not manufacture native ACP events from transcript evidence. Standard ACP resources remain preferred, and these compatibility exceptions should be removed when upstream emits equivalent content.
An unfinished ACP response continues streaming when you open another conversation or page. Returning before it finishes restores the latest in-memory timeline and continues the live response. Once it finishes, normal ACP history replay remains the source of truth.
ACP assistant turns show whole-turn duration. Live timing follows the client-observed prompt lifecycle and survives in-app navigation. Historical timing is derived in Electron Main from bounded OpenClaw transcript timestamps and only annotates a turn already restored by ACP replay.
ACP Chat renders standard ACP resources as attachments. User-selected images appear as thumbnails with a filename hover overlay, while other available attachment cards show the filename and a muted, truncating source path. When the current OpenClaw ACP adapter omits assistant media, canonical persisted OpenClaw media facts and explicit assistant `MEDIA:` directives can also be recovered as attachment cards without displaying transcript-only metadata.
Existing local file references, including paths outside the active workspace, are revalidated in Electron Main for the exact session and generation before every preview or open. Previewable local attachments produced by the AI, including `.docx` and `.pptx` files within the 20 MB inline-preview limit, keep their primary read-only in-app preview action and provide a secondary menu for opening with compatible applications or revealing the file in Finder, File Explorer, or the system file manager. For local HTML attachments, that menu starts with an action that opens the file in the right-side Preview tab.
The same Office limitations apply here: `.doc` and `.ppt` remain system-open formats, DOCX pagination may differ from Microsoft Word, and PPTX animations, transitions, and media playback are unsupported. Compatible-application discovery is available only on macOS and Windows and silently degrades to reveal-only behavior on Linux or when discovery fails. Other local files, including Office files larger than 20 MB, open in the system application after a user click. User-selected folder attachments remain available after send and open in the system file manager; ClawX does not read or preview their contents. Remote HTTP and HTTPS attachments open externally after a user click. Bare or inline prose paths without canonical media facts are not treated as attachments.
ACP Chat can also display generated image previews when image-generation media is delivered by the runtime as trusted structured media. Trusted OpenClaw internal-UI deliveries and task-correlated final replies preserve the original user-facing completion text, including text-only failure explanations, rather than replacing it with a generic image caption. During historical OpenClaw replay, assistant image `MEDIA:` markers are promoted to the inline image experience only when they follow a recorded image-generation task start for that session. ClawX loads previews through host media handling in Electron Main, not arbitrary renderer filesystem access. Standard ACP image and resource content remains the preferred path and renders directly.
### ACP File Activity Semantics
- File activity is projected from successful, completed OpenClaw `write`, `edit`, and `apply_patch` calls. Tool recognition follows the official OpenClaw Chat UI; filtering to completed calls is specific to ClawX.
- Created and modified activity rows use the same file-card shell and **Open with** menu as previewable assistant attachments while retaining their status and optional `+/-` summary. For HTML files, the first menu item opens the file in the right-side **Preview** tab. Deleted rows keep only the **Changes** action. Every application-list, selected-application, and reveal request is independently revalidated in Electron Main from the workspace root and relative path. Tool-derived paths never become attachments or expose canonical native paths to the renderer.
- A `write` is shown as the tool declares it: a creation with an all-added diff, even if the path may already exist.
- **Changes** is a chronological, session-level record of tool-declared activity. It is not Git output or a verified diff against a source baseline.
- For each file, Changes renders at most one diff editor per assistant turn. Sequential fragments are composed when safe; independent fragments share one concatenated editor without claiming a complete-file baseline.
- Side effects made by shell commands, scripts, users, or IDEs are not detected.
- A full ACP replay can restore recorded file activity. If replay is incomplete, ClawX does not infer missing activity through fallback behavior.
```
┌──────────────────────────────────────────────────────────────────┐
│ ClawX Desktop App │
│ │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ Electron Main Process │ │
│ │ • Window and application lifecycle management │ │
│ │ • Gateway process supervision │ │
│ │ • System integration (tray, notifications, keychain) │ │
│ │ • Auto-update orchestration │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬───────────────────────────────────┘
│ IPC (authoritative control plane)
┌──────────────────────────────────────────────────────────────────┐
│ React Renderer Process │
│ • Modern component-based UI (React 19) │
│ • State management with Zustand │
│ • Unified host-api/api-client calls │
│ • Markdown assistant replies, literal user input │
└──────────────────────────────┬───────────────────────────────────┘
│ Typed IPC requests
┌──────────────────────────────────────────────────────────────────┐
│ Main Host Services and Gateway Manager │
│ • host:invoke typed service dispatcher │
│ • Settings, files, sessions, skills, providers, diagnostics │
│ • Main-owned Gateway WebSocket and process supervision │
└──────────────────────────────┬───────────────────────────────────┘
│ Main-owned WebSocket
┌──────────────────────────────────────────────────────────────────┐
│ OpenClaw Gateway │
│ • AI agent runtime and orchestration │
│ • Message channel management │
│ • Skill/plugin execution environment │
│ • Provider abstraction layer │
└──────────────────────────────────────────────────────────────────┘
```
### Design Principles
- **Process Isolation**: The AI runtime operates in a separate process, keeping the UI responsive even during heavy computation.
- **Single Entry for Frontend Calls**: Renderer requests go through `host-api` / `api-client`; protocol details are hidden behind a stable interface.
- **Main-Process Transport Ownership**: Electron Main owns the ACP Chat stdio bridge and Gateway transports; the renderer talks to Main over typed IPC.
- **Extension IPC Contributions**: Main-process extensions contribute host-api actions through the typed IPC registry instead of HTTP routes.
- **Graceful Recovery**: Built-in reconnect, timeout, and backoff logic handles transient failures automatically.
- **Secure Storage**: API keys and sensitive data use the operating system's native secure storage mechanisms.
- **CORS-Safe by Design**: The renderer does not call local Gateway or Host API HTTP endpoints directly.
### Process Model and Gateway Troubleshooting
- ClawX is an Electron app, so **one app instance normally appears as multiple OS processes** (main/renderer/zygote/utility). This is expected.
- Single-instance protection uses Electron's lock plus a local process-file lock fallback, preventing duplicate app launches in environments where desktop IPC or the session bus is unstable.
- During rolling upgrades, mixed old and new app versions can still have asymmetric protection behavior. For best reliability, upgrade all desktop clients to the same version.
- The OpenClaw Gateway listener should still be **single-owner**: only one process should listen on `127.0.0.1:18789`.
- Gateway readiness is based on OpenClaw core signals such as `system-presence`, `health`, and `status`. Memory or channel failures are shown as capability degradation rather than global Gateway failure.
- To verify the active listener:
- macOS/Linux: `lsof -nP -iTCP:18789 -sTCP:LISTEN`
- Windows (PowerShell): `Get-NetTCPConnection -LocalPort 18789 -State Listen`
- Clicking the window close button (`X`) hides ClawX to the tray; it does not fully quit the app. Use **Quit ClawX** in the tray menu for a complete shutdown.
+130
View File
@@ -0,0 +1,130 @@
# ClawX Development Guide
This document provides the detailed version of the Development section in the README.
### Prerequisites
- **Node.js**: 22.22.3+, 24.15.0+, or 25.9.0+ within the corresponding supported major line (Node 24 LTS recommended)
- **Package Manager**: pnpm 9+ (npm is also supported)
- **Linux (Ubuntu/Debian)**: Install the required system libraries before running Electron:
```bash
sudo apt-get install -y libnss3 libgtk-3-0 libxss1 libxtst6 libatspi2.0-0 libnotify4 xdg-utils
```
On Ubuntu 24.04+, some packages use a `t64` suffix; `apt` automatically selects the correct variant when you run the command above.
### Project Structure
```text
ClawX/
├── electron/ # Electron Main Process
│ ├── services/ # Typed Host API, provider, secrets, and runtime services
│ │ ├── providers/ # Provider/account model sync logic
│ │ └── secrets/ # OS keychain and secret storage
│ ├── shared/ # Shared provider schemas/constants
│ │ └── providers/
│ ├── main/ # App entry, windows, and IPC registration
│ ├── gateway/ # OpenClaw Gateway process manager
│ ├── preload/ # Secure IPC bridge
│ └── utils/ # Utilities for storage, auth, and paths
├── src/ # React Renderer Process
│ ├── lib/ # Unified frontend API and error model
│ ├── stores/ # Zustand stores (settings/chat/gateway)
│ ├── components/ # Reusable UI components
│ ├── pages/ # Setup/Dashboard/Chat/Channels/Skills/Cron/Settings
│ ├── i18n/ # Localization resources
│ └── types/ # TypeScript type definitions
├── tests/
│ ├── e2e/ # Playwright Electron end-to-end smoke tests
│ └── unit/ # Vitest unit and integration-like tests
├── resources/ # Static assets (icons and images)
└── scripts/ # Build and utility scripts
```
### Available Commands
```bash
# Development
pnpm run init # Install dependencies and download bundled binaries (uv, agent-browser)
pnpm dev # Start with hot reload (auto-prepares bundled skills if missing)
# Quality
pnpm lint # Run ESLint
pnpm typecheck # TypeScript validation
# Testing
pnpm test # Run unit tests
pnpm run test:e2e # Run Electron E2E smoke tests
pnpm run test:e2e:headed # Run Electron E2E tests with a visible window
pnpm run perf:chat # Capture synthetic Chat Renderer/Main CPU profiles
pnpm run profile:main # Launch the built app with Main inspector on port 9229
pnpm run comms:replay # Compute communication replay metrics
pnpm run comms:baseline # Refresh the communication baseline snapshot
pnpm run comms:compare # Compare replay metrics against baseline thresholds
# Build and Package
pnpm run build:vite # Build the frontend only
pnpm build # Full production build with packaging assets
pnpm package # Package for the current platform with bundled skills
pnpm package:mac # Package for macOS
pnpm package:win # Package for Windows
pnpm package:linux # Package for Linux
```
On headless Linux, Electron tests need a display service. Use `xvfb-run -a pnpm run test:e2e`.
Electron E2E functional tests use two Playwright workers by default both locally and in CI. Set `CLAWX_E2E_WORKERS=<positive integer>` to tune the ordinary parallel lane for the machine. Tests that touch OS-global state use the one-worker `exclusive` project, and host performance profiles run alone afterward. New E2E tests are parallel by default; apply `E2E_EXCLUSIVE_TAG` from `tests/e2e/parallel-policy.ts` when a test uses the real clipboard or another machine-global resource.
For a focused ordinary spec that does not need the exclusive prerequisite, run `pnpm exec playwright test <spec> --project=parallel --no-deps`.
### Electron Performance Diagnostics
`pnpm run perf:chat` runs isolated synthetic ACP workloads for streaming and for rich static Markdown sidebar and scroll interaction. It writes versioned metrics plus Renderer and Main CPU profiles under the Playwright `test-results/` directory. Renderer profiles cover the production store/render path and frame pacing. The streaming Main profile measures Main-to-Renderer IPC fanout, while the interaction Main profile shows whether Main remains idle while Renderer interactions run. Neither includes the upstream OpenClaw/ACP subprocess or GPU-process paths.
Open a CPU profile in Chrome DevTools. The artifacts contain generated fixture text only and are not product telemetry. Results are hardware-dependent, so compare repeated runs on the same machine instead of applying one cross-platform absolute threshold.
For a live Renderer recording, start development with `CLAWX_REMOTE_DEBUGGING_PORT=9223 pnpm dev` and attach Playwright or Chrome DevTools to `localhost:9223`. For a live Electron Main recording, run `pnpm run profile:main`, open `chrome://inspect`, configure `localhost:9229`, and select the Electron Main target. Leave `CLAWX_GATEWAY_WS_TRACE` unset unless WebSocket tracing itself is being measured.
ClawX leaves Chromium hardware acceleration enabled by default so long documents, scrolling, and layout animations can use GPU compositing and rasterization. Chromium still honors the native `--disable-gpu` command-line switch as a troubleshooting fallback for a machine with a broken graphics driver.
### Communication Regression Checks
When a PR changes communication paths such as Gateway events, the ACP Chat bridge send/receive flow, channel delivery, or transport fallback, run:
```bash
pnpm run comms:replay
pnpm run comms:compare
```
The `comms-regression` CI job enforces required scenarios and threshold checks.
### Electron E2E Tests
The Playwright Electron suite launches the packaged renderer and Main process from `dist/` and `dist-electron/`, so it does not require manually running `pnpm dev` first.
`pnpm run test:e2e` automatically:
- builds the renderer and Electron bundles with `pnpm run build:vite`
- starts Electron in an isolated E2E mode with a temporary `HOME`
- uses a temporary ClawX `userData` directory
- runs ordinary spec files concurrently while fencing OS-global and performance tests
- skips heavy startup side effects such as Gateway auto-start, bundled skill installation, tray creation, and CLI auto-install
The first baseline specs cover:
- first-launch Setup Wizard visibility on a fresh profile
- skipping setup and navigating to the Models page inside the Electron app
Add future Electron flows under `tests/e2e/` and reuse the shared fixture in `tests/e2e/fixtures/electron.ts`. Keep tests parallel-safe by avoiding fixed writable paths, ports, native keychains, and other external shared state. Use `E2E_EXCLUSIVE_TAG` when isolation is not possible.
### Tech Stack
| Layer | Technology |
|-------|------------|
| Runtime | Electron 40+ |
| UI Framework | React 19 + TypeScript |
| Styling | Tailwind CSS + shadcn/ui |
| State | Zustand |
| Build | Vite + electron-builder |
| Testing | Vitest + Playwright |
| Animation | Framer Motion |
| Icons | Lucide React |
+83
View File
@@ -0,0 +1,83 @@
# ClawX Features
This document provides the detailed version of the Features section in the README.
### Zero Configuration Barrier
Complete the entire setup from installation to your first AI conversation through an intuitive graphical interface. No terminal commands, YAML files, or environment-variable hunting are required.
### Intelligent Chat Interface
Communicate with AI agents through a modern chat experience. ClawX supports multiple conversation contexts and message history, with assistant replies rendered as streaming Markdown with syntax-highlighted fenced code, CJK-aware parsing, GitHub-flavored tables, and KaTeX-powered LaTeX math (`$inline$`, `$$block$$`, `\(inline\)`, and `\[block\]`). User input remains literal text. The main composer also supports direct `@agent` routing for multi-agent setups. Fenced code preserves source line breaks, soft-wraps long lines, and provides a localized copy action after streaming completes.
Skills inserted from the composer appear as `/skill-name` cards. Click a card to open the preview sidebar and read that skill's `SKILL.md`.
When you target another agent with `@agent`, ClawX switches directly to that agent's own conversation context instead of relaying through the default agent. Agent workspaces stay separate by default, while stronger runtime isolation depends on OpenClaw sandbox settings.
The session sidebar is workspace-first: the default workspace stays at the top, other workspaces sort naturally, and each workspace can collapse or load more sessions. A session row shows a spinner while the AI is replying, a blue dot when an unseen reply finishes, and its relative activity time after the conversation is opened; hovering still reveals row actions. Imported workspaces can be renamed from their sidebar header. The custom name is reflected in the chat composer, while hovering the header still reveals the filesystem path.
When a valid workspace is selected, a new chat inherits it while remaining editable until the first send. Editable new or unbound chats expose a workspace chip in the composer. Its menu lists recent and known-session workspaces, lets you return to the default workspace, or choose another folder. If a saved workspace folder was moved or deleted, Chat pauses session creation and asks you to choose an existing folder instead of repeatedly retrying the missing path. Unavailable non-default groups are marked in the sidebar and can be removed after confirmation; this permanently deletes every session in that group. A session row is removed and navigation changes only after permanent deletion succeeds. Failed deletions leave the conversation and confirmation open for retry. Synthetic OpenClaw UUID-date fallback titles are treated as missing only when they match the session ID, then replaced with the conversation's first user prompt instead of being persisted as the session name.
Each agent can override its own `provider/model` runtime setting. Agents without overrides continue inheriting the global default model.
The Workspace and Preview tabs in Chat's right panel provide read-only previews for Markdown, `.docx`, and `.pptx` files. Markdown previews use the same syntax-highlighted, soft-wrapped, copyable fenced code, CJK-aware parsing, and KaTeX math support in static rendering mode. The Preview header can expand the selected file to the full ClawX viewport; use the same control or press Escape to return to the panel. Legacy `.doc` and `.ppt` files continue to open through the operating system instead of inline. DOCX pagination may differ from Microsoft Word, and PPTX previews do not support animations, transitions, or media playback. Office files larger than 20 MB are not previewed inline.
### Local HTML Preview
The Chat right panel contains Workspace, Preview, and Changes tabs. It no longer provides a general Web Browser, Home page, or address bar. Authorized local `.html` and `.htm` attachments, file activities, and Workspace files open in Preview by default. File actions let you choose the built-in Preview or a system application, and the Preview header can open the current HTML file in the system browser.
All links are non-clickable. Links rendered by ClawX appear as ordinary text, and links inside HTML Preview have their styling and pointer interaction removed. HTML Preview also blocks forms, script navigation, redirects, hash navigation, popups, downloads, network requests, and device permissions. It can render self-contained local HTML but cannot leave the selected document.
### Multi-Channel Management
Configure and monitor multiple AI channels simultaneously. Each channel operates independently, allowing you to run specialized agents for different tasks.
Each channel supports multiple accounts, per-account agent binding, and switching the channel default account directly from the Channels page.
For custom channel account IDs, ClawX enforces OpenClaw-compatible canonical IDs: `[a-z0-9_-]`, lowercase, a maximum of 64 characters, and starting with a letter or number. This prevents routing mismatches.
ClawX also bundles Tencent's official personal WeChat channel plugin, so you can link WeChat directly from the Channels page through an in-app QR flow.
### Cron-Based Automation
Schedule AI tasks to run automatically. Define triggers and set intervals so AI agents can work around the clock.
The Cron page lets you configure external delivery directly in the task form with separate sender-account and recipient-target selectors. For supported channels, recipient targets are discovered automatically from channel directories or known session history, so you no longer need to edit `jobs.json` by hand. The task message field supports inserting skills with the same inline `/skill` token syntax as the main chat composer, scoped to the selected agent, so scheduled prompts can trigger skills directly.
The schedule picker is split into **Recurring** and **Once** tabs. Recurring offers Hourly, Daily, Weekdays, Weekly, and Custom raw cron frequencies with inline time and weekday controls. Once runs the task a single time at a chosen date, with the weekday shown, and time. One-time tasks must be scheduled for a future moment and are automatically removed by the runtime once they finish.
### Extensible Skill System
Extend your AI agents with pre-built skills. The integrated Skills page is local-first: it scans managed and workspace skill directories and lets you enable or disable skills without depending on the Gateway. Enterprise extensions may also expose an extension-provided marketplace.
ClawX pre-bundles full document-processing skills (`pdf`, `xlsx`, `docx`, `pptx`), deploys them automatically to the managed skills directory (default `~/.openclaw/skills`) on startup, and enables them by default on first install.
The Skills page can display skills discovered from multiple OpenClaw sources, including the managed directory, workspace, and extra skill directories. It shows each skill's actual location so you can open the real folder directly. For bundled OpenClaw skills, community builds ship and expose only `skill-creator`; non-allowlisted bundled skills are physically trimmed in both development and packaged startup, and stale `openclaw.json` entries for removed bundled skills are pruned.
### Secure Provider Integration
Connect to multiple AI providers, including OpenAI, Anthropic, and Z.AI / GLM, with credentials stored securely in the native system keychain. OpenAI supports both API keys and browser OAuth for Codex subscriptions.
In Developer Mode, the dedicated Image Generation page supports an independent OpenAI-compatible image-generation endpoint with a Base URL, API key, and model name such as `gpt-image-2`. Image generation can therefore use a dedicated `/v1/images/generations` service while chat continues using the normal OpenAI provider.
For **Custom** providers used with OpenAI-compatible gateways, you can set a custom `User-Agent` in **Settings -> AI Providers -> Edit Provider** for compatibility-sensitive endpoints.
When you edit or switch providers, ClawX preserves existing per-model capability metadata such as `input: ["text", "image"]`. Newly selected Custom-provider models use OpenClaw onboarding-compatible image-input inference, with unknown models defaulting to text-only.
Custom-provider model rows also receive an explicit `contextWindow`, inferred from the model family, such as `gpt-5.x` -> 272k. Rows saved by older versions are backfilled on startup so OpenClaw can compact long sessions before they fail with "Context overflow" errors. When no compaction configuration exists, ClawX seeds `agents.defaults.compaction.mode = "safeguard"` and `reserveTokensFloor = 50000`; rows or configurations you authored yourself are never modified, except that a missing `reserveTokensFloor` may be backfilled.
Z.AI (CN / Global) maps to OpenClaw's built-in `zai` provider (`ZAI_API_KEY`). The default model is `glm-5.2`. Use the Code Plan preset for Coding Plan endpoints (`.../api/coding/paas/v4`) or the normal API endpoints (`.../api/paas/v4`). CN and Global are mutually exclusive because they share one OpenClaw runtime key.
When a compatible gateway rejects `/models` for non-authentication reasons, ClawX automatically falls back to a lightweight `/chat/completions` or `/responses` probe using the configured model during API-key validation.
### Adaptive Theming
Choose light mode, dark mode, or a system-synchronized theme. ClawX adapts to your preferences automatically.
### Startup Launch Control
In **Settings -> General**, enable **Launch at system startup** so ClawX starts automatically after login.
### Update Prompts
ClawX checks for new versions on startup. When an update is available, it shows an in-app prompt; downloading and installing happen only after you choose the action.
+12
View File
@@ -0,0 +1,12 @@
# ClawX Proxy Settings
This document provides the detailed version of the Proxy Settings section in the README.
- A bare `host:port` value is treated as an HTTP proxy.
- If advanced proxy fields are left empty, ClawX falls back to **Proxy Server**.
- Saving proxy settings reapplies Electron networking immediately and restarts the Gateway automatically.
- When Telegram is enabled, ClawX also syncs the proxy to OpenClaw's Telegram channel configuration.
- When the ClawX proxy is disabled, a normal Gateway restart preserves an existing Telegram channel proxy.
- To explicitly clear the Telegram proxy from OpenClaw configuration, disable the proxy and save the proxy settings once.
- In **Settings -> Advanced -> Developer**, you can run **OpenClaw Doctor**, which executes `openclaw doctor --json` and displays the diagnostic output in the app.
- In packaged Windows builds, the bundled `openclaw` CLI/TUI runs through the shipped `node.exe` entry point to keep terminal input behavior stable.
+113
View File
@@ -0,0 +1,113 @@
# ClawXのアーキテクチャ
このドキュメントは、READMEの「アーキテクチャ」セクションの詳細版です。
ClawXは **統合Host APIレイヤーを備えたデュアルプロセスアーキテクチャ**を採用しています。Rendererは単一のクライアント抽象を呼び出し、プロトコル選択とプロセスライフサイクルはElectron Mainが管理します。
OpenClawの設定配信もElectron Mainが管理します。Gateway実行中は`config.get`が返す権威あるスナップショットを基準にし、変更を`config.set`でコミットします。Gatewayが停止中または起動中の場合は、同じコーディネーターが解決済みJSON5設定ファイルを更新しますが、これを理由にGatewayを起動することはありません。そのため、通常のプロバイダー、Agent、チャネル、バインディング、スキル、モデルの変更ではGatewayプロセスを置き換えません。完全な再起動は、プロキシなどのプロセス起動環境の変更と、ユーザーによる明示的な操作に限られます。確認済みのプロセス終了とWebSocket切断では、既存の自動再接続経路が引き続き使用されます。WebSocketハートビートの連続3回までの欠落は診断のみとし、短いpong遅延で長時間実行中の処理を中断しません。pongまたは任意の受信メッセージでカウントをリセットし、4回連続で欠落した場合に、ライフサイクルが自動復旧可能なrunning状態であれば、保護されたGateway自動復旧を要求します。認証設定をSQLiteへ書き込んだ後はOpenClawの`secrets.reload`を呼び出し、実行中のAgentがプロセス再起動なしで新しい認証情報を読み取れるようにします。
ChatはElectron Mainが所有するACP stdio bridgeを使用します。Mainはアプリが管理するGateway tokenをプライベートなプロセス環境経由でローカルの子プロセスへ渡すため、ランタイム設定の再読み込み後もACP履歴リプレイの認証が維持されます。保護されたGateway復旧が受理済みのメインセッションrunを中断した場合、パッチ済みOpenClawランタイムは別の復旧runを開始し、中断されたrun idを明示的なlineageとして保持します。Chat eventとagent eventはそのlineageを維持し、再接続したACP bridgeはpending promptを新しいrunへ引き継ぎ、run単位のストリームカーソルをリセットしてセッション単位のtool eventを購読します。RendererはGatewayランタイムの識別子を認識せず、型付きhost eventから同じメモリ内ACP timelineを描画し続けます。Gatewayはproviders、models、skills、workspace、settings、diagnostics、media configurationなどの非Chat機能を引き続き担当します。
### ACPのセマンティック権威
ACPが提供するすべてのChatの意味とコンテキストでは、`session/load`履歴だけでなくACPを優先的なセマンティック権威として扱います。該当する場合のセッションIDとルーティング、ワークスペースと実行`cwd`、promptとtimelineの状態、標準resourceや添付ファイルのセマンティクスが含まれます。ACPが値やイベントを提供する場合、MainとRendererはGatewayスナップショット、transcriptからの推論、ローカル設定、別の並列投影で置き換えず、ACPの結果を使用します。
上流ACPに相当する機能がない場合に限り、ACPを迂回できます。その互換性パスは狭く有界で、sessionとgenerationに紐付ける必要があります。また、理由、情報源、制限、調整方法、削除条件を該当するHarness referenceまたはruleに記録し、競合する権威へ暗黙に発展させてはいけません。
### ACP履歴の権威と有界なtranscript補足
ACP `session/load` のリプレイがChat履歴の主要な権威です。ClawXは第二のACP ledger、縮約timeline、リプレイキャッシュ、再構成したツール履歴を永続化しません。OpenClawの構造化ACP event ledgerが利用できない場合、そのACP adapterは永続化済みtranscriptの`toolCall``toolResult`を順番どおりにネイティブなtool updateへ再構成し、text-tool-textの境界を維持します。ClawX自身はこれらの記録を推論しません。OpenClawの一部の機能にはまだ完全に対応するACP実装がありません。たとえば、assistantメディアがACPから省略されたり、Gateway処理によってassistantの`MEDIA:`ディレクティブが表示中のライブ返信から削除されたりする場合があります。そのため、ClawXは有界で印付き、メモリのみの互換性補足だけを保持します。
- 非同期の画像生成完了は、同じセッションに確認済みの`image_generate`コンテキストがあり、完了の証拠が信頼できるか、承認済みのtranscript証拠である場合に限り復元できます。
- 一般の添付ファイルは、永続化されたassistantの`__openclaw.media`事実、または行頭にある明示的なassistant `MEDIA:`ディレクティブから復元できます。復元されるのは添付ファイルの参照と宣言されたメタデータだけで、周囲のassistantメッセージは復元しません。
- ACPリプレイには元のイベントタイムスタンプがないため、Mainは有界のtranscript JSONLレコードからメタデータのみのターン全体の時間を追加できます。これはACPですでに復元されたターンにだけ付与できます。
- cronセッションのACPリプレイが完全に空の場合、Mainの型付きcron履歴APIがスケジュール済みプロンプトと完了サマリーを提供できます。識別された実行サマリーにOpenClawの切り詰めマーカーがある場合、対応するrunのtranscriptがより長く、永続化されたサマリーの完全な接頭辞を共有するときに限り、Mainは最終assistantテキストを復元できます。
履歴の読み取りは最新のtranscriptメッセージ1000件に制限されます。成功したライブpromptでは直ちに1回読み取り、1500ms後に1回だけ再試行します。すべての補足は、正確なsession、ACP generation、操作、必要に応じてライブユーザーターンに紐付けられます。古い、欠落した、重複した、または曖昧な一致は破棄されます。これらの経路で通常のassistantメッセージ、thought、tool、plan、permission、ファイルアクティビティ、欠落したターン、別のChat履歴を再構成してはいけません。Mainはtranscriptの証拠からネイティブACPイベントを生成しません。標準ACP resourceが優先され、上流が同等の内容を提供した場合はこれらの互換性例外を削除します。
別の会話やページを開いても、未完了のACP応答はストリーミングを継続します。完了前に戻ると最新のメモリ内timelineを復元し、ライブ応答の表示を続けます。完了後は通常のACP履歴リプレイが正の情報源です。
ACPのassistantターンにはターン全体の所要時間が表示されます。ライブ計時はクライアントが観測したpromptライフサイクルに従い、アプリ内の移動後も継続します。履歴の所要時間はElectron Mainが有界のOpenClaw transcriptタイムスタンプから算出し、ACPリプレイですでに復元されたターンにだけ付与します。
ACP Chatは標準ACP resourceを添付ファイルとして描画します。ユーザーが選択した画像はファイル名をホバーオーバーレイに表示するサムネイルになり、その他の利用可能な添付カードにはファイル名と淡色で省略可能なソースパスが表示されます。現在のOpenClaw ACP adapterがassistantメディアを省略した場合、正規化された永続OpenClawメディア情報と明示的なassistant `MEDIA:`ディレクティブを、transcript専用メタデータを表示せずに添付カードとして復元できます。
既存のローカルファイル参照は、アクティブなworkspace外のパスを含め、プレビューやオープンのたびにElectron Mainが正確なsessionとgenerationについて再検証します。AIが生成したプレビュー可能なローカル添付(20 MB以下の`.docx``.pptx`を含む)は、読み取り専用のアプリ内プレビューを主操作として保持し、対応アプリで開く操作やFinder、エクスプローラー、システムのファイルマネージャーで表示する操作を副次メニューから選べます。ローカルHTML添付では、そのメニューの先頭項目から右側のPreviewタブでファイルを開けます。
Officeプレビューには同じ制限があります。`.doc``.ppt`はシステムアプリで開き、DOCXのページ区切りはMicrosoft Wordと異なる場合があり、PPTXのアニメーション、画面切り替え、メディア再生はサポートされません。対応アプリの検出はmacOSとWindowsでのみ利用でき、Linuxまたは検出失敗時は通知なしにファイル位置の表示だけへ切り替わります。その他のローカルファイル(20 MBを超えるOfficeファイルを含む)は、クリック後にシステムアプリで開きます。ユーザーが選択したフォルダー添付は送信後も利用でき、クリックするとシステムのファイルマネージャーで開きます。ClawXはその内容を読み取ったりプレビューしたりしません。リモートHTTP/HTTPS添付はクリック後に外部で開きます。正規のメディア情報を伴わない通常の文章中のパスは添付として扱われません。
ACP Chatは、ランタイムが画像生成メディアを信頼できる構造化メディアとして配信した場合、生成画像のプレビューも表示できます。信頼できるOpenClaw internal-UI配信と画像生成タスクに紐付いた最終返信では、テキストだけの失敗説明を含む元のユーザー向け完了テキストを保持し、汎用画像キャプションに置き換えません。OpenClawの履歴リプレイ中、assistant画像の`MEDIA:`マーカーは、同じセッションで画像生成タスクの開始が記録されている場合に限りインライン画像へ昇格します。プレビューは任意のRendererファイルシステムアクセスではなく、Electron Mainのホストメディア処理で読み込みます。標準ACPの画像とresourceコンテンツが引き続き優先され、そのまま描画されます。
### ACPファイルアクティビティのセマンティクス
- ファイルアクティビティは、成功して完了したOpenClawの`write``edit``apply_patch`呼び出しから投影されます。ツール認識は公式OpenClaw Chat UIに従い、完了した呼び出しだけに絞る処理はClawX固有です。
- 作成・変更された行は、プレビュー可能なassistant添付と同じファイルカードと**Open with**メニューを使い、状態と任意の`+/-`概要を保持します。HTMLではメニューの先頭項目が右側の**Preview**タブでファイルを開きます。削除行には **Changes** 操作だけを残します。アプリ一覧、選択アプリで開く操作、表示位置の要求は、workspaceルートと相対パスからElectron Mainが個別に再検証します。ツール由来のパスは添付にならず、Rendererへ正規化済みのネイティブパスも公開されません。
- `write` はツールの宣言どおり、対象パスがすでに存在する可能性があっても、作成および全行追加の差分として表示されます。
- **Changes** はツールが宣言したアクティビティを時系列に記録するセッション単位の記録です。Gitの出力でも、検証済みソースベースラインとの差分でもありません。
- 各ファイルについて、Changesはassistantの各ターンに最大1つのdiffエディターを表示します。安全に連結できる断片は合成し、独立した断片は1つのエディターに連結しますが、完全なファイルベースラインとの差分とはみなしません。
- シェルコマンド、スクリプト、ユーザー、IDEによる副作用は検出されません。
- 完全なACPリプレイから記録済みのファイルアクティビティを復元できます。リプレイが不完全でも、ClawXはフォールバック推論で欠落を補いません。
```
┌──────────────────────────────────────────────────────────────────┐
│ ClawX デスクトップアプリ │
│ │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ Electron メインプロセス │ │
│ │ • ウィンドウとアプリケーションのライフサイクル管理 │ │
│ │ • Gatewayプロセスの監視 │ │
│ │ • システム統合(トレイ、通知、キーチェーン) │ │
│ │ • 自動更新のオーケストレーション │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬───────────────────────────────────┘
│ IPC(権威ある制御プレーン)
┌──────────────────────────────────────────────────────────────────┐
│ React Rendererプロセス │
│ • モダンなコンポーネントベースUI(React 19) │
│ • Zustandによる状態管理 │
│ • 統一host-api/api-client呼び出し │
│ • assistant返信はMarkdown、ユーザー入力はプレーンテキスト │
└──────────────────────────────┬───────────────────────────────────┘
│ 型付きIPCリクエスト
┌──────────────────────────────────────────────────────────────────┐
│ Main Host ServicesとGateway Manager │
│ • host:invoke型付きサービスディスパッチ │
│ • 設定、ファイル、セッション、スキル、プロバイダー、診断 │
│ • Main所有のGateway WebSocketとプロセス監視 │
└──────────────────────────────┬───────────────────────────────────┘
│ Main所有WebSocket
┌──────────────────────────────────────────────────────────────────┐
│ OpenClaw Gateway │
│ • AIエージェントランタイムとオーケストレーション │
│ • メッセージチャネル管理 │
│ • スキル/プラグイン実行環境 │
│ • プロバイダー抽象化レイヤー │
└──────────────────────────────────────────────────────────────────┘
```
### 設計原則
- **プロセス分離**:AIランタイムは別プロセスで動作し、重い計算中もUIの応答性を保ちます。
- **フロントエンド呼び出しの単一入口**:Rendererのリクエストは`host-api` / `api-client`を経由し、プロトコルの詳細は安定したインターフェースの背後に隠されます。
- **Mainプロセスによるトランスポート管理**Electron MainがACP Chat stdio bridgeとGatewayトランスポートを所有し、Rendererは型付きIPCでMainと通信します。
- **拡張IPCの貢献点**Mainプロセス拡張はHTTP routeではなく、型付きIPCレジストリを通じてhost-api actionを提供します。
- **グレースフルリカバリ**:再接続、タイムアウト、バックオフを内蔵し、一時的な障害を自動処理します。
- **セキュアストレージ**:APIキーや機密データにはOSのネイティブな安全な保存機構を使用します。
- **CORSセーフ設計**RendererはローカルGatewayやHost API HTTPエンドポイントを直接呼び出しません。
### プロセスモデルとGatewayのトラブルシューティング
- ClawXはElectronアプリのため、**1つのアプリインスタンスでも複数のOSプロセスが表示される**main/renderer/zygote/utility)のは正常です。
- 単一起動保護にはElectronのロックに加えてローカルのプロセスファイルロックのフォールバックを使用し、デスクトップIPCやセッションバスが不安定な環境での二重起動を防ぎます。
- ローリングアップグレード中に旧版と新版が混在すると、単一起動保護が非対称になる場合があります。安定性のため、すべてのデスクトップクライアントを同じバージョンへ更新してください。
- OpenClaw Gatewayのリスナーは**単一所有者**である必要があります。`127.0.0.1:18789`をListenするプロセスは1つだけにしてください。
- Gatewayのreadinessは`system-presence``health``status`などOpenClawのコア信号を基準にします。メモリまたはチャネルの失敗は、Gateway全体の障害ではなく機能低下として表示されます。
- アクティブなリスナーは次のコマンドで確認できます。
- macOS/Linux`lsof -nP -iTCP:18789 -sTCP:LISTEN`
- WindowsPowerShell):`Get-NetTCPConnection -LocalPort 18789 -State Listen`
- ウィンドウの閉じるボタン(`X`)はClawXをトレイに隠すだけで、完全終了ではありません。完全終了にはトレイメニューの **Quit ClawX** を使用してください。
+130
View File
@@ -0,0 +1,130 @@
# ClawX開発ガイド
このドキュメントは、READMEの「開発」セクションの詳細版です。
### 前提条件
- **Node.js**:対応するメジャー系列の22.22.3以上、24.15.0以上、または25.9.0以上(Node 24 LTS推奨)
- **パッケージマネージャー**:pnpm 9以上(npmも対応)
- **LinuxUbuntu/Debian**Electronを実行する前に必要なシステムライブラリをインストールしてください。
```bash
sudo apt-get install -y libnss3 libgtk-3-0 libxss1 libxtst6 libatspi2.0-0 libnotify4 xdg-utils
```
Ubuntu 24.04以降では一部のパッケージに`t64`サフィックスが付きます。上記コマンドを実行すると、`apt`が適切なバリアントを自動選択します。
### プロジェクト構成
```text
ClawX/
├── electron/ # Electron Mainプロセス
│ ├── services/ # 型付きHost API、プロバイダー、秘密情報、ランタイムサービス
│ │ ├── providers/ # プロバイダー/アカウントのモデル同期ロジック
│ │ └── secrets/ # OSキーチェーンと秘密情報の保存
│ ├── shared/ # 共有プロバイダースキーマ/定数
│ │ └── providers/
│ ├── main/ # アプリ入口、ウィンドウ、IPC登録
│ ├── gateway/ # OpenClaw Gatewayプロセスマネージャー
│ ├── preload/ # セキュアIPCブリッジ
│ └── utils/ # ストレージ、認証、パスのユーティリティ
├── src/ # React Rendererプロセス
│ ├── lib/ # フロントエンド統合APIとエラーモデル
│ ├── stores/ # Zustandストア(settings/chat/gateway
│ ├── components/ # 再利用可能なUIコンポーネント
│ ├── pages/ # Setup/Dashboard/Chat/Channels/Skills/Cron/Settings
│ ├── i18n/ # ローカライズリソース
│ └── types/ # TypeScript型定義
├── tests/
│ ├── e2e/ # Playwright Electron E2Eスモークテスト
│ └── unit/ # Vitestユニット/統合系テスト
├── resources/ # 静的アセット(アイコン、画像)
└── scripts/ # ビルドとユーティリティのスクリプト
```
### 利用可能なコマンド
```bash
# 開発
pnpm run init # 依存関係をインストールし、同梱バイナリ(uv、agent-browser)をダウンロード
pnpm dev # ホットリロードで起動(不足時は同梱スキルを自動準備)
# 品質
pnpm lint # ESLintを実行
pnpm typecheck # TypeScriptを検証
# テスト
pnpm test # ユニットテストを実行
pnpm run test:e2e # Electron E2Eスモークテストを実行
pnpm run test:e2e:headed # 表示可能なウィンドウでElectron E2Eテストを実行
pnpm run perf:chat # 合成Chat Renderer/Main CPUプロファイルを取得
pnpm run profile:main # Main inspectorを9229番ポートで起動したビルド済みアプリを実行
pnpm run comms:replay # 通信リプレイ指標を算出
pnpm run comms:baseline # 通信ベースラインスナップショットを更新
pnpm run comms:compare # リプレイ指標をベースラインの閾値と比較
# ビルドとパッケージ
pnpm run build:vite # フロントエンドのみをビルド
pnpm build # パッケージアセットを含む本番ビルド
pnpm package # 現在のプラットフォーム向けにパッケージ化(同梱スキルを含む)
pnpm package:mac # macOS向けにパッケージ化
pnpm package:win # Windows向けにパッケージ化
pnpm package:linux # Linux向けにパッケージ化
```
ヘッドレスLinuxではElectronテストに表示サービスが必要です。`xvfb-run -a pnpm run test:e2e`を使用してください。
Electron E2E機能テストはローカルとCIの両方で既定で2つのPlaywright workerを使用します。通常の並列レーンは`CLAWX_E2E_WORKERS=<正の整数>`で調整できます。OS全体の状態に触れるテストは1 workerの`exclusive`プロジェクトを使用し、ホストのパフォーマンスプロファイルはその後単独で実行されます。新しいE2Eテストは既定で並列です。実際のクリップボードなどマシン全体で共有されるリソースを使う場合は、`tests/e2e/parallel-policy.ts`の`E2E_EXCLUSIVE_TAG`を適用してください。
独占前提を必要としない通常のspecだけを実行する場合は、`pnpm exec playwright test <spec> --project=parallel --no-deps`を使用します。
### Electronパフォーマンス診断
`pnpm run perf:chat`は、ストリーミングとリッチな静的Markdownサイドバー/スクロール操作を対象に、分離された合成ACP負荷を実行します。Playwrightの`test-results/`ディレクトリにバージョン付きメトリクスとRenderer/Main CPUプロファイルを書き込みます。Rendererプロファイルは本番のstore/render経路とフレームペーシングを対象とします。ストリーミングMainプロファイルはMainからRendererへのIPC fanoutを測定し、操作用MainプロファイルはRenderer操作中にMainがアイドル状態を保つかを示します。どちらも上流のOpenClaw/ACPサブプロセスやGPUプロセスの経路は含みません。
CPUプロファイルはChrome DevToolsで開けます。アーティファクトには生成されたfixtureテキストだけが含まれ、製品テレメトリーではありません。結果はハードウェアに依存するため、単一のクロスプラットフォーム絶対閾値ではなく、同じマシンで繰り返した結果を比較してください。
実際のRendererを記録するには、`CLAWX_REMOTE_DEBUGGING_PORT=9223 pnpm dev`で開発環境を起動し、PlaywrightまたはChrome DevToolsを`localhost:9223`へ接続します。実際のElectron Mainを記録するには`pnpm run profile:main`を実行し、`chrome://inspect`で`localhost:9229`を設定してElectron Mainターゲットを選びます。WebSocket trace自体を測定する場合を除き、`CLAWX_GATEWAY_WS_TRACE`は設定しないでください。
ClawXは既定でChromiumのハードウェアアクセラレーションを有効にし、長い文書、スクロール、レイアウトアニメーションでGPUコンポジットとラスタライズを利用します。グラフィックスドライバーに問題がある場合のトラブルシューティングには、Chromium標準の`--disable-gpu`コマンドラインスイッチを使用できます。
### 通信回帰チェック
Gatewayイベント、ACP Chat bridgeの送受信フロー、チャネル配信、トランスポートフォールバックなどの通信経路をPRで変更した場合は、次を実行してください。
```bash
pnpm run comms:replay
pnpm run comms:compare
```
CIの`comms-regression`ジョブが必須シナリオと閾値を検証します。
### Electron E2Eテスト
Playwright Electronスイートは`dist/`と`dist-electron/`からパッケージ済みのRendererとMainプロセスを起動するため、事前に`pnpm dev`を手動実行する必要はありません。
`pnpm run test:e2e`は自動的に次を行います。
- `pnpm run build:vite`でRendererとElectronのバンドルをビルド
- 一時的な`HOME`を使ってElectronを分離E2Eモードで起動
- 一時的なClawX `userData`ディレクトリを使用
- OS全体のリソースとパフォーマンステストを隔離しながら、通常のspecファイルを並列実行
- Gateway自動起動、同梱スキルのインストール、トレイ作成、CLI自動インストールなど、重い起動副作用をスキップ
最初のベースラインspecは次を対象とします。
- 新しいプロファイルでの初回起動Setup Wizardの表示
- セットアップをスキップし、Electronアプリ内でModelsページへ移動できること
今後のElectronフローは`tests/e2e/`に追加し、`tests/e2e/fixtures/electron.ts`の共有fixtureを再利用してください。固定の書き込みパス、ポート、ネイティブキーチェーン、その他の外部共有状態を避けてテストを並列安全に保ちます。分離できない場合は`E2E_EXCLUSIVE_TAG`を使用してください。
### 技術スタック
| レイヤー | 技術 |
|---------|------|
| ランタイム | Electron 40+ |
| UIフレームワーク | React 19 + TypeScript |
| スタイリング | Tailwind CSS + shadcn/ui |
| 状態管理 | Zustand |
| ビルド | Vite + electron-builder |
| テスト | Vitest + Playwright |
| アニメーション | Framer Motion |
| アイコン | Lucide React |
+83
View File
@@ -0,0 +1,83 @@
# ClawXの機能
このドキュメントは、READMEの「機能」セクションの詳細版です。
### ゼロ設定バリア
インストールから最初のAI会話まで、直感的なグラフィカルインターフェースですべてのセットアップを完了できます。ターミナルコマンド、YAMLファイル、環境変数の探索は不要です。
### インテリジェントチャットインターフェース
モダンなチャット体験を通じてAIエージェントとコミュニケーションできます。複数の会話コンテキストとメッセージ履歴に対応し、エージェントの返信は、シンタックスハイライト付きのフェンスコード、CJK対応の解析、GitHub風テーブル、KaTeXによるLaTeX数式(`$インライン$``$$ブロック$$``\(インライン\)``\[ブロック\]`)を含むストリーミングMarkdownとして描画されます。ユーザー入力は常にプレーンテキストとして扱われます。マルチエージェント構成では、メインのコンポーザーから `@agent` で対象エージェントへ直接ルーティングできます。フェンスコードはソースの改行を保持し、長い行をソフトラップし、ストリーミング完了後にローカライズされたコピー操作を提供します。
コンポーザーから挿入したスキルは `/skill-name` カードとして表示されます。カードをクリックすると右側のプレビューサイドバーが開き、そのスキルの `SKILL.md` を読めます。
`@agent` で別のエージェントを指定すると、ClawXはデフォルトエージェントを経由せず、そのエージェント自身の会話コンテキストへ直接切り替えます。エージェントのワークスペースは既定で分離されますが、より強い実行時分離はOpenClawのsandbox設定に依存します。
セッションサイドバーはワークスペース優先で構成されます。既定のワークスペースが先頭に固定され、その他のワークスペースは自然な順序で並びます。各ワークスペースは折りたたんだり、セッションを追加読み込みしたりできます。AIが返信中のセッション行にはスピナーが表示され、未確認の返信が完了すると青い点が表示されます。会話を開いた後は相対的なアクティビティ時刻が表示され、ホバーすると行の操作が表示されます。インポートしたワークスペースはサイドバーの見出しから名前を変更できます。カスタム名はチャットコンポーザーにも反映され、見出しにホバーするとファイルシステムのパスを確認できます。
有効なワークスペースが選択されている場合、新しいチャットは最初の送信まで編集可能な状態でそのワークスペースを引き継ぎます。編集可能な新規チャットまたは未バインドのチャットでは、コンポーザーのワークスペースチップから、最近使用したワークスペースと既知のセッションワークスペースの一覧を開けます。既定のワークスペースへ戻ることも、別のフォルダーを選ぶこともできます。保存済みのワークスペースフォルダーが移動または削除された場合、Chatはセッション作成を一時停止し、無効なパスを繰り返し再試行せず、既存のフォルダーを選ぶよう案内します。利用できない既定以外のグループにはサイドバーで印が付き、確認後に削除できます。この操作ではグループ内のすべてのセッションが完全に削除されます。セッション行の削除と画面遷移は完全削除が成功した後にのみ行われます。失敗した場合は会話と確認ダイアログが保持され、再試行できます。OpenClawが生成するUUIDと日付のフォールバックタイトルは、セッションIDと一致する場合に限り欠落タイトルとして扱われ、セッション名として保存せず、会話の最初のユーザーメッセージに置き換えて表示します。
各エージェントは自身の `provider/model` 実行時設定を上書きできます。上書きしていないエージェントはグローバルの既定モデルを引き続き継承します。
Chat右側パネルのWorkspaceとPreviewタブでは、Markdown、`.docx``.pptx`を読み取り専用でプレビューできます。Markdownのプレビューは静的レンダリングモードで、シンタックスハイライト、ソフトラップ、コピー可能なフェンスコード、CJK対応解析、KaTeX数式をサポートします。プレビューのヘッダーから選択中のファイルをClawXの表示領域全体へ拡大できます。同じボタンまたはEscapeキーでパネルへ戻れます。従来形式の`.doc``.ppt`はアプリ内ではなくOS経由で開きます。DOCXのページ区切りはMicrosoft Wordと異なる場合があり、PPTXプレビューではアニメーション、画面切り替え、メディア再生をサポートしません。20 MBを超えるOfficeファイルはアプリ内でプレビューされません。
### ローカルHTMLプレビュー
Chat右側パネルにはWorkspace、Preview、Changesタブがあります。汎用Webブラウザ、ホーム画面、アドレスバーは提供されません。許可されたローカル`.html``.htm`の添付ファイル、ファイルアクティビティ、Workspaceファイルは既定でPreviewに開きます。ファイル操作ではClawX内蔵のPreviewまたはシステムアプリを選択でき、Previewのヘッダーから現在のHTMLファイルをシステムブラウザで開くこともできます。
すべてのリンクはクリックできません。ClawXが描画するリンクは通常のテキストとして表示され、HTML Preview内のリンクからもリンク装飾とポインター操作が除去されます。HTML Previewはフォーム、スクリプトによる移動、リダイレクト、ページ内移動、ポップアップ、ダウンロード、ネットワーク要求、デバイス権限もブロックします。自己完結したローカルHTMLは表示できますが、選択中の文書から移動することはできません。
### マルチチャネル管理
複数のAIチャネルを同時に設定・監視できます。各チャネルは独立して動作するため、異なるタスクに特化したエージェントを実行できます。
各チャネルは複数アカウント、アカウント単位のAgent紐付け、Channelsページからの既定アカウント切り替えに対応しています。
カスタムチャネルアカウントIDには、ルーティング不一致を防ぐため、OpenClaw互換の正規形式(`[a-z0-9_-]`、小文字、最大64文字、先頭は英字または数字)を必須としています。
ClawXにはTencent公式の個人WeChatチャネルプラグインも同梱されており、Channelsページからアプリ内QRフローでWeChatを直接連携できます。
### Cronベースの自動化
AIタスクを自動的に実行するようスケジュール設定できます。トリガーと間隔を定義し、AIエージェントを常時稼働させられます。
Cronページでは、送信アカウントと受信先ターゲットを別々に選択して、タスクフォームから外部配信を直接設定できます。対応チャネルでは、受信先ターゲットがチャネルディレクトリまたは既知のセッション履歴から自動検出されるため、`jobs.json`を手動編集する必要はありません。タスクメッセージ欄では、メインのチャットコンポーザーと同じインライン `/skill` トークン構文で、選択したエージェントのスキルを挿入できます。これにより、スケジュール済みプロンプトからスキルを直接起動できます。
スケジュール選択は**繰り返し**と**1回のみ**のタブに分かれています。繰り返しでは毎時、毎日、平日、毎週、カスタム(生のcron)を時刻・曜日コントロール付きで選択できます。1回のみでは、曜日が表示された指定日と時刻に一度だけ実行します。1回のみのタスクは未来の時刻を指定する必要があり、完了後はランタイムによって自動削除されます。
### 拡張可能なスキルシステム
事前構築されたスキルでAIエージェントを拡張できます。統合Skillsページはローカル優先で、管理ディレクトリとworkspaceのスキルディレクトリをスキャンし、Gatewayに依存せずスキルを有効化・無効化できます。エンタープライズ拡張では、拡張機能が提供するマーケットプレイスを表示することもできます。
ClawXはドキュメント処理スキル(`pdf``xlsx``docx``pptx`)を完全な形で同梱し、起動時に管理スキルディレクトリ(既定は`~/.openclaw/skills`)へ自動配備し、初回インストール時に既定で有効化します。
Skillsページでは、管理ディレクトリ、workspace、追加スキルディレクトリなど、複数のOpenClawソースから検出されたスキルを表示できます。各スキルの実際の場所も表示されるため、実フォルダーを直接開けます。OpenClaw同梱のbundled skillについて、コミュニティ版では`skill-creator`だけをパッケージと画面に残します。許可リストにないbundled skillは開発時とパッケージ版の起動時に物理的に削除され、削除済みスキルに対応する古い`openclaw.json`エントリも整理されます。
### セキュアなプロバイダー統合
OpenAI、Anthropic、Z.AI / GLMなど複数のAIプロバイダーに接続でき、認証情報はOSのネイティブキーチェーンに安全に保存されます。OpenAIはAPIキーとブラウザOAuth(Codexサブスクリプション)の両方に対応しています。
開発者モードの専用Image Generationページでは、Base URL、APIキー、`gpt-image-2`などのモデル名を指定して、独立したOpenAI互換の画像生成エンドポイントを設定できます。画像生成は専用の`/v1/images/generations`サービスを使い、チャットは通常のOpenAIプロバイダーを使い続けられます。
OpenAI互換ゲートウェイで **Custom** プロバイダーを使う場合、互換性が必要なエンドポイント向けに **設定 → AI Providers → Providerを編集** からカスタム `User-Agent` を設定できます。
プロバイダーを編集または切り替える際、ClawXは `input: ["text", "image"]` など既存のモデル単位の能力メタデータを保持します。新しく選択したCustomプロバイダーのモデルにはOpenClaw onboarding互換の画像入力推論を適用し、不明なモデルはテキスト専用として扱います。
Customプロバイダーのモデル行には、モデルファミリーから推定した明示的な `contextWindow`(例:`gpt-5.x` → 272k)も付与されます。旧バージョンで保存された行は起動時に補完されるため、OpenClawは長いセッションが「Context overflow」エラーになる前に圧縮できます。圧縮設定がない場合、ClawXは `agents.defaults.compaction.mode = "safeguard"``reserveTokensFloor = 50000` を初期設定します。ユーザーが作成したモデル行や設定は変更されませんが、`reserveTokensFloor` が欠落している場合だけ補完されることがあります。
Z.AICN / Global)はOpenClaw組み込みの `zai` プロバイダー(`ZAI_API_KEY`)に対応し、既定モデルは `glm-5.2` です。Code PlanプリセットではCoding Planエンドポイント(`.../api/coding/paas/v4`)を、通常のAPIでは(`.../api/paas/v4`)を使います。CNとGlobalは同じOpenClawランタイムキーを共有するため相互排他的です。
互換ゲートウェイが認証以外の理由で`/models`を拒否した場合、ClawXはAPIキー検証時に設定済みモデルを使い、軽量な`/chat/completions`または`/responses`プローブへ自動フォールバックします。
### アダプティブテーマ
ライトモード、ダークモード、システム同期テーマを選択できます。ClawXは設定に自動的に適応します。
### 自動起動設定
**設定 → 一般**で **システム起動時に自動起動** を有効にすると、ログイン後にClawXが自動的に起動します。
### 更新通知
ClawXは起動時に新しいバージョンを確認します。更新が利用可能になるとアプリ内プロンプトを表示し、選択した場合にのみダウンロードとインストールを実行します。
+12
View File
@@ -0,0 +1,12 @@
# ClawXのプロキシ設定
このドキュメントは、READMEの「プロキシ設定」セクションの詳細版です。
- `host:port` だけの値はHTTPプロキシとして扱われます。
- 高度なプロキシ項目が空の場合、ClawXは **プロキシサーバー** にフォールバックします。
- プロキシ設定を保存すると、Electronのネットワーク設定が即座に再適用され、Gatewayが自動的に再起動します。
- Telegramが有効な場合、ClawXはプロキシをOpenClawのTelegramチャネル設定にも同期します。
- ClawXのプロキシが無効な状態で通常のGateway再起動が行われても、既存のTelegramチャネルプロキシは保持されます。
- OpenClaw設定からTelegramプロキシを明示的に削除するには、プロキシを無効にしてプロキシ設定を一度保存してください。
- **設定 → 詳細設定 → 開発者**では **OpenClaw Doctor** を実行できます。`openclaw doctor --json` を実行し、診断結果をアプリ内に表示します。
- Windowsのパッケージ版では、同梱の`openclaw` CLI/TUIは同梱の`node.exe`エントリーポイント経由で実行され、ターミナル入力の安定性を保ちます。
+113
View File
@@ -0,0 +1,113 @@
# Архитектура ClawX
Этот документ содержит подробную версию раздела «Архитектура» из README.
ClawX использует **двухпроцессную архитектуру с унифицированным уровнем Host API**. Renderer обращается к единой абстракции клиента, а Electron Main управляет выбором протокола и жизненным циклом процессов.
Доставка конфигурации OpenClaw также управляется Electron Main. Когда Gateway запущен, ClawX использует авторитетный снимок из `config.get` как основу и применяет изменения через `config.set`. Когда Gateway остановлен или запускается, тот же координатор обновляет разрешённый JSON5-файл конфигурации, не запуская Gateway из-за этого обновления. Поэтому обычные изменения провайдера, агента, канала, привязки, навыка и модели не заменяют процесс Gateway. Полные перезапуски остаются только для изменений среды запуска процесса, например прокси, и явных действий пользователя. Подтверждённые завершения процесса и закрытия WebSocket используют существующие пути автоматического переподключения. Первые три последовательных пропуска WebSocket heartbeat являются только диагностикой, поэтому краткая задержка pong не прерывает долгую операцию; pong или любое входящее сообщение сбрасывает счётчик, а при четвёртом последовательном пропуске запрашивается защищённое автоматическое восстановление Gateway, если его жизненный цикл находится в состоянии running с разрешённым автовосстановлением. После записи конфигурации аутентификации в SQLite ClawX вызывает `secrets.reload` OpenClaw, чтобы работающие агенты получили новые учётные данные без перезапуска процесса.
Chat использует ACP stdio bridge, принадлежащий Electron Main. Main передаёт тому же локальному дочернему процессу управляемый приложением Gateway token через приватное окружение процесса, поэтому после перезагрузки конфигурации среды выполнения воспроизведение истории ACP остаётся аутентифицированным. Если защищённое восстановление Gateway прерывает принятый run основной сессии, исправленная среда OpenClaw запускает отдельный восстановительный run с явной ссылкой на id прерванного run. События Chat и agent сохраняют эту связь; переподключившийся ACP bridge принимает новый run для ожидающего prompt, сбрасывает потоковые курсоры run и подписывается на события инструментов сессии. Renderer не использует идентификатор среды Gateway и продолжает строить одну ACP timeline в памяти из типизированных host events. Gateway продолжает отвечать за возможности вне Chat: providers, models, skills, workspace, settings, diagnostics и media configuration.
### Семантический авторитет ACP
ACP является предпочтительным семантическим источником для каждого значения и контекста Chat, которые он предоставляет, а не только для истории `session/load`. Сюда относятся, где применимо, идентификатор сессии и маршрутизация, рабочее пространство и исполняемый `cwd`, состояние prompt и timeline, а также семантика стандартных resource и вложений. Если ACP предоставляет значение или событие, Main и Renderer должны использовать его, а не заменять снимком Gateway, выводом из transcript, локальной конфигурацией или параллельной проекцией.
Обход ACP разрешён только тогда, когда в upstream нет эквивалентной возможности. Такой путь совместимости должен быть узким, ограниченным и привязанным к session и generation. В соответствующем Harness reference или rule необходимо указать причину, источник истины, ограничения, поведение согласования и условие удаления; обход не должен незаметно стать конкурирующим источником истины.
### Авторитет истории ACP и ограниченные дополнения из transcript
Воспроизведение ACP `session/load` является главным источником истории Chat. ClawX не сохраняет второй ACP ledger, сокращённую timeline, кэш воспроизведения или восстановленную историю инструментов. Если структурированный ACP event ledger OpenClaw недоступен, его ACP adapter преобразует сохранённые записи transcript `toolCall` и `toolResult` в нативные обновления инструментов в исходном порядке, сохраняя границы text-tool-text; сам ClawX эти записи не выводит. Некоторые возможности OpenClaw пока не имеют полного соответствия в ACP. Например, media assistant может отсутствовать в ACP, а обработка Gateway может удалять директивы assistant `MEDIA:` из видимого потокового ответа. Поэтому ClawX хранит только ограниченные, помеченные дополнения совместимости в памяти:
- Асинхронное завершение генерации изображения можно восстановить только при наличии подтверждённого контекста `image_generate` в той же сессии и доверенного либо разрешённого transcript-доказательства.
- Обычные вложения можно восстановить из канонических сохранённых фактов assistant `__openclaw.media` или явных директив assistant `MEDIA:` в начале строки. Восстанавливаются только ссылки на вложения и объявленные метаданные, но не окружающее сообщение assistant.
- Поскольку ACP replay не содержит исходных временных меток событий, Main может добавить метаданные длительности всего хода из ограниченных записей transcript JSONL. Они могут быть привязаны только к уже восстановленному ACP-ходу.
- Если ACP replay cron-сессии полностью пуст, типизированный API истории cron в Main может предоставить запланированный запрос и сводку завершения. Если сводка идентифицированного запуска содержит маркер усечения OpenClaw, Main может восстановить финальный текст assistant из transcript этого запуска только когда transcript длиннее и содержит полный сохранённый префикс сводки.
Историческое чтение ограничено последними 1000 сообщениями transcript. Успешный live prompt выполняет одно немедленное чтение и одну повторную попытку через 1500 мс. Каждое дополнение привязано к точной session, ACP generation, операции и, где применимо, текущему пользовательскому ходу; устаревшие, отсутствующие, дублирующиеся и неоднозначные совпадения отбрасываются. Эти пути не должны восстанавливать обычные сообщения assistant, thoughts, tools, plans, permissions, файловые операции, пропущенные ходы или параллельную историю Chat. Main не создаёт нативные события ACP из transcript-доказательств. Стандартные ACP resources остаются предпочтительными, а после появления эквивалентного контента upstream эти исключения совместимости должны быть удалены.
Незавершённый ответ ACP продолжает потоковую выдачу при открытии другого разговора или страницы. Возврат до завершения восстанавливает последнюю timeline в памяти и продолжает отображение ответа. После завершения обычное воспроизведение истории ACP остаётся источником истины.
Ходы assistant в ACP показывают длительность всего хода. Живой таймер следует за наблюдаемым клиентом жизненным циклом prompt и сохраняется при навигации внутри приложения. Историческая длительность вычисляется Electron Main по ограниченным временным меткам transcript OpenClaw и добавляется только к ходу, уже восстановленному ACP replay.
ACP Chat отображает стандартные ACP resources как вложения. Выбранные пользователем изображения показываются как миниатюры с именем файла при наведении, а другие доступные карточки вложений содержат имя файла и приглушённый обрезаемый исходный путь. Если текущий OpenClaw ACP adapter не передаёт media assistant, канонические сохранённые факты media OpenClaw и явные директивы assistant `MEDIA:` также могут быть восстановлены как карточки вложений без отображения метаданных, предназначенных только для transcript.
Существующие локальные ссылки на файлы, включая пути за пределами активного рабочего пространства, перед каждым предпросмотром или открытием повторно проверяются Electron Main для точной session и generation. Локальные вложения, созданные AI и доступные для предпросмотра, включая `.docx` и `.pptx` размером до 20 МБ, сохраняют основное действие предпросмотра только для чтения внутри приложения и дополнительное меню для открытия совместимым приложением или показа в Finder, File Explorer либо системном файловом менеджере. Для локальных HTML-вложений первый пункт меню открывает файл во вкладке Preview справа.
Для Office действуют те же ограничения: `.doc` и `.ppt` открываются системным приложением, разбиение DOCX на страницы может отличаться от Microsoft Word, а анимации, переходы и воспроизведение медиа в PPTX не поддерживаются. Поиск совместимых приложений доступен только в macOS и Windows; в Linux или при ошибке поиска происходит незаметный переход к действию показа расположения. Остальные локальные файлы, включая Office-файлы размером более 20 МБ, открываются системным приложением после нажатия пользователя. Выбранные пользователем папки остаются доступными после отправки и открываются системным файловым менеджером; ClawX не читает и не просматривает их содержимое. Вложения HTTP и HTTPS открываются внешне после нажатия. Обычные пути в тексте без канонических media-фактов не считаются вложениями.
ACP Chat также может показывать предпросмотр сгенерированных изображений, когда среда выполнения доставляет media генерации как доверенные структурированные данные. Доверенные OpenClaw internal-UI доставки и финальные ответы, связанные с задачей генерации, сохраняют исходный пользовательский текст завершения, включая текстовое описание ошибки, вместо замены на общий заголовок изображения. При историческом воспроизведении OpenClaw маркеры assistant `MEDIA:` переводятся в встроенный просмотр изображения только после зарегистрированного запуска задачи генерации в той же сессии. ClawX загружает предпросмотр через обработку media на стороне Electron Main, а не через произвольный доступ Renderer к файловой системе. Стандартные изображения и ресурсы ACP остаются предпочтительным путём и отображаются напрямую.
### Семантика файловых операций ACP
- Файловые операции проецируются из успешных завершённых вызовов OpenClaw `write`, `edit` и `apply_patch`. Распознавание инструментов соответствует официальному OpenClaw Chat UI; фильтрация только завершённых вызовов специфична для ClawX.
- Строки созданных и изменённых файлов используют ту же оболочку карточки и меню **Open with**, что и предпросматриваемые вложения assistant, сохраняя статус и необязательную сводку `+/-`. Для HTML первый пункт меню открывает файл во вкладке **Preview** справа. Удалённые строки сохраняют только действие **Changes**. Каждый запрос списка приложений, выбора приложения и показа расположения заново проверяется Electron Main по корню рабочего пространства и относительному пути. Пути из инструментов не становятся вложениями и не раскрывают Renderer канонические системные пути.
- `write` отображается так, как его объявляет инструмент: как создание с разницей из всех добавленных строк, даже если путь уже может существовать.
- **Changes** — это хронологическая запись объявленной инструментом активности на уровне сессии. Это не вывод Git и не проверенная разница относительно исходной базы.
- Для каждого файла Changes отображает не более одного diff-редактора на ход assistant. Последовательные фрагменты объединяются, если это безопасно; независимые фрагменты объединяются в один редактор без утверждения, что это полная разница относительно базовой версии файла.
- Побочные эффекты shell-команд, скриптов, пользователей или IDE не обнаруживаются.
- Полное ACP replay может восстановить записанные файловые операции. При неполном replay ClawX не выводит пропущенную активность через fallback.
```
┌──────────────────────────────────────────────────────────────────┐
│ Десктопное приложение ClawX │
│ │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ Главный процесс Electron │ │
│ │ • Управление жизненным циклом окна и приложения │ │
│ │ • Наблюдение за процессом Gateway │ │
│ │ • Интеграция с системой (трей, уведомления, связка ключей) │ │
│ │ • Оркестрация автообновлений │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬───────────────────────────────────┘
│ IPC (авторитетная плоскость управления)
┌──────────────────────────────────────────────────────────────────┐
│ Процесс Renderer на React │
│ • Современный компонентный UI (React 19) │
│ • Управление состоянием с Zustand │
│ • Унифицированные вызовы host-api/api-client │
│ • Ответы assistant в Markdown, ввод пользователя как обычный текст│
└──────────────────────────────┬───────────────────────────────────┘
│ Типизированные IPC-запросы
┌──────────────────────────────────────────────────────────────────┐
│ Main Host Services и Gateway Manager │
│ • Типизированный диспетчер сервисов host:invoke │
│ • Настройки, файлы, сессии, навыки, провайдеры, диагностика │
│ • WebSocket Gateway и наблюдение за процессом принадлежат Main │
└──────────────────────────────┬───────────────────────────────────┘
│ WebSocket под управлением Main
┌──────────────────────────────────────────────────────────────────┐
│ OpenClaw Gateway │
│ • Среда выполнения и оркестрация AI-агентов │
│ • Управление каналами сообщений │
│ • Среда выполнения навыков/плагинов │
│ • Уровень абстракции провайдеров │
└──────────────────────────────────────────────────────────────────┘
```
### Принципы проектирования
- **Изоляция процессов**: AI-среда выполнения работает в отдельном процессе, сохраняя отзывчивость UI даже при тяжёлых вычислениях.
- **Единая точка входа для фронтенда**: запросы Renderer проходят через `host-api` / `api-client`, а детали протокола скрыты за стабильным интерфейсом.
- **Транспорт принадлежит Main**: Electron Main владеет ACP Chat stdio bridge и транспортами Gateway; Renderer общается с Main через типизированный IPC.
- **Расширения через IPC**: расширения Main-процесса добавляют действия host-api через типизированный IPC-реестр, а не через HTTP routes.
- **Корректное восстановление**: встроенные переподключение, таймауты и backoff автоматически обрабатывают временные сбои.
- **Безопасное хранение**: API-ключи и конфиденциальные данные используют нативные механизмы безопасного хранения ОС.
- **CORS-безопасность**: Renderer не вызывает напрямую локальные HTTP-эндпоинты Gateway или Host API.
### Модель процессов и устранение неполадок Gateway
- ClawX — приложение Electron, поэтому **один экземпляр обычно отображается как несколько процессов ОС** (main/renderer/zygote/utility). Это нормально.
- Защита единственного экземпляра использует блокировку Electron и резервный локальный файл блокировки процесса, предотвращая дублирование запуска при нестабильном desktop IPC или сессионной шине.
- При последовательном обновлении смешанные старые и новые версии могут вести себя асимметрично. Для надёжности обновляйте все десктопные клиенты до одной версии.
- Слушатель OpenClaw Gateway должен иметь **единственного владельца**: только один процесс должен слушать `127.0.0.1:18789`.
- Готовность Gateway определяется основными сигналами OpenClaw, такими как `system-presence`, `health` и `status`. Ошибки памяти или каналов отображаются как снижение возможностей, а не как общий сбой Gateway.
- Проверить активный слушатель можно командами:
- macOS/Linux: `lsof -nP -iTCP:18789 -sTCP:LISTEN`
- Windows (PowerShell): `Get-NetTCPConnection -LocalPort 18789 -State Listen`
- Нажатие кнопки закрытия окна (`X`) скрывает ClawX в трее, но не завершает приложение. Для полного завершения используйте **Quit ClawX** в меню трея.
+130
View File
@@ -0,0 +1,130 @@
# Руководство по разработке ClawX
Этот документ содержит подробную версию раздела «Разработка» из README.
### Требования
- **Node.js**: 22.22.3+, 24.15.0+ или 25.9.0+ в пределах соответствующей основной версии (рекомендуется Node 24 LTS)
- **Менеджер пакетов**: pnpm 9+ (npm также поддерживается)
- **Linux (Ubuntu/Debian)**: перед запуском Electron установите необходимые системные библиотеки:
```bash
sudo apt-get install -y libnss3 libgtk-3-0 libxss1 libxtst6 libatspi2.0-0 libnotify4 xdg-utils
```
В Ubuntu 24.04+ некоторые пакеты используют суффикс `t64`; после выполнения команды `apt` автоматически выберет подходящий вариант.
### Структура проекта
```text
ClawX/
├── electron/ # Главный процесс Electron
│ ├── services/ # Типизированные Host API, провайдеры, секреты и runtime-сервисы
│ │ ├── providers/ # Логика синхронизации моделей provider/account
│ │ └── secrets/ # Связка ключей ОС и хранилище секретов
│ ├── shared/ # Общие схемы провайдеров и константы
│ │ └── providers/
│ ├── main/ # Точка входа приложения, окна и регистрация IPC
│ ├── gateway/ # Менеджер процесса OpenClaw Gateway
│ ├── preload/ # Безопасный IPC-мост
│ └── utils/ # Утилиты для хранилища, аутентификации и путей
├── src/ # Процесс Renderer на React
│ ├── lib/ # Унифицированный фронтенд API и модель ошибок
│ ├── stores/ # Хранилища Zustand (settings/chat/gateway)
│ ├── components/ # Переиспользуемые UI-компоненты
│ ├── pages/ # Setup/Dashboard/Chat/Channels/Skills/Cron/Settings
│ ├── i18n/ # Ресурсы локализации
│ └── types/ # Определения типов TypeScript
├── tests/
│ ├── e2e/ # Сквозные дымовые тесты Playwright Electron
│ └── unit/ # Модульные и интеграционные тесты Vitest
├── resources/ # Статические ресурсы (иконки и изображения)
└── scripts/ # Скрипты сборки и утилит
```
### Доступные команды
```bash
# Разработка
pnpm run init # Установить зависимости и скачать встроенные бинарные файлы (uv, agent-browser)
pnpm dev # Запуск с горячей перезагрузкой (автоподготовка bundled skills при отсутствии)
# Качество
pnpm lint # Запустить ESLint
pnpm typecheck # Проверить типы TypeScript
# Тестирование
pnpm test # Запустить модульные тесты
pnpm run test:e2e # Запустить дымовые E2E-тесты Electron
pnpm run test:e2e:headed # Запустить E2E-тесты Electron с видимым окном
pnpm run perf:chat # Получить синтетические CPU-профили Chat Renderer/Main
pnpm run profile:main # Запустить собранное приложение с Main inspector на порту 9229
pnpm run comms:replay # Рассчитать метрики повторного воспроизведения коммуникаций
pnpm run comms:baseline # Обновить снимок базовой линии коммуникаций
pnpm run comms:compare # Сравнить метрики с порогами базовой линии
# Сборка и упаковка
pnpm run build:vite # Собрать только фронтенд
pnpm build # Полная production-сборка с ресурсами упаковки
pnpm package # Упаковать для текущей платформы со встроенными навыками
pnpm package:mac # Упаковать для macOS
pnpm package:win # Упаковать для Windows
pnpm package:linux # Упаковать для Linux
```
В headless Linux тестам Electron нужен сервер отображения. Используйте `xvfb-run -a pnpm run test:e2e`.
Функциональные E2E-тесты Electron локально и в CI по умолчанию используют два worker-процесса Playwright. Обычную параллельную группу можно настроить через `CLAWX_E2E_WORKERS=<положительное целое>`. Тесты, затрагивающие глобальное состояние ОС, используют однопоточный проект `exclusive`, а профили производительности хоста запускаются отдельно после них. Новые E2E-тесты по умолчанию параллельны; при использовании реального буфера обмена или другого общего ресурса машины применяйте `E2E_EXCLUSIVE_TAG` из `tests/e2e/parallel-policy.ts`.
Для запуска отдельного обычного spec без эксклюзивного предварительного этапа используйте `pnpm exec playwright test <spec> --project=parallel --no-deps`.
### Диагностика производительности Electron
`pnpm run perf:chat` запускает изолированные синтетические ACP-нагрузки для потоковой выдачи и взаимодействия с боковой панелью и прокруткой в статическом Markdown-документе. В каталог Playwright `test-results/` записываются версионированные метрики и CPU-профили Renderer и Main. Профили Renderer охватывают production store/render-путь и плавность кадров. Потоковый профиль Main измеряет IPC fanout от Main к Renderer, а профиль интеракций показывает, остаётся ли Main свободным во время действий Renderer. Ни один профиль не включает процессы upstream OpenClaw/ACP или путь GPU-процесса.
CPU-профиль можно открыть в Chrome DevTools. Артефакты содержат только сгенерированный fixture-текст и не являются телеметрией продукта. Результаты зависят от оборудования, поэтому сравнивайте повторные запуски на одной машине, а не применяйте единый абсолютный порог для разных платформ.
Для записи реального Renderer запустите разработку командой `CLAWX_REMOTE_DEBUGGING_PORT=9223 pnpm dev` и подключите Playwright или Chrome DevTools к `localhost:9223`. Для записи реального Electron Main выполните `pnpm run profile:main`, откройте `chrome://inspect`, настройте `localhost:9229` и выберите цель Electron Main. Не устанавливайте `CLAWX_GATEWAY_WS_TRACE`, если измеряется не сам WebSocket trace.
ClawX по умолчанию оставляет аппаратное ускорение Chromium включённым, чтобы длинные документы, прокрутка и анимации layout использовали GPU-композицию и растеризацию. При проблемах с графическим драйвером можно использовать встроенный переключатель Chromium `--disable-gpu` как резервный вариант диагностики.
### Проверки регрессии коммуникаций
Если PR изменяет пути коммуникации, включая события Gateway, поток отправки/получения ACP Chat, доставку каналов или транспортный fallback, выполните:
```bash
pnpm run comms:replay
pnpm run comms:compare
```
Задача CI `comms-regression` проверяет обязательные сценарии и пороги.
### E2E-тесты Electron
Набор Playwright Electron запускает упакованные Renderer и Main-процессы из `dist/` и `dist-electron/`, поэтому заранее вручную запускать `pnpm dev` не требуется.
`pnpm run test:e2e` автоматически:
- собирает Renderer и бандлы Electron через `pnpm run build:vite`
- запускает Electron в изолированном E2E-режиме с временным `HOME`
- использует временный каталог `userData` ClawX
- запускает обычные spec-файлы параллельно, изолируя тесты глобальных ресурсов ОС и производительности
- пропускает тяжёлые побочные эффекты запуска, такие как автозапуск Gateway, установка bundled skills, создание трея и автоустановка CLI
Первые базовые spec покрывают:
- видимость Setup Wizard при первом запуске на чистом профиле
- пропуск настройки и переход на страницу Models внутри приложения Electron
Добавляйте будущие сценарии Electron в `tests/e2e/` и переиспользуйте общий fixture из `tests/e2e/fixtures/electron.ts`. Сохраняйте тесты безопасными для параллельного запуска: избегайте фиксированных доступных для записи путей, портов, нативных хранилищ ключей и другого внешнего общего состояния. Если изоляция невозможна, используйте `E2E_EXCLUSIVE_TAG`.
### Технологический стек
| Уровень | Технология |
|---------|------------|
| Среда выполнения | Electron 40+ |
| UI-фреймворк | React 19 + TypeScript |
| Стилизация | Tailwind CSS + shadcn/ui |
| Состояние | Zustand |
| Сборка | Vite + electron-builder |
| Тестирование | Vitest + Playwright |
| Анимация | Framer Motion |
| Иконки | Lucide React |
+83
View File
@@ -0,0 +1,83 @@
# Возможности ClawX
Этот документ содержит подробную версию раздела «Возможности» из README.
### Нулевой порог настройки
Весь процесс от установки до первого разговора с AI выполняется через интуитивный графический интерфейс. Терминальные команды, YAML-файлы и поиск переменных окружения не требуются.
### Интеллектуальный интерфейс чата
Общайтесь с AI-агентами через современный чат. ClawX поддерживает несколько контекстов разговоров и историю сообщений, а ответы агента отображаются как потоковый Markdown с подсветкой синтаксиса для fenced code, разбором CJK, таблицами GitHub-flavored и формулами LaTeX через KaTeX (`$строчные$`, `$$блочные$$`, `\(строчные\)` и `\[блочные\]`). Пользовательский ввод всегда остаётся обычным текстом. В многoагентных конфигурациях основное поле ввода поддерживает прямую маршрутизацию через `@agent`. Fenced code сохраняет исходные переводы строк, переносит длинные строки и предоставляет локализованное действие копирования после завершения потоковой выдачи.
Навыки, вставленные из композитора, отображаются как карточки `/skill-name`. Нажмите карточку, чтобы открыть боковую панель предпросмотра и прочитать `SKILL.md` этого навыка.
При выборе другого агента через `@agent` ClawX напрямую переключается в контекст этого агента, не передавая запрос через агента по умолчанию. Рабочие пространства агентов по умолчанию разделены, а более строгая изоляция среды выполнения зависит от настроек sandbox OpenClaw.
Боковая панель сессий организована по принципу «сначала рабочие пространства»: рабочее пространство по умолчанию находится вверху, остальные сортируются естественным образом, а каждое рабочее пространство можно свернуть или загрузить для него дополнительные сессии. Во время ответа AI в строке сессии отображается индикатор загрузки, после завершения непросмотренного ответа появляется синяя точка, а после открытия разговора снова показывается относительное время активности. При наведении отображаются действия строки. Импортированные рабочие пространства можно переименовать из заголовка боковой панели. Пользовательское имя отображается в композиторе чата, а при наведении на заголовок по-прежнему виден путь в файловой системе.
Если выбрано доступное рабочее пространство, новый чат наследует его и остаётся редактируемым до первой отправки. В редактируемых новых или ещё не привязанных чатах чип рабочего пространства в композиторе открывает меню с недавно использованными и известными из сессий рабочими пространствами. Можно вернуться к рабочему пространству по умолчанию или выбрать другую папку. Если сохранённая папка была перемещена или удалена, Chat приостанавливает создание сессии и предлагает выбрать существующую папку вместо повторных попыток использовать недоступный путь. Недоступные группы, кроме группы по умолчанию, отмечаются в боковой панели и могут быть удалены после подтверждения; это навсегда удаляет все сессии группы. Строка сессии удаляется, а навигация меняется только после успешного окончательного удаления. При ошибке удаления разговор и подтверждение остаются открытыми для повторной попытки. Синтетические резервные заголовки OpenClaw с UUID и датой считаются отсутствующими только при совпадении с ID сессии, после чего заменяются первым сообщением пользователя и не сохраняются как имя сессии.
Каждый агент может переопределить собственную настройку среды выполнения `provider/model`. Агенты без переопределения продолжают наследовать глобальную модель по умолчанию.
Вкладки Workspace и Preview на правой панели Chat предоставляют предпросмотр только для чтения файлов Markdown, `.docx` и `.pptx`. Предпросмотр Markdown в статическом режиме использует ту же подсветку синтаксиса, перенос длинных строк, копирование fenced code, разбор CJK и поддержку формул KaTeX. В заголовке Preview можно развернуть выбранный файл на весь видимый экран ClawX; тем же элементом управления или клавишей Escape можно вернуться на панель. Устаревшие `.doc` и `.ppt` по-прежнему открываются через операционную систему, а не внутри приложения. Разбиение DOCX на страницы может отличаться от Microsoft Word; предпросмотр PPTX не поддерживает анимации, переходы и воспроизведение медиа. Office-файлы размером более 20 МБ не просматриваются внутри приложения.
### Предпросмотр локального HTML
На правой панели Chat есть вкладки Workspace, Preview и Changes. Универсального веб-браузера, домашней страницы и адресной строки больше нет. Разрешённые локальные вложения `.html` и `.htm`, файловые операции и файлы рабочего пространства по умолчанию открываются в Preview. В действиях файла можно выбрать встроенный Preview или системное приложение, а заголовок Preview может открыть текущий HTML-файл в системном браузере.
Все ссылки некликабельны. Ссылки, отображаемые ClawX, выглядят как обычный текст; в HTML Preview также удаляются оформление ссылок и взаимодействие указателем. HTML Preview блокирует формы, переходы из скриптов, перенаправления, переходы внутри страницы, всплывающие окна, загрузки, сетевые запросы и разрешения устройств. Самодостаточный локальный HTML отображается, но не может покинуть выбранный документ.
### Управление несколькими каналами
Настраивайте и отслеживайте несколько AI-каналов одновременно. Каждый канал работает независимо, позволяя запускать специализированных агентов для разных задач.
Каждый канал поддерживает несколько аккаунтов, привязку агента к аккаунту и переключение аккаунта канала по умолчанию прямо на странице Channels.
Для пользовательских ID аккаунтов каналов ClawX требует совместимый с OpenClaw канонический формат: `[a-z0-9_-]`, строчные буквы, максимум 64 символа, начало с буквы или цифры. Это предотвращает ошибки маршрутизации.
ClawX также включает официальный плагин личного WeChat от Tencent, поэтому WeChat можно подключить прямо на странице Channels через встроенный QR-код.
### Автоматизация по расписанию
Планируйте автоматический запуск AI-задач. Определяйте триггеры и интервалы, чтобы AI-агенты могли работать круглосуточно.
На странице Cron внешнюю доставку можно настроить непосредственно в форме задачи с отдельными селекторами аккаунта отправителя и цели получателя. Для поддерживаемых каналов цели получателей автоматически обнаруживаются из каталогов каналов или известной истории сессий, поэтому больше не нужно вручную редактировать `jobs.json`. Поле сообщения задачи поддерживает вставку навыков тем же синтаксисом встроенных токенов `/skill`, что и основной композитор чата, с учётом выбранного агента. Запланированные запросы могут запускать навыки напрямую.
Выбор расписания разделён на вкладки **Повтор** и **Однократно**. Повтор предлагает частоты «Ежечасно», «Ежедневно», «По будням», «Еженедельно» и «Свой» (произвольный cron) со встроенным выбором времени и дня недели. Однократно запускает задачу один раз в выбранные дату и время с отображением дня недели. Одноразовые задачи должны быть запланированы на будущее и автоматически удаляются средой выполнения после завершения.
### Расширяемая система навыков
Расширяйте возможности AI-агентов готовыми навыками. Встроенная страница Skills работает по принципу local-first: сканирует управляемые каталоги и каталоги рабочего пространства и позволяет включать или отключать навыки без зависимости от Gateway. В корпоративных сборках расширение также может предоставить собственный маркетплейс.
ClawX предварительно упаковывает полные навыки обработки документов (`pdf`, `xlsx`, `docx`, `pptx`), автоматически развёртывает их в управляемый каталог навыков (по умолчанию `~/.openclaw/skills`) при запуске и включает их по умолчанию при первой установке.
На странице Skills можно показывать навыки из нескольких источников OpenClaw, включая управляемый каталог, workspace и дополнительные каталоги навыков. Для каждого навыка отображается фактическое расположение, чтобы папку можно было открыть напрямую. Для bundled skills OpenClaw в community-сборках упаковывается и отображается только `skill-creator`; bundled skills, отсутствующие в списке разрешённых, физически удаляются при запуске в режиме разработки и в packaged-сборках, а устаревшие записи для удалённых навыков в `openclaw.json` очищаются.
### Безопасная интеграция провайдеров
Подключайтесь к нескольким AI-провайдерам, включая OpenAI, Anthropic и Z.AI / GLM; учётные данные безопасно хранятся в нативном системном хранилище ключей. OpenAI поддерживает API-ключи и браузерный OAuth для подписок Codex.
В режиме разработчика отдельная страница Image Generation поддерживает независимый OpenAI-совместимый эндпоинт генерации изображений с Base URL, API-ключом и именем модели, например `gpt-image-2`. Поэтому генерация изображений может использовать отдельный сервис `/v1/images/generations`, а чат продолжает использовать обычный OpenAI-провайдер.
Для **Custom**-провайдеров, работающих с OpenAI-совместимыми шлюзами, можно задать собственный `User-Agent` в разделе **Настройки → AI-провайдеры → Редактировать провайдер** для эндпоинтов с требованиями к совместимости.
При редактировании или переключении провайдера ClawX сохраняет существующие метаданные возможностей модели, например `input: ["text", "image"]`. Для новых моделей Custom-провайдера используется совместимая с OpenClaw onboarding логика определения поддержки изображений; неизвестные модели считаются текстовыми.
Строки моделей Custom-провайдера также получают явный `contextWindow`, рассчитанный по семейству модели, например `gpt-5.x` → 272k. Строки, сохранённые старыми версиями, дополняются при запуске, чтобы OpenClaw мог сжимать длинные сессии до ошибки «Context overflow». Если настройки сжатия отсутствуют, ClawX создаёт `agents.defaults.compaction.mode = "safeguard"` и `reserveTokensFloor = 50000`. Созданные пользователем строки и конфигурации не изменяются, кроме возможного дополнения отсутствующего `reserveTokensFloor`.
Z.AI (CN / Global) соответствует встроенному провайдеру OpenClaw `zai` (`ZAI_API_KEY`). Модель по умолчанию — `glm-5.2`. Пресет Code Plan использует эндпоинты Coding Plan (`.../api/coding/paas/v4`), а обычные API — (`.../api/paas/v4`). CN и Global взаимоисключающие, поскольку используют один ключ среды выполнения OpenClaw.
Если совместимый шлюз отклоняет `/models` по причинам, не связанным с аутентификацией, ClawX во время проверки API-ключа автоматически переключается на лёгкий зонд `/chat/completions` или `/responses` с настроенной моделью.
### Адаптивные темы
Выбирайте светлую, тёмную или синхронизированную с системой тему. ClawX автоматически адаптируется к вашим предпочтениям.
### Управление автозапуском
В разделе **Настройки → Общие** включите **Запускать при старте системы**, чтобы ClawX автоматически запускался после входа в систему.
### Запросы на обновление
ClawX проверяет наличие новых версий при запуске. Если обновление доступно, приложение показывает запрос; скачивание и установка выполняются только после вашего выбора.
+12
View File
@@ -0,0 +1,12 @@
# Настройки прокси ClawX
Этот документ содержит подробную версию раздела «Настройки прокси» из README.
- Значение в формате `host:port` рассматривается как HTTP-прокси.
- Если расширенные поля прокси пусты, ClawX использует **Прокси-сервер**.
- Сохранение настроек прокси немедленно повторно применяет сетевые настройки Electron и автоматически перезапускает Gateway.
- При включённом Telegram ClawX также синхронизирует прокси с конфигурацией канала Telegram в OpenClaw.
- Если прокси ClawX отключён, обычный перезапуск Gateway сохраняет существующий прокси канала Telegram.
- Чтобы явно удалить прокси Telegram из конфигурации OpenClaw, отключите прокси и один раз сохраните настройки прокси.
- В разделе **Настройки → Дополнительно → Разработчик** можно запустить **OpenClaw Doctor**. Он выполняет `openclaw doctor --json` и показывает диагностический вывод в приложении.
- В упакованных сборках Windows встроенный `openclaw` CLI/TUI запускается через поставляемую точку входа `node.exe`, чтобы сохранить стабильное поведение ввода в терминале.
+110
View File
@@ -0,0 +1,110 @@
# ClawX 系统架构
本文档是 README「系统架构」一节的详细说明。
ClawX 采用 **双进程 + Host API 统一接入架构**。渲染进程只调用统一客户端抽象,协议选择与进程生命周期由 Electron 主进程统一管理:
OpenClaw 配置交付也统一由 Electron Main 管理。Gateway 运行时,ClawX 以 `config.get` 返回的权威快照为基线,并通过 `config.set` 提交修改;Gateway 停止或启动中时,同一个协调器只更新解析后的 JSON5 配置文件,不会因此启动 Gateway。因此,普通的 Provider、Agent、Channel、绑定、Skill 和模型修改不会替换 Gateway 进程。完整重启仅保留给代理等进程启动环境变化和用户显式操作。已确认的进程退出与 WebSocket 关闭继续使用现有的自动重连路径。连续前 3 次 WebSocket 心跳无响应只更新诊断,不会因短暂的 pong 延迟中断长时间运行的任务;收到 pong 或任意消息会重置计数,连续第 4 次无响应时,只有在生命周期处于可自动恢复的 running 状态时,才会请求受保护的 Gateway 自动恢复。认证配置写入 SQLite 后,ClawX 会调用 OpenClaw 的 `secrets.reload`,让运行中的 Agent 无需重启即可读取新凭据。
Chat 使用由 Electron Main 持有的 ACP stdio bridge。Main 通过私有进程环境把同一份应用管理的 Gateway token 传给本地子进程,因此运行时配置重载后 ACP 历史回放仍能完成认证。如果受保护的 Gateway 恢复中断了已接收的主会话 run,补丁后的 OpenClaw 运行时会启动独立的恢复 run,并显式携带被中断 run id 作为 lineage。Chat 和 agent events 会保留该 lineage;重连后的 ACP bridge 据此将 pending prompt 接续到新 run,重置该 run 的流式游标,并订阅会话级 tool events。Renderer 不感知 Gateway 运行实例身份,仍通过类型化 host events 渲染同一个内存 ACP timeline。Gateway 继续负责 providers、models、skills、workspace、settings、diagnostics 和 media configuration 等非 Chat 能力。
### ACP 语义权威
对于 ACP 能够提供的每一种 Chat 语义和上下文,ACP 都是优先的语义权威。这包括适用时的 session identity 与路由、工作空间和执行 `cwd`、prompt 与 timeline 状态,以及标准 resource 或附件语义。ACP 提供值或事件时,Main 和 Renderer 必须使用 ACP 的结果,不得用 Gateway 快照、transcript 推断、本地配置或另一套并行投影替代。
只有在上游 ACP 没有对应能力时,才允许绕过 ACP。此类兼容性路径必须保持狭窄、有界,并绑定 session 和 generation;同时必须在相关 Harness reference 或 rule 中记录其原因、事实来源、限制、协调行为和移除条件,不得悄悄演变为竞争性的权威来源。
### ACP 历史权威与有界 transcript 补充
ACP `session/load` 回放是 Chat 历史的首要事实来源。ClawX 不会持久化第二套 ACP ledger、精简 timeline、回放缓存或重建的工具历史。当 OpenClaw 的结构化 ACP event ledger 不可用时,其 ACP adapter 会按 transcript 顺序把持久化的 `toolCall``toolResult` 记录重建为原生工具更新,并保留 text-tool-text 边界;ClawX 本身不会推断这些记录。OpenClaw 的部分能力目前还没有完全对应的 ACP 实现;例如,assistant 媒体可能不会出现在 ACP 中,Gateway 处理也可能从可见的实时回复中移除 assistant `MEDIA:` 指令。因此,ClawX 只保留有界、带标记、仅存于内存的兼容性补充路径:
- 只有在同一 session 中存在已确认的 `image_generate` 上下文,且完成证据可信或来自获准 transcript 证据时,才可以恢复异步图像生成结果。
- 普通附件可以从持久化的 assistant `__openclaw.media` 规范事实或明确的行首 assistant `MEDIA:` 指令中恢复。这只恢复附件引用和声明的元数据,不恢复周围的 assistant 消息。
- 由于 ACP 回放不提供原始事件时间戳,Main 可以从有界的 transcript JSONL 记录中补充仅包含元数据的整轮耗时,但只能标注已经由 ACP 回放恢复出的回合。
- 如果 cron session 的 ACP 回放完全为空,Main 的类型化 cron-history API 可以提供计划提示词和完成摘要。当已识别的运行摘要带有 OpenClaw 截断标记时,只有在对应 run 的 transcript 更长且共享完整的已持久化摘要前缀时,Main 才可以恢复最终 assistant 文本。
历史读取最多读取最近 1000 条 transcript 消息。一次成功的实时 prompt 会立即读取一次,并在 1500ms 后重试一次。每个补充路径都必须绑定精确的 session、ACP generation、补充操作,并在适用时绑定当前的用户回合;过期、缺失、重复或有歧义的匹配都会被丢弃。这些路径不得重建普通 assistant 消息、thought、tool、plan、permission、文件活动、缺失回合或另一套 Chat 历史,Main 也不得根据 transcript 伪造原生 ACP 事件。标准 ACP resource 仍是首选;上游提供等价内容后,这些兼容性例外应当移除。
打开其它会话或页面时,尚未完成的 ACP 回复仍会继续流式接收。若在回复完成前返回,ClawX 会恢复最新的内存 timeline 并继续显示实时输出;回复完成后,普通 ACP 历史回放仍是唯一事实来源。
ACP assistant 回合会显示整轮耗时。Live 计时跟随客户端观测到的 prompt 生命周期,并在应用内导航后保持连续;历史耗时由 Electron Main 根据有界的 OpenClaw transcript 时间戳计算,而且只能标注 ACP 回放已经恢复出的回合。
ACP Chat 会将标准 ACP resource 渲染为附件。用户选择的图片会显示为缩略图,并在悬停蒙层中显示文件名;其它可用的附件卡片会显示文件名,以及灰色、可截断的来源路径。当前 OpenClaw ACP adapter 遗漏 assistant 媒体时,OpenClaw 持久化的规范媒体事实和显式 assistant `MEDIA:` 指令也可恢复为附件卡片,且不会显示仅用于 transcript 的元数据。现有本地文件引用(包括当前 workspace 外的路径)在每次预览或打开前,都会由 Electron Main 按精确的 session 和 generation 重新验证。AI 生成且可预览的本地附件(包括不超过 20 MB 的 `.docx``.pptx` 文件)会保留主要的只读应用内预览操作,并提供次级菜单,可通过兼容应用打开,或在 Finder、文件资源管理器或系统文件管理器中显示。对于本地 HTML 附件,该菜单第一项会在右侧预览中打开文件。Office 预览在此处也有相同限制:`.doc``.ppt` 仍通过系统应用打开,DOCX 的分页效果可能与 Microsoft Word 不同,PPTX 的动画、切换效果和媒体播放不受支持。兼容应用发现仅在 macOS 和 Windows 上可用;在 Linux 上或发现失败时,会静默降级为仅显示文件位置。其它本地文件(包括超过 20 MB 的 Office 文件)会在用户点击后通过系统应用打开。用户选择的文件夹附件在发送后也会保持可用,点击后交给系统文件管理器打开;ClawX 不会读取或预览其中内容。远程 HTTP 和 HTTPS 附件会在用户点击后从外部打开。没有规范媒体事实佐证的普通文本裸路径或行内路径不会被当作附件。
ACP Chat 也可在 runtime 以可信结构化媒体投递图像生成结果时显示生成图片预览。对于可信的 OpenClaw internal-UI 投递和与生图任务关联的最终回复,ClawX 会保留原始的用户可见完成文案,包括只有文本的失败说明,而不会统一替换成通用图片文案。历史 OpenClaw 回放中,assistant 的图片 `MEDIA:` 标记只有在同一会话已记录图像生成任务启动后才会进入内联图片体验。ClawX 通过 Electron Main 的主机媒体处理加载预览,而不是让 Renderer 任意访问文件系统。标准 ACP 图片和 resource 内容仍是首选路径,并会直接渲染。
### ACP 文件活动语义
- 文件活动由成功且已完成的 OpenClaw `write``edit``apply_patch` 调用投影而来。工具识别方式与 OpenClaw 官方 Chat UI 保持一致;仅接收已完成调用的筛选规则是 ClawX 特有的。
- 已创建和已修改的活动行与可预览的 assistant 附件共用同一种文件卡片外壳和**打开方式**菜单,同时保留状态文字及可用的 `+/-` 统计。对于 HTML 文件,菜单第一项会在右侧**预览**中打开文件;已删除的活动行只保留 **Changes** 操作。应用列表、指定应用打开和显示文件位置都会由 Electron Main 根据 workspace 根目录与相对路径分别重新验证;工具路径不会因此变成附件,Renderer 也不会获得规范化系统路径。
- `write` 按工具声明的语义显示:视为创建,并展示为全部新增的差异,即使该路径可能已经存在。
- **Changes** 是按时间顺序记录工具声明活动的会话级记录,不是 Git 输出,也不是相对于已验证源码基线的差异。
- 对每个文件,Changes 在每轮助手回复中最多展示一个 diff 编辑器。可安全串联的片段会合并,独立片段会拼接到同一个编辑器中,但不会被描述为基于完整文件基线的差异。
- Shell 命令、脚本、用户或 IDE 产生的副作用不会被检测。
- 完整的 ACP 回放可以恢复已记录的文件活动;如果回放不完整,ClawX 不会通过回退推断来补造缺失活动。
```
┌───────────────────────────────────────────────────────────────────┐
│ ClawX 桌面应用 │
│ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ Electron 主进程 │ │
│ │ • 窗口与应用生命周期管理 │ │
│ │ • 网关进程监控 │ │
│ │ • 系统集成(托盘、通知、密钥链) │ │
│ │ • 自动更新编排 │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │ │
│ │ IPC (权威控制面) │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ React 渲染进程 │ │
│ │ • 现代组件化 UI(React 19 │ │
│ │ • Zustand 状态管理 │ │
│ │ • 统一 host-api/api-client 调用 │ │
│ │ • 回复使用 Markdown,用户输入按原文显示 │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬───────────────────────────────────┘
│ 类型化 IPC 请求
┌─────────────────────────────────────────────────────────────────┐
│ 主进程 Host Services 与 Gateway Manager │
│ │
│ • host:invoke 类型化服务分发 │
│ • 设置、文件、会话、技能、供应商、诊断服务 │
│ • 主进程持有 Gateway WebSocket 并负责进程监控 │
└──────────────────────────────┬──────────────────────────────────┘
│ 主进程持有 WebSocket
┌─────────────────────────────────────────────────────────────────┐
│ OpenClaw 网关 │
│ │
│ • AI 智能体运行时与编排 │
│ • 消息频道管理 │
│ • 技能/插件执行环境 │
│ • 供应商抽象层 │
└─────────────────────────────────────────────────────────────────┘
```
### 设计原则
- **进程隔离**:AI 运行时在独立进程中运行,确保即使在高负载计算期间 UI 也能保持响应
- **前端调用单一入口**:渲染层统一走 host-api/api-client,不感知底层协议细节
- **主进程掌控传输策略**ACP Chat stdio bridge 与 Gateway 传输都由 Electron Main 持有,渲染进程通过类型化 IPC 调用 Main
- **扩展 IPC 贡献点**:主进程扩展通过类型化 IPC 注册表贡献 host-api action,而不是挂载 HTTP route
- **优雅恢复**:内置重连、超时、退避逻辑,自动处理瞬时故障
- **安全存储**:API 密钥和敏感数据利用操作系统原生的安全存储机制
- **CORS 安全**:渲染进程不直接请求本地 Gateway 或 Host API HTTP 端点
### 进程模型与 Gateway 排障
- ClawX 基于 Electron,**单个应用实例出现多个系统进程是正常现象**main/renderer/zygote/utility)。
- 单实例保护同时使用 Electron 自带锁与本地进程文件锁回退机制,可在桌面会话总线异常时避免重复启动。
- 滚动升级期间若新旧版本混跑,单实例保护仍可能出现不对称行为。为保证稳定性,建议桌面客户端尽量统一升级到同一版本。
- 但 OpenClaw Gateway 监听应始终保持**单实例**:`127.0.0.1:18789` 只能有一个监听者。
- Gateway readiness 以 OpenClaw 的 `system-presence``health``status` 等核心信号为准;memory 或频道失败会显示为能力降级,而不是全局 Gateway 故障。
- 可用以下命令确认监听进程:
- macOS/Linux`lsof -nP -iTCP:18789 -sTCP:LISTEN`
- WindowsPowerShell):`Get-NetTCPConnection -LocalPort 18789 -State Listen`
- 点击窗口关闭按钮(`X`)默认只是最小化到托盘,并不会完全退出应用。请在托盘菜单中选择 **Quit ClawX** 执行完整退出。
+107
View File
@@ -0,0 +1,107 @@
# ClawX 开发文档
本文档是 README「开发指南」一节的详细说明。
### 前置要求
- **Node.js**:对应主版本范围内的 22.22.3+、24.15.0+ 或 25.9.0+(推荐 Node 24 LTS
- **包管理器**pnpm 9+(推荐)或 npm
- **LinuxUbuntu/Debian**:运行 Electron 前,请先安装所需系统库:
```bash
sudo apt-get install -y libnss3 libgtk-3-0 libxss1 libxtst6 libatspi2.0-0 libnotify4 xdg-utils
```
在 Ubuntu 24.04+ 上,部分软件包使用 `t64` 后缀,运行上述命令后 `apt` 会自动选择正确版本。
### 项目结构
```ClawX/
├── electron/ # Electron 主进程
│ ├── services/ # 类型化 Host API、Provider、Secrets 与运行时服务
│ │ ├── providers/ # Provider/account 模型同步逻辑
│ │ └── secrets/ # 系统钥匙串与密钥存储
│ ├── shared/ # 共享 Provider schema/常量
│ │ └── providers/
│ ├── main/ # 应用入口、窗口、IPC 注册
│ ├── gateway/ # OpenClaw 网关进程管理
│ ├── preload/ # 安全 IPC 桥接
│ └── utils/ # 工具模块(存储、认证、路径)
├── src/ # React 渲染进程
│ ├── lib/ # 前端统一 API 与错误模型
│ ├── stores/ # Zustand 状态仓库(settings/chat/gateway
│ ├── components/ # 可复用 UI 组件
│ ├── pages/ # Setup/Dashboard/Chat/Channels/Skills/Cron/Settings
│ ├── i18n/ # 国际化资源
│ └── types/ # TypeScript 类型定义
├── tests/
│ ├── e2e/ # Playwright Electron 端到端冒烟测试
│ └── unit/ # Vitest 单元/集成型测试
├── resources/ # 静态资源(图标、图片)
└── scripts/ # 构建与工具脚本
```
### 常用命令
```bash
# 开发
pnpm run init # 安装依赖并下载捆绑二进制(uv、agent-browser
pnpm dev # 以热重载模式启动(若缺失会自动准备预装技能包)
# 代码质量
pnpm lint # 运行 ESLint 检查
pnpm typecheck # TypeScript 类型检查
# 测试
pnpm test # 运行单元测试
pnpm run test:e2e # 运行 Electron E2E 冒烟测试
pnpm run test:e2e:headed # 以可见窗口运行 Electron E2E 测试
pnpm run perf:chat # 采集合成 Chat 场景的 Renderer/Main CPU Profile
pnpm run profile:main # 启动构建产物并在 9229 端口调试 Main
pnpm run comms:replay # 计算通信回放指标
pnpm run comms:baseline # 刷新通信基线快照
pnpm run comms:compare # 将回放指标与基线阈值对比
# 构建与打包
pnpm run build:vite # 仅构建前端
pnpm build # 完整生产构建(含打包资源)
pnpm package # 为当前平台打包(包含预装技能资源)
pnpm package:mac # 为 macOS 打包
pnpm package:win # 为 Windows 打包
pnpm package:linux # 为 Linux 打包
```
在无头 Linux 环境下,Electron 测试需要显示服务;可使用 `xvfb-run -a pnpm run test:e2e`。
Electron E2E 功能测试在本地和 CI 中默认使用两个 Playwright worker;可通过 `CLAWX_E2E_WORKERS=<正整数>` 按机器能力调整普通并行通道。访问操作系统全局状态的测试进入单 worker 的 `exclusive` project,主机性能采样则在功能测试结束后独占运行。新增 E2E 测试默认并行;若测试使用真实剪贴板或其他机器级共享资源,请应用 `tests/e2e/parallel-policy.ts` 中的 `E2E_EXCLUSIVE_TAG`。
如果只需运行一个不依赖独占前置阶段的普通 spec,可使用 `pnpm exec playwright test <spec> --project=parallel --no-deps`。
### Electron 性能诊断
`pnpm run perf:chat` 会运行隔离的合成 ACP 负载,分别覆盖流式响应,以及富 Markdown 静态会话中的侧栏和滚动交互,并在 Playwright 的 `test-results/` 目录输出版本化指标与 Renderer/Main CPU Profile。Renderer Profile 覆盖生产 store/render 路径和帧节奏;流式 Main Profile 测量 Main 到 Renderer 的 IPC fanout,交互 Main Profile 用于确认 Renderer 交互期间 Main 是否保持空闲。两者都不包含上游 OpenClaw/ACP 子进程或 GPU 进程路径。CPU Profile 可直接用 Chrome DevTools 打开;其中只包含生成的测试文本,不会上报为产品遥测。性能数据依赖硬件,应在同一机器上多次运行后对比,不应使用统一的跨平台绝对阈值。
录制真实 Renderer 时,使用 `CLAWX_REMOTE_DEBUGGING_PORT=9223 pnpm dev` 启动开发环境,再让 Playwright 或 Chrome DevTools 连接 `localhost:9223`。录制真实 Electron Main 时,运行 `pnpm run profile:main`,在 `chrome://inspect` 中配置 `localhost:9229` 并选择 Electron Main target。除非正在测量 WebSocket trace 本身,否则不要设置 `CLAWX_GATEWAY_WS_TRACE`。
ClawX 默认保留 Chromium 硬件加速,使长文档、滚动和布局动画能够使用 GPU 合成与光栅化。若某台机器的显卡驱动存在问题,仍可使用 Chromium 原生的 `--disable-gpu` 命令行参数作为排障回退。
### 通信回归检查
当 PR 涉及通信链路(Gateway 事件、ACP Chat bridge 收发流程、Channel 投递、传输回退)时,建议执行:
```bash
pnpm run comms:replay
pnpm run comms:compare
```
CI 中的 `comms-regression` 会校验必选场景与阈值。
### 技术栈
| 层级 | 技术 |
|------|------|
| 运行时 | Electron 40+ |
| UI 框架 | React 19 + TypeScript |
| 样式 | Tailwind CSS + shadcn/ui |
| 状态管理 | Zustand |
| 构建工具 | Vite + electron-builder |
| 测试 | Vitest + Playwright |
| 动画 | Framer Motion |
| 图标 | Lucide React |
+54
View File
@@ -0,0 +1,54 @@
# ClawX 功能特性
本文档是 README「功能特性」一节的详细说明。
### 🎯 零配置门槛
从安装到第一次 AI 对话,全程通过直观的图形界面完成。无需终端命令,无需 YAML 文件,无需到处寻找环境变量。
### 💬 智能聊天界面
通过现代化的聊天体验与 AI 智能体交互。支持多会话上下文、消息历史记录,并以流式 Markdown 渲染智能体回复,支持带语法高亮的围栏代码块、面向中日韩文本的解析、GitHub 风格表格,以及由 KaTeX 渲染的 LaTeX 数学公式(`$行内$``$$块级$$``\(行内\)``\[块级\]`);用户输入则始终按原始文本显示。同时支持在多 Agent 场景下通过主输入框中的 `@agent` 直接路由到目标智能体。围栏代码会保留源码换行、自动软换行,并在流式输出结束后提供本地化的复制操作。
从输入框插入的技能会以 `/技能名` 卡片形式显示;点击卡片可在右侧预览栏打开并阅读该技能的 `SKILL.md`
当你使用 `@agent` 选择其他智能体时,ClawX 会直接切换到该智能体自己的对话上下文,而不是经过默认智能体转发。各 Agent 工作区默认彼此分离,但更强的运行时隔离仍取决于 OpenClaw 的 sandbox 配置。
会话侧边栏现在以工作空间优先组织:默认工作空间固定在最上方,其它工作空间按自然顺序排列,每个工作空间都可折叠或继续加载更多会话。AI 回复期间,会话行显示加载指示器;未查看的回复完成后显示蓝点;打开会话后恢复显示相对活跃时间,悬停时仍会露出操作按钮。导入的工作空间可从侧边栏标题处重命名,新名称会同步显示在对话输入框下方,同时悬浮标题仍可查看文件系统路径。如果当前所选会话存在有效工作空间,新对话会继承该工作空间,并在首次发送前保持可编辑。对于可编辑的新对话或未绑定对话,输入框的工作空间卡片会打开一个小菜单,列出最近使用及现有会话中的工作空间,并可切回默认工作空间或选择其它目录。如果保存的工作空间文件夹已被移动或删除,Chat 会暂停创建会话并提示选择现有文件夹,而不会持续重试失效路径。不可用的非默认工作空间会在侧边栏显示标记,并可在确认后删除;该操作会永久删除分组中的全部会话。只有永久删除成功后,会话行才会移除且页面才会跳转;删除失败时会保留会话与确认框,方便重试。OpenClaw 生成的 UUID 加日期兜底标题只有在与该会话 ID 匹配时才会被视为缺失标题,随后改用会话的首条用户消息展示,而不会被持久化为会话名称。
每个 Agent 还可以单独覆盖自己的 `provider/model` 运行时设置;未覆盖的 Agent 会继续继承全局默认模型。
Chat 右侧面板的工作空间和预览选项卡支持以只读方式预览 Markdown、`.docx``.pptx` 文件。Markdown 文件预览以静态渲染模式提供相同的围栏代码语法高亮、软换行与复制操作、面向中日韩文本的解析和 KaTeX 数学公式支持。预览栏顶部可将当前文件展开至 ClawX 的整个可视区域;再次点击该按钮或按 Esc 即可返回侧栏。旧版 `.doc``.ppt` 文件不会在应用内预览,而是继续通过操作系统打开。DOCX 的分页效果可能与 Microsoft Word 不同;PPTX 预览不支持动画、切换效果或媒体播放。超过 20 MB 的 Office 文件不会在应用内预览。
### 本地 HTML 预览
Chat 右侧面板只包含工作空间、预览和变更,不再提供通用网页浏览器、主页或地址栏。已授权的本地 `.html``.htm` 附件、文件活动及工作空间文件默认在预览中打开。文件操作可以选择 ClawX 内置预览或系统应用,预览标题栏也可将当前 HTML 文件交给系统浏览器打开。
所有链接都不可点击。ClawX 渲染的链接显示为普通文本,HTML 预览中的链接也会移除链接样式和指针交互。HTML 预览同时阻止表单、脚本跳转、重定向、页内跳转、弹窗、下载、网络请求和设备权限;它可以显示自包含的本地 HTML,但无法离开当前选中的文档。
### 📡 多频道管理
同时配置和监控多个 AI 频道。每个频道独立运行,允许你为不同任务运行专门的智能体。
现在每个频道支持多个账号,并可在 Channels 页面直接完成账号绑定到 Agent 与默认账号切换。
对于自定义频道账号 ID,ClawX 现在会强制校验 OpenClaw 兼容的规范格式(`[a-z0-9_-]`、小写、最长 64 位、且必须以字母或数字开头),避免路由匹配异常。
ClawX 现在还内置了腾讯官方个人微信渠道插件,可直接在 Channels 页面通过内置二维码流程完成微信连接。
### ⏰ 定时任务自动化
调度 AI 任务自动执行。定义触发器、设置时间间隔,让 AI 智能体 7×24 小时不间断工作。
现在定时任务页面已经可以直接配置外部投递,统一拆成“发送账号”和“接收目标”两个下拉选择。对于已支持的通道,接收目标会从通道目录能力或已知会话历史中自动发现,不需要再手动修改 `jobs.json`。任务的消息输入框也支持像主对话框那样以内联 `/skill` 令牌的方式插入技能(按所选智能体范围加载),让定时提示词可以直接触发技能。调度选择器现在分为**周期**和**单次**两个选项卡:周期支持每小时、每天、工作日、每周、自定义(原始 cron)等频率,并内置时间/星期选择;单次则在所选日期(显示星期)和时间执行一次。单次任务必须设置为未来时间,并会在执行完成后由运行时自动清除。
### 🧩 可扩展技能系统
通过预构建的技能扩展 AI 智能体的能力。集成的 Skills 页面采用“本地优先”方式:会扫描托管目录与 workspace 技能目录,并且无需依赖 Gateway 即可启用或停用技能;在企业扩展接管时,也可以显示扩展提供的 marketplace。
ClawX 还会内置预装完整的文档处理技能(`pdf``xlsx``docx``pptx`),在启动时自动部署到托管技能目录(默认 `~/.openclaw/skills`),并在首次安装时默认启用。
Skills 页面可展示来自多个 OpenClaw 来源的技能(托管目录、workspace、额外技能目录),并显示每个技能的实际路径,便于直接打开真实安装位置。对于 OpenClaw 自带的 bundled skills,社区版现在在打包产物里只保留并展示 `skill-creator`;开发模式和打包版启动时都会直接清理其它 bundled skill,同时把这些已删除 bundled skill 在 `openclaw.json` 中残留的旧配置一并移除。
### 🔐 安全的供应商集成
连接多个 AI 供应商(OpenAI、Anthropic、Z.AI / GLM 等),凭证安全存储在系统原生密钥链中。OpenAI 同时支持 API Key 与浏览器 OAuthCodex 订阅)登录。
在开发者模式下,独立的“图像生成”页面支持配置 OpenAI 兼容生图端点(Base URL、API Key 和模型名,例如 `gpt-image-2`),生图请求会走专用的 `/v1/images/generations` 服务,聊天仍继续使用正常的 OpenAI Provider。
如果你通过 **自定义(CustomProvider** 对接 OpenAI-compatible 网关,可以在 **设置 → AI Providers → 编辑 Provider** 中配置自定义 `User-Agent`,以提高兼容性。
编辑或切换 Provider 时,ClawX 会保留已有的模型级能力元数据,例如 `input: ["text", "image"]`。新选择的自定义 Provider 模型会使用与 OpenClaw onboarding 一致的图片输入能力推断;未知模型默认按纯文本模型处理。
自定义 Provider 的模型行还会写入显式的 `contextWindow`(按模型系列推断,例如 `gpt-5.x` → 272k),旧版本保存的模型行会在启动时自动回填,使 OpenClaw 能在长会话超限前主动压缩上下文,避免出现 "Context overflow" 报错。当你没有配置 compaction 时,ClawX 会默认写入 `agents.defaults.compaction.mode = "safeguard"``reserveTokensFloor = 50000`;你手动配置过的模型行或压缩配置永远不会被修改(仅可能回填缺失的 `reserveTokensFloor`)。
Z.AI(国内站 / 国际站)会映射到 OpenClaw 内置的 `zai` 供应商(`ZAI_API_KEY`),默认模型为 `glm-5.2`。可通过 Code Plan 预设切换到编码套餐端点(`…/api/coding/paas/v4`),或使用普通 API 端点(`…/api/paas/v4`);国内站与国际站互斥,因为它们共享同一个 OpenClaw 运行时 key。
如果兼容网关的 `/models` 因非鉴权原因不可用,ClawX 会在校验 API Key 时使用已配置的模型,自动降级为轻量的 `/chat/completions``/responses` 探测。
### 🌙 自适应主题
支持浅色模式、深色模式或跟随系统主题。ClawX 自动适应你的偏好设置。
### 🚀 开机启动控制
**设置 → 通用** 中,你可以开启 **开机自动启动**,让 ClawX 在系统登录后自动启动。
### 🔔 更新提示
ClawX 可以在启动时自动检查新版本。发现更新后会显示应用内提示;只有在你选择操作后,才会下载或安装更新。
+12
View File
@@ -0,0 +1,12 @@
# ClawX 代理设置
本文档是 README「代理设置」一节的详细说明。
- 只填写 `host:port` 时,会按 HTTP 代理处理。
- 高级代理项留空时,会自动回退到“代理服务器”。
- 保存代理设置后,Electron 网络层会立即重新应用代理,并自动重启 Gateway。
- 如果启用了 TelegramClawX 还会把代理同步到 OpenClaw 的 Telegram 频道配置中。
- 当 ClawX 代理处于关闭状态时,Gateway 的常规重启会保留已有的 Telegram 频道代理配置。
- 如果你要明确清空 OpenClaw 中的 Telegram 代理,请在关闭代理后点一次“保存代理设置”。
-**设置 → 高级 → 开发者** 中,可以直接运行 **OpenClaw Doctor**,执行 `openclaw doctor --json` 并在应用内查看诊断输出。
- 在 Windows 打包版本中,内置的 `openclaw` CLI/TUI 会通过随包分发的 `node.exe` 入口运行,以保证终端输入行为稳定。
+11 -2
View File
@@ -1,4 +1,5 @@
import { createDiagnosticsApi } from '../../services/diagnostics-api';
import type { HostApiContribution, RuntimeHostAction } from '../../main/ipc/host-contract';
import type {
Extension,
ExtensionContext,
@@ -12,10 +13,18 @@ class DiagnosticsExtension implements HostApiProviderExtension {
// Diagnostics are exposed through host IPC contributions.
}
getHostApiContributions(ctx: ExtensionContext) {
getHostApiContributions(ctx: ExtensionContext): HostApiContribution[] {
const diagnostics = createDiagnosticsApi({ gatewayManager: ctx.gatewayManager });
const actions: Record<string, RuntimeHostAction> = {
gatewaySnapshot: () => diagnostics.gatewaySnapshot(),
acpTrace: () => diagnostics.acpTrace(),
recordAcpTrace: (payload) => diagnostics.recordAcpTrace(
payload as Parameters<typeof diagnostics.recordAcpTrace>[0],
),
};
return [{
module: 'diagnostics',
actions: createDiagnosticsApi({ gatewayManager: ctx.gatewayManager }),
actions,
}];
}
}
-333
View File
@@ -1,333 +0,0 @@
/**
* Gateway WebSocket Client
* Provides a typed interface for Gateway RPC calls
*/
import { GatewayManager, GatewayStatus } from './manager';
/**
* Channel types supported by OpenClaw
*/
export type ChannelType = 'whatsapp' | 'dingtalk' | 'telegram' | 'discord' | 'wechat';
/**
* Channel status
*/
export interface Channel {
id: string;
type: ChannelType;
name: string;
status: 'connected' | 'disconnected' | 'connecting' | 'error';
lastActivity?: string;
error?: string;
config?: Record<string, unknown>;
}
/**
* Skill definition
*/
export interface Skill {
id: string;
name: string;
description: string;
enabled: boolean;
category?: string;
icon?: string;
configurable?: boolean;
version?: string;
author?: string;
}
/**
* Skill bundle definition
*/
export interface SkillBundle {
id: string;
name: string;
description: string;
skills: string[];
icon?: string;
recommended?: boolean;
}
/**
* Chat message
*/
export interface ChatMessage {
id: string;
role: 'user' | 'assistant' | 'system';
content: string;
timestamp: string;
channel?: string;
toolCalls?: ToolCall[];
metadata?: Record<string, unknown>;
}
/**
* Tool call in a message
*/
export interface ToolCall {
id: string;
name: string;
arguments: Record<string, unknown>;
result?: unknown;
status: 'pending' | 'running' | 'completed' | 'error';
duration?: number;
}
/**
* Cron task definition
*/
export interface CronTask {
id: string;
name: string;
schedule: string;
command: string;
enabled: boolean;
lastRun?: string;
nextRun?: string;
status: 'idle' | 'running' | 'error';
error?: string;
}
/**
* Provider configuration
*/
export interface ProviderConfig {
id: string;
name: string;
type: 'openai' | 'anthropic' | 'ollama' | 'custom';
apiKey?: string;
baseUrl?: string;
model?: string;
enabled: boolean;
}
/**
* Gateway Client
* Typed wrapper around GatewayManager for making RPC calls
*/
export class GatewayClient {
constructor(private manager: GatewayManager) { }
/**
* Get current gateway status
*/
getStatus(): GatewayStatus {
return this.manager.getStatus();
}
/**
* Check if gateway is connected
*/
isConnected(): boolean {
return this.manager.isConnected();
}
// ==================== Channel Methods ====================
/**
* List all channels
*/
async listChannels(): Promise<Channel[]> {
return this.manager.rpc<Channel[]>('channels.list');
}
/**
* Get channel by ID
*/
async getChannel(channelId: string): Promise<Channel> {
return this.manager.rpc<Channel>('channels.get', { channelId });
}
/**
* Connect a channel
*/
async connectChannel(channelId: string): Promise<void> {
return this.manager.rpc<void>('channels.connect', { channelId });
}
/**
* Disconnect a channel
*/
async disconnectChannel(channelId: string): Promise<void> {
return this.manager.rpc<void>('channels.disconnect', { channelId });
}
/**
* Get QR code for channel connection (e.g., WhatsApp)
*/
async getChannelQRCode(channelType: ChannelType): Promise<string> {
return this.manager.rpc<string>('channels.getQRCode', { channelType });
}
// ==================== Skill Methods ====================
/**
* List all skills
*/
async listSkills(): Promise<Skill[]> {
return this.manager.rpc<Skill[]>('skills.list');
}
/**
* Enable a skill
*/
async enableSkill(skillId: string): Promise<void> {
return this.manager.rpc<void>('skills.enable', { skillId });
}
/**
* Disable a skill
*/
async disableSkill(skillId: string): Promise<void> {
return this.manager.rpc<void>('skills.disable', { skillId });
}
/**
* Get skill configuration
*/
async getSkillConfig(skillId: string): Promise<Record<string, unknown>> {
return this.manager.rpc<Record<string, unknown>>('skills.getConfig', { skillId });
}
/**
* Update skill configuration
*/
async updateSkillConfig(skillId: string, config: Record<string, unknown>): Promise<void> {
return this.manager.rpc<void>('skills.updateConfig', { skillId, config });
}
// ==================== Chat Methods ====================
/**
* Send a chat message
*/
async sendMessage(content: string, channelId?: string): Promise<ChatMessage> {
return this.manager.rpc<ChatMessage>('chat.send', { content, channelId });
}
/**
* Get chat history
*/
async getChatHistory(limit = 50, offset = 0): Promise<ChatMessage[]> {
return this.manager.rpc<ChatMessage[]>('chat.history', { limit, offset });
}
/**
* Clear chat history
*/
async clearChatHistory(): Promise<void> {
return this.manager.rpc<void>('chat.clear');
}
// ==================== Cron Methods ====================
/**
* List all cron tasks
*/
async listCronTasks(): Promise<CronTask[]> {
return this.manager.rpc<CronTask[]>('cron.list');
}
/**
* Create a new cron task
*/
async createCronTask(task: Omit<CronTask, 'id' | 'status'>): Promise<CronTask> {
return this.manager.rpc<CronTask>('cron.create', task);
}
/**
* Update a cron task
*/
async updateCronTask(taskId: string, updates: Partial<CronTask>): Promise<CronTask> {
return this.manager.rpc<CronTask>('cron.update', { taskId, ...updates });
}
/**
* Delete a cron task
*/
async deleteCronTask(taskId: string): Promise<void> {
return this.manager.rpc<void>('cron.delete', { taskId });
}
/**
* Run a cron task immediately
*/
async runCronTask(taskId: string): Promise<void> {
return this.manager.rpc<void>('cron.run', { taskId });
}
// ==================== Provider Methods ====================
/**
* List configured AI providers
*/
async listProviders(): Promise<ProviderConfig[]> {
return this.manager.rpc<ProviderConfig[]>('providers.list');
}
/**
* Add or update a provider
*/
async setProvider(provider: ProviderConfig): Promise<void> {
return this.manager.rpc<void>('providers.set', provider);
}
/**
* Remove a provider
*/
async removeProvider(providerId: string): Promise<void> {
return this.manager.rpc<void>('providers.remove', { providerId });
}
/**
* Test provider connection
*/
async testProvider(providerId: string): Promise<{ success: boolean; error?: string }> {
return this.manager.rpc<{ success: boolean; error?: string }>('providers.test', { providerId });
}
// ==================== System Methods ====================
/**
* Get Gateway health status
*/
async getHealth(): Promise<{ status: string; uptime: number; version?: string }> {
return this.manager.rpc<{ status: string; uptime: number; version?: string }>('system.health');
}
/**
* Get Gateway configuration
*/
async getConfig(): Promise<Record<string, unknown>> {
return this.manager.rpc<Record<string, unknown>>('system.config');
}
/**
* Update Gateway configuration
*/
async updateConfig(config: Record<string, unknown>): Promise<void> {
return this.manager.rpc<void>('system.updateConfig', config);
}
/**
* Get Gateway version info
*/
async getVersion(): Promise<{ version: string; nodeVersion?: string; platform?: string }> {
return this.manager.rpc<{ version: string; nodeVersion?: string; platform?: string }>('system.version');
}
/**
* Get available skill bundles
*/
async getSkillBundles(): Promise<SkillBundle[]> {
return this.manager.rpc<SkillBundle[]>('skills.bundles');
}
/**
* Install a skill bundle
*/
async installBundle(bundleId: string): Promise<void> {
return this.manager.rpc<void>('skills.installBundle', { bundleId });
}
}
+311
View File
@@ -0,0 +1,311 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import { randomUUID } from 'node:crypto';
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import { isDeepStrictEqual } from 'node:util';
import JSON5 from 'json5';
import type { GatewayManager } from './manager';
import { withConfigLock } from '../utils/config-mutex';
import { resolveOpenClawConfigPath } from '../utils/paths';
export type OpenClawConfig = Record<string, unknown>;
/** Mutators may be replayed after a compare-and-swap conflict and must not perform external writes. */
export type OpenClawConfigMutator = (
config: OpenClawConfig,
) => void | Promise<void>;
type ConfigDeliveryGatewayManager = Pick<GatewayManager, 'getStatus' | 'rpc'>;
interface ConfigSnapshot {
config?: unknown;
raw?: unknown;
hash?: unknown;
}
interface ActiveMutationContext {
config: OpenClawConfig;
active: boolean;
sourceExists: boolean;
}
export interface OpenClawConfigSnapshot {
config: OpenClawConfig;
exists: boolean;
}
interface FileConfigSnapshot {
config: OpenClawConfig;
raw: string | undefined;
}
let gatewayManager: ConfigDeliveryGatewayManager | undefined;
let transactionTail: Promise<void> = Promise.resolve();
const activeMutation = new AsyncLocalStorage<ActiveMutationContext>();
function parseConfig(raw: string): OpenClawConfig {
const parsed = JSON5.parse(raw) as unknown;
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('OpenClaw config must be an object');
}
return parsed as OpenClawConfig;
}
function serializeConfig(config: OpenClawConfig): string {
return `${JSON.stringify(config, null, 2)}\n`;
}
function parseRunningConfigSnapshot(snapshot: ConfigSnapshot | undefined): OpenClawConfig {
if (snapshot?.config && typeof snapshot.config === 'object' && !Array.isArray(snapshot.config)) {
return structuredClone(snapshot.config) as OpenClawConfig;
}
const raw = typeof snapshot?.raw === 'string' ? snapshot.raw : '';
if (!raw.trim()) {
throw new Error('Gateway config.get returned an incomplete config snapshot');
}
return parseConfig(raw);
}
function isBaseHashConflict(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
return /config changed since last load; re-run config\.get and retry/i.test(message);
}
function isConfigSetResponseLost(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
return message.includes('RPC timeout: config.set')
|| message.includes('Gateway stopped')
|| message.includes('Gateway not connected')
|| message.includes('Gateway service restart')
|| message.includes('Failed to send RPC request:');
}
async function acceptPersistedConfigSetCommitIfMatched(config: OpenClawConfig): Promise<boolean> {
const persisted = await readFileConfig(resolveOpenClawConfigPath());
return isDeepStrictEqual(persisted.config, config);
}
async function mutateRunningConfig(
manager: ConfigDeliveryGatewayManager,
mutator: OpenClawConfigMutator,
): Promise<boolean> {
for (let attempt = 0; attempt < 2; attempt += 1) {
const snapshot = await manager.rpc<ConfigSnapshot>('config.get', {});
const hash = typeof snapshot?.hash === 'string' ? snapshot.hash.trim() : '';
if (!hash) {
throw new Error('Gateway config.get returned an incomplete config snapshot');
}
const config = parseRunningConfigSnapshot(snapshot);
if (!await applyMutator(config, mutator, true)) return false;
try {
await manager.rpc('config.set', {
raw: serializeConfig(config),
baseHash: hash,
});
return true;
} catch (error) {
if (attempt === 0 && isBaseHashConflict(error)) continue;
// config.set may durably replace the file and then close the socket with
// code 1012 before its RPC response reaches ClawX. Reconnect can restore
// running state before the RPC timeout fires, so verify the persisted
// snapshot whenever the response was lost instead of only while stopped.
if (manager.getStatus().state !== 'running' || isConfigSetResponseLost(error)) {
if (await acceptPersistedConfigSetCommitIfMatched(config)) return true;
}
throw error;
}
}
return false;
}
async function applyMutator(
config: OpenClawConfig,
mutator: OpenClawConfigMutator,
sourceExists: boolean,
): Promise<boolean> {
const baseline = structuredClone(config);
const context: ActiveMutationContext = { config, active: true, sourceExists };
try {
await activeMutation.run(context, async () => await mutator(config));
} finally {
context.active = false;
}
return !isDeepStrictEqual(config, baseline);
}
async function applyNestedMutator(
context: ActiveMutationContext,
mutator: OpenClawConfigMutator,
): Promise<boolean> {
const baseline = structuredClone(context.config);
await mutator(context.config);
return !isDeepStrictEqual(context.config, baseline);
}
async function readFileConfig(configPath: string): Promise<FileConfigSnapshot> {
try {
const raw = await readFile(configPath, 'utf8');
return { config: parseConfig(raw), raw };
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return { config: {}, raw: undefined };
}
throw error;
}
}
async function readFileRaw(configPath: string): Promise<string | undefined> {
try {
return await readFile(configPath, 'utf8');
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
throw error;
}
}
async function removeTemporaryFile(temporaryPath: string): Promise<void> {
try {
await unlink(temporaryPath);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
}
async function mutateFileConfig(
manager: ConfigDeliveryGatewayManager | undefined,
mutator: OpenClawConfigMutator,
): Promise<boolean> {
return await withConfigLock(async () => {
const configPath = resolveOpenClawConfigPath();
for (let attempt = 0; attempt < 2; attempt += 1) {
const snapshot = await readFileConfig(configPath);
const changed = await applyMutator(snapshot.config, mutator, snapshot.raw !== undefined);
if (manager?.getStatus().state === 'running') {
return await mutateRunningConfig(manager, mutator);
}
if (!changed) return false;
await mkdir(dirname(configPath), { recursive: true });
const temporaryPath = `${configPath}.${process.pid}.${randomUUID()}.tmp`;
await writeFile(temporaryPath, serializeConfig(snapshot.config), {
encoding: 'utf8',
flag: 'wx',
mode: 0o600,
});
try {
if (manager?.getStatus().state === 'running') {
return await mutateRunningConfig(manager, mutator);
}
const currentRaw = await readFileRaw(configPath);
if (manager?.getStatus().state === 'running') {
return await mutateRunningConfig(manager, mutator);
}
if (currentRaw !== snapshot.raw) {
if (attempt === 0) continue;
throw new Error('OpenClaw config changed during file mutation; retry the mutation');
}
await rename(temporaryPath, configPath);
return true;
} finally {
await removeTemporaryFile(temporaryPath);
}
}
return false;
});
}
async function runMutation(mutator: OpenClawConfigMutator): Promise<boolean> {
const manager = gatewayManager;
if (manager?.getStatus().state === 'running') {
return await mutateRunningConfig(manager, mutator);
}
return await mutateFileConfig(manager, mutator);
}
async function runRead(): Promise<OpenClawConfigSnapshot> {
const manager = gatewayManager;
if (manager?.getStatus().state === 'running') {
const snapshot = await manager.rpc<ConfigSnapshot>('config.get', {});
return { config: parseRunningConfigSnapshot(snapshot), exists: true };
}
const snapshot = await readFileConfig(resolveOpenClawConfigPath());
return { config: snapshot.config, exists: snapshot.raw !== undefined };
}
async function runSecretsReload(): Promise<boolean> {
const manager = gatewayManager;
if (manager?.getStatus().state !== 'running') return false;
await manager.rpc('secrets.reload', {});
return true;
}
export function registerOpenClawConfigCoordinator(
manager: ConfigDeliveryGatewayManager,
): void {
gatewayManager = manager;
}
export function mutateOpenClawConfig(
mutator: OpenClawConfigMutator,
): Promise<boolean> {
const context = activeMutation.getStore();
if (context?.active) {
return applyNestedMutator(context, mutator);
}
const transaction = transactionTail.then(
() => runMutation(mutator),
() => runMutation(mutator),
);
transactionTail = transaction.then(
() => undefined,
() => undefined,
);
return transaction;
}
export function readOpenClawConfigSnapshot(): Promise<OpenClawConfigSnapshot> {
const context = activeMutation.getStore();
if (context?.active) {
return Promise.resolve({
config: structuredClone(context.config),
exists: context.sourceExists,
});
}
const transaction = transactionTail.then(
() => runRead(),
() => runRead(),
);
transactionTail = transaction.then(
() => undefined,
() => undefined,
);
return transaction;
}
export function reloadOpenClawSecretsIfRunning(): Promise<boolean> {
const transaction = transactionTail.then(
() => runSecretsReload(),
() => runSecretsReload(),
);
transactionTail = transaction.then(
() => undefined,
() => undefined,
);
return transaction;
}
export function resetOpenClawConfigCoordinatorForTests(): void {
gatewayManager = undefined;
transactionTail = Promise.resolve();
}
+112 -29
View File
@@ -1,6 +1,6 @@
import { app } from 'electron';
import path from 'path';
import { existsSync, readFileSync, mkdirSync, readdirSync, rmSync, symlinkSync } from 'fs';
import { existsSync, readFileSync, mkdirSync, readdirSync, symlinkSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
@@ -33,8 +33,13 @@ import { buildProxyEnv, resolveProxySettings } from '../utils/proxy';
import { syncProxyConfigToOpenClaw } from '../utils/openclaw-proxy';
import { logger } from '../utils/logger';
import { prependPathEntry } from '../utils/env-path';
import { copyPluginFromNodeModules, fixupPluginManifest, cpSyncSafe, buildCandidateSources } from '../utils/plugin-install';
import { copyPluginFromNodeModules, fixupPluginManifest, cpSyncSafe, buildCandidateSources, repairTrustedOfficialPluginInstallRecords, removeTrustedOfficialPluginInstallRecord, resolvePluginNpmPackagePath } from '../utils/plugin-install';
import { safeRmSync } from '../utils/safe-fs';
import { CLAWX_OPENAI_IMAGE_PROVIDER_KEY } from '../utils/openclaw-image-relay-constants';
import {
ensureOpenClaw2026_7_1UpgradeSnapshot,
quarantineLegacyUpdateCheckState,
} from '../utils/openclaw-upgrade-snapshot';
import { stripSystemdSupervisorEnv } from './config-sync-env';
import { cleanupAgentsSymlinkedSkills, cleanupStalePluginRuntimeDeps } from './skills-symlink-cleanup';
import {
@@ -81,20 +86,45 @@ const CHANNEL_PLUGIN_MAP: Record<string, { dirName: string; npmName: string }> =
};
/**
* OpenClaw 3.22+ ships Discord, Telegram, and other channels as built-in
* extensions. If a previous ClawX version copied one of these into
* ~/.openclaw/extensions/, the broken copy overrides the working built-in
* plugin and must be removed.
* OpenClaw ships some channel plugins as bundled extensions under
* dist/extensions/. If ClawX previously mirrored one of those ids into
* ~/.openclaw/extensions/, the stale copy overrides the bundled plugin.
* Only remove extension copies whose id is actually bundled in the
* currently resolved OpenClaw runtime (e.g. telegram in 2026.6.10).
*/
const BUILTIN_CHANNEL_EXTENSIONS = ['discord', 'telegram', 'qqbot'];
function listBundledOpenClawExtensionPluginIds(): string[] {
const extensionsDir = join(getOpenClawResolvedDir(), 'dist', 'extensions');
if (!existsSync(fsPath(extensionsDir))) {
return [];
}
const pluginIds: string[] = [];
for (const entry of readdirSync(fsPath(extensionsDir), { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const manifestPath = join(extensionsDir, entry.name, 'openclaw.plugin.json');
if (!existsSync(fsPath(manifestPath))) continue;
try {
const parsed = JSON.parse(readFileSync(fsPath(manifestPath), 'utf-8')) as { id?: unknown };
if (typeof parsed.id === 'string' && parsed.id.trim()) {
pluginIds.push(parsed.id.trim());
}
} catch {
// ignore malformed manifests
}
}
return pluginIds;
}
function cleanupStaleBuiltInExtensions(): void {
for (const ext of BUILTIN_CHANNEL_EXTENSIONS) {
for (const ext of listBundledOpenClawExtensionPluginIds()) {
const extDir = join(homedir(), '.openclaw', 'extensions', ext);
if (existsSync(fsPath(extDir))) {
logger.info(`[plugin] Removing stale built-in extension copy: ${ext}`);
try {
rmSync(fsPath(extDir), { recursive: true, force: true });
safeRmSync(fsPath(extDir));
} catch (err) {
logger.warn(`[plugin] Failed to remove stale extension ${ext}:`, err);
}
@@ -166,7 +196,7 @@ function ensureConfiguredPluginsUpgraded(configuredChannels: string[]): boolean
logger.info(`[plugin] ${isInstalled ? 'Auto-upgrading' : 'Installing'} ${channelType} plugin${isInstalled ? `: ${installedVersion}${sourceVersion}` : `: ${sourceVersion}`} (bundled)`);
try {
mkdirSync(fsPath(join(homedir(), '.openclaw', 'extensions')), { recursive: true });
rmSync(fsPath(targetDir), { recursive: true, force: true });
safeRmSync(fsPath(targetDir));
cpSyncSafe(bundledDir, targetDir);
fixupPluginManifest(targetDir);
} catch (err) {
@@ -183,25 +213,26 @@ function ensureConfiguredPluginsUpgraded(configuredChannels: string[]): boolean
// Dev mode fallback: copy from node_modules/ with pnpm dep resolution
if (!app.isPackaged) {
const npmPkgPath = join(process.cwd(), 'node_modules', ...npmName.split('/'));
if (!existsSync(fsPath(join(npmPkgPath, 'openclaw.plugin.json')))) continue;
const sourceVersion = readPluginVersion(join(npmPkgPath, 'package.json'));
if (!sourceVersion) continue;
// Skip only if installed AND same version — but still patch manifest ID.
if (isInstalled && installedVersion && sourceVersion === installedVersion) {
fixupPluginManifest(targetDir);
continue;
}
const npmPkgPath = resolvePluginNpmPackagePath(npmName);
if (npmPkgPath && existsSync(fsPath(join(npmPkgPath, 'openclaw.plugin.json')))) {
const sourceVersion = readPluginVersion(join(npmPkgPath, 'package.json'));
if (!sourceVersion) continue;
// Skip only if installed AND same version — but still patch manifest ID.
if (isInstalled && installedVersion && sourceVersion === installedVersion) {
fixupPluginManifest(targetDir);
continue;
}
logger.info(`[plugin] ${isInstalled ? 'Auto-upgrading' : 'Installing'} ${channelType} plugin${isInstalled ? `: ${installedVersion}${sourceVersion}` : `: ${sourceVersion}`} (dev/node_modules)`);
logger.info(`[plugin] ${isInstalled ? 'Auto-upgrading' : 'Installing'} ${channelType} plugin${isInstalled ? `: ${installedVersion}${sourceVersion}` : `: ${sourceVersion}`} (dev/node_modules)`);
try {
mkdirSync(fsPath(join(homedir(), '.openclaw', 'extensions')), { recursive: true });
copyPluginFromNodeModules(npmPkgPath, targetDir, npmName);
fixupPluginManifest(targetDir);
} catch (err) {
logger.warn(`[plugin] Failed to ${isInstalled ? 'auto-upgrade' : 'install'} ${channelType} plugin from node_modules:`, err);
succeeded = false;
try {
mkdirSync(fsPath(join(homedir(), '.openclaw', 'extensions')), { recursive: true });
copyPluginFromNodeModules(npmPkgPath, targetDir, npmName);
fixupPluginManifest(targetDir);
} catch (err) {
logger.warn(`[plugin] Failed to ${isInstalled ? 'auto-upgrade' : 'install'} ${channelType} plugin from node_modules:`, err);
succeeded = false;
}
}
}
}
@@ -227,7 +258,7 @@ function cleanupUnconfiguredChannelPlugins(configuredChannels: string[]): boolea
logger.info(`[plugin] Removing unconfigured channel plugin: ${channelType} (${dirName})`);
try {
rmSync(fsPath(targetDir), { recursive: true, force: true });
safeRmSync(fsPath(targetDir));
} catch (err) {
logger.warn(`[plugin] Failed to remove unconfigured channel plugin ${channelType}:`, err);
succeeded = false;
@@ -236,6 +267,18 @@ function cleanupUnconfiguredChannelPlugins(configuredChannels: string[]): boolea
return succeeded;
}
async function cleanupUnconfiguredChannelPluginInstallRecords(configuredChannels: string[]): Promise<void> {
const configuredSet = new Set(configuredChannels);
for (const [channelType, { dirName }] of Object.entries(CHANNEL_PLUGIN_MAP)) {
if (configuredSet.has(channelType)) continue;
// Metadata can outlive the directory (for example after an interrupted
// 2026.6.10 → 2026.7.1 migration). OpenClaw validates tracked records even
// when the channel is no longer configured, so reconcile this on every
// launch rather than hiding it behind the directory-maintenance cache.
await removeTrustedOfficialPluginInstallRecord(dirName);
}
}
function resolveImageGenerationPrimary(config: unknown): string | null {
if (!config || typeof config !== 'object') return null;
const agents = (config as { agents?: unknown }).agents;
@@ -493,6 +536,13 @@ export async function syncGatewayConfigBeforeLaunch(
},
));
maintenance['plugin-maintenance'] = result;
// Always refresh trusted install metadata through ClawX — this must not
// be skipped when plugin-maintenance is cache-hit, otherwise official
// external plugins like WhatsApp fail openKeyedStore at runtime.
await measureAsync(timingsMs, 'trustedPluginInstallSyncMs', async () => {
await cleanupUnconfiguredChannelPluginInstallRecords(configuredChannels);
await repairTrustedOfficialPluginInstallRecords();
});
} catch (err) {
logger.warn('Failed to auto-upgrade plugins:', err);
}
@@ -591,6 +641,32 @@ export async function prepareGatewayLaunchContext(port: number): Promise<Gateway
throw new Error(`OpenClaw package not found at: ${openclawDir}`);
}
await measureAsync(timingsMs, 'upgradeSnapshotMs', async () => {
try {
const snapshot = await ensureOpenClaw2026_7_1UpgradeSnapshot();
if (snapshot.status === 'created') {
logger.info(`[upgrade] Created OpenClaw 2026.7.1 pre-migration snapshot (${snapshot.files.length} files): ${snapshot.snapshotDir}`);
}
} catch (error) {
// OpenClaw also maintains migration-specific backups. Keep startup
// available if the additional ClawX safety snapshot cannot be written.
logger.warn('[upgrade] Failed to create OpenClaw 2026.7.1 pre-migration snapshot:', error);
}
});
await measureAsync(timingsMs, 'legacyUpdateCheckCleanupMs', async () => {
try {
const cleanup = await quarantineLegacyUpdateCheckState();
if (cleanup.status === 'quarantined') {
logger.info(
`[upgrade] Quarantined conflicting legacy update-check state: ${cleanup.sourcePath}${cleanup.backupPath}`,
);
}
} catch (error) {
logger.warn('[upgrade] Failed to quarantine legacy update-check state:', error);
}
});
const appSettings = await measureAsync(timingsMs, 'settingsMs', getAllSettings);
const prelaunchSummary = await measureAsync(timingsMs, 'prelaunchSyncMs', async () => (
await syncGatewayConfigBeforeLaunch(appSettings, openclawDir)
@@ -636,8 +712,15 @@ export async function prepareGatewayLaunchContext(port: number): Promise<Gateway
...proxyEnv,
OPENCLAW_GATEWAY_TOKEN: appSettings.gatewayToken,
OPENCLAW_SKIP_CHANNELS: skipChannels ? '1' : '',
CLAWDBOT_SKIP_CHANNELS: skipChannels ? '1' : '',
OPENCLAW_NO_RESPAWN: '1',
// Disable OpenClaw's interactive-shell env snapshot. When the Gateway runs
// as an Electron utilityProcess, `process.execPath` is the Electron binary,
// and OpenClaw captures the shell env by spawning `process.execPath -e
// <script>` inside a sanitized login shell that strips ELECTRON_RUN_AS_NODE.
// Electron then treats the script as an app path and pops up "Unable to find
// Electron app at <cwd>/const safe = new Set(...)". Turning the snapshot off
// avoids that broken spawn; exec tools fall back to the Gateway launch env.
OPENCLAW_EXEC_SHELL_SNAPSHOT: '0',
};
// Ensure extension-specific packages (e.g. grammy from the telegram
+4 -2
View File
@@ -27,7 +27,6 @@ export function dispatchProtocolEvent(
if (normalized) {
emitter.emit('chat:runtime-event', normalized);
}
emitter.emit('notification', { method: event, params: payload });
break;
}
case 'channel.status':
@@ -53,14 +52,17 @@ export function dispatchJsonRpcNotification(
emitter: GatewayEventEmitter,
notification: JsonRpcNotification,
): void {
emitter.emit('notification', notification);
if (notification.method === 'agent') {
const normalized = normalizeGatewayChatRuntimeEvent(notification.params);
if (normalized) {
emitter.emit('chat:runtime-event', normalized);
}
} else {
emitter.emit('notification', notification);
}
switch (notification.method) {
case 'agent':
break;
case GatewayEventType.CHANNEL_STATUS_CHANGED:
emitter.emit('channel:status', notification.params as GatewayChannelStatusEvent);
break;
+120 -205
View File
@@ -14,13 +14,19 @@ import {
loadOrCreateDeviceIdentity,
type DeviceIdentity,
} from '../utils/device-identity';
import {
cancelLocalDeviceAutoApproval,
scheduleLocalDeviceAutoApproval,
} from '../utils/control-ui-device-pairing';
import {
DEFAULT_RECONNECT_CONFIG,
type ReconnectConfig,
type GatewayLifecycleState,
getReconnectScheduleDecision,
getReconnectSkipReason,
isOpenClawFatalConfigExitCode,
} from './process-policy';
import { removeOpenClaw2026_7_1UpgradeSnapshot } from '../utils/openclaw-upgrade-snapshot';
import {
clearPendingGatewayRequests,
rejectPendingGatewayRequest,
@@ -45,12 +51,18 @@ import { launchGatewayProcess } from './process-launcher';
import { GatewayRestartController } from './restart-controller';
import { GatewayRestartGovernor } from './restart-governor';
import {
DEFAULT_GATEWAY_RELOAD_POLICY,
loadGatewayReloadPolicy,
type GatewayReloadPolicy,
} from './reload-policy';
import { classifyGatewayStderrMessage, recordGatewayStartupStderrLine } from './startup-stderr';
classifyGatewayStderrMessage,
GATEWAY_STARTUP_SLOW_STAGE_MS,
GATEWAY_STARTUP_SLOW_TOTAL_MS,
GatewayStartupTraceCollector,
recordGatewayStartupStderrLine,
} from './startup-stderr';
import { runGatewayStartupSequence } from './startup-orchestrator';
import {
hasFatalRuntimeFailureSignal,
hasInvalidConfigFailureSignal,
hasStartupMigrationLockSignal,
} from './startup-recovery';
import {
GatewayCapabilityMonitor,
type GatewayCapabilityName,
@@ -170,6 +182,7 @@ export class GatewayManager extends EventEmitter {
private startLock = false;
private lastSpawnSummary: string | null = null;
private recentStartupStderrLines: string[] = [];
private readonly startupTraceCollector = new GatewayStartupTraceCollector();
private pendingRequests: Map<string, PendingGatewayRequest> = new Map();
private deviceIdentity: DeviceIdentity | null = null;
private restartInFlight: Promise<void> | null = null;
@@ -177,21 +190,15 @@ export class GatewayManager extends EventEmitter {
private readonly lifecycleController = new GatewayLifecycleController();
private readonly restartController = new GatewayRestartController();
private readonly restartGovernor = new GatewayRestartGovernor();
private reloadDebounceTimer: NodeJS.Timeout | null = null;
private initialReadyHeartbeatRecoveryTimer: NodeJS.Timeout | null = null;
private reloadPolicy: GatewayReloadPolicy = { ...DEFAULT_GATEWAY_RELOAD_POLICY };
private reloadPolicyLoadedAt = 0;
private reloadPolicyRefreshPromise: Promise<void> | null = null;
private upgradeSnapshotCleanupAttempted = false;
private externalShutdownSupported: boolean | null = null;
private reconnectAttemptsTotal = 0;
private reconnectSuccessTotal = 0;
private static readonly RELOAD_POLICY_REFRESH_MS = 15_000;
private static readonly HEARTBEAT_INTERVAL_MS = 60_000;
private static readonly HEARTBEAT_TIMEOUT_MS = 30_000;
private static readonly HEARTBEAT_MAX_MISSES = 4;
public static readonly RESTART_COOLDOWN_MS = 5_000;
private static readonly GATEWAY_READY_FALLBACK_PROBE_DELAYS_MS = [1_500, 3_000, 5_000, 8_000, 12_000, 30_000] as const;
private static readonly INITIAL_READY_HEARTBEAT_RECOVERY_GRACE_MS = 5 * 60_000;
private lastRestartAt = 0;
/** Set by scheduleReconnect() before calling start() to signal auto-reconnect. */
private isAutoReconnectStart = false;
@@ -235,11 +242,11 @@ export class GatewayManager extends EventEmitter {
this.on('gateway:ready', () => {
this.resetGatewayReadyFallback();
this.clearInitialReadyHeartbeatRecoveryTimer();
if (this.status.state === 'running' && !this.status.gatewayReady) {
logger.info('Gateway subsystems ready (event received)');
this.setStatus({ gatewayReady: true });
}
void this.cleanupOpenClawUpgradeSnapshot();
});
this.on('gateway:health', (payload) => {
this.capabilityMonitor.recordOpenClawHealth(payload);
@@ -323,8 +330,6 @@ export class GatewayManager extends EventEmitter {
logger.info(`Gateway start requested (port=${this.status.port})`);
this.lastSpawnSummary = null;
this.shouldReconnect = true;
await this.refreshReloadPolicy(true);
// Lazily load device identity (async file I/O + key generation).
// Must happen before connect() which uses the identity for the handshake.
await this.initDeviceIdentity();
@@ -406,21 +411,48 @@ export class GatewayManager extends EventEmitter {
tSpawned = Date.now();
},
waitForReady: async (port) => {
const recoveringOwnedProcess = tSpawned === 0
&& this.process?.pid != null
&& this.ownsProcess;
await waitForGatewayReady({
port,
getProcessExitCode: () => this.processExitCode,
// A code-1012 in-process reload normally returns within seconds.
// Do not hold the lifecycle lock for the general 2400-attempt cold
// startup budget when the owned process is alive but no longer serves WS.
...(recoveringOwnedProcess ? { retries: 50 } : {}),
});
tReady = Date.now();
},
terminateStaleOwnedProcess: async () => {
const shouldReconnect = this.shouldReconnect;
this.shouldReconnect = false;
try {
await this.forceTerminateOwnedProcessForQuit();
} finally {
this.shouldReconnect = shouldReconnect;
}
},
onConnectedToManagedGateway: () => {
this.startHealthCheck();
const tConnected = Date.now();
logger.info('[metric] gateway.startup', {
const spawnToReadyMs = tReady && tSpawned ? tReady - tSpawned : undefined;
const startupTrace = this.startupTraceCollector.getSummary();
const startupMetric = {
configSyncMs: tSpawned ? tSpawned - t0 : undefined,
spawnToReadyMs: tReady && tSpawned ? tReady - tSpawned : undefined,
spawnToReadyMs,
readyToConnectMs: tReady ? tConnected - tReady : undefined,
totalMs: tConnected - t0,
});
openclawTrace: startupTrace,
};
logger.info('[metric] gateway.startup', startupMetric);
if (spawnToReadyMs !== undefined && spawnToReadyMs >= GATEWAY_STARTUP_SLOW_TOTAL_MS) {
logger.warn('[gateway-startup] Slow managed Gateway startup detected', {
pid: this.status.pid,
spawnToReadyMs,
openclawTrace: startupTrace,
});
}
},
runDoctorRepair: async () => await runOpenClawDoctorRepair(),
onDoctorRepairSuccess: () => {
@@ -440,7 +472,17 @@ export class GatewayManager extends EventEmitter {
error
);
this.setStatus({ state: 'error', error: String(error) });
if (this.shouldReconnect) {
const fatalStartupFailure = isOpenClawFatalConfigExitCode(this.processExitCode)
|| hasFatalRuntimeFailureSignal(error, this.recentStartupStderrLines)
|| hasStartupMigrationLockSignal(error, this.recentStartupStderrLines)
|| hasInvalidConfigFailureSignal(error, this.recentStartupStderrLines);
if (fatalStartupFailure) {
// OpenClaw 2026.7.1 uses EX_CONFIG for fatal configuration failures.
// Runtime and SQLite compatibility failures are likewise not repaired
// by restarting the same binary, so leave recovery to a manual start.
this.shouldReconnect = false;
logger.error('Gateway startup failed fatally; automatic reconnect disabled');
} else if (this.shouldReconnect) {
logger.warn('Gateway start failed; scheduling auto-reconnect recovery');
this.scheduleReconnect();
}
@@ -468,6 +510,7 @@ export class GatewayManager extends EventEmitter {
*/
async stop(): Promise<void> {
logger.info('Gateway stop requested');
cancelLocalDeviceAutoApproval();
this.lifecycleController.bump('stop');
// Disable auto-reconnect
this.shouldReconnect = false;
@@ -645,138 +688,6 @@ export class GatewayManager extends EventEmitter {
});
}
/**
* Ask the Gateway process to reload config in-place when possible.
* Falls back to restart on unsupported platforms or signaling failures.
*/
async reload(): Promise<void> {
await this.refreshReloadPolicy();
if (this.reloadPolicy.mode === 'off' || this.reloadPolicy.mode === 'restart') {
logger.info(
`[gateway-refresh] mode=reload result=policy_forced_restart policy=${this.reloadPolicy.mode}`,
);
await this.restart();
return;
}
if (this.restartController.isRestartDeferred({
state: this.status.state,
startLock: this.startLock,
})) {
this.restartController.markDeferredRestart('reload', {
state: this.status.state,
startLock: this.startLock,
});
return;
}
const pidBefore = this.process?.pid;
logger.info(`[gateway-refresh] mode=reload requested pid=${pidBefore ?? 'n/a'} state=${this.status.state}`);
if (!this.process?.pid || this.status.state !== 'running') {
logger.warn('[gateway-refresh] mode=reload result=fallback_restart cause=not_running');
logger.warn('Gateway reload requested while not running; falling back to restart');
await this.restart();
return;
}
const connectedForMs = this.status.connectedAt
? Date.now() - this.status.connectedAt
: Number.POSITIVE_INFINITY;
// Avoid signaling a process that just came up; it will already read latest config.
if (connectedForMs < 8000) {
logger.info(
`[gateway-refresh] mode=reload result=skipped_recent_connect connectedForMs=${connectedForMs} pid=${this.process.pid}`,
);
logger.info(`Gateway connected ${connectedForMs}ms ago, skipping reload signal`);
return;
}
if (process.platform === 'win32') {
// Windows does not support SIGUSR1 for in-process reload.
// Fall back to a full restart. The connectedForMs < 8000 guard above
// already skips unnecessary restarts for recently-started processes.
logger.warn('[gateway-refresh] mode=reload result=fallback_restart cause=windows');
await this.restart();
return;
}
try {
process.kill(this.process.pid, 'SIGUSR1');
logger.info(`Sent SIGUSR1 to Gateway for config reload (pid=${this.process.pid})`);
// Some gateway builds do not handle SIGUSR1 as an in-process reload.
// If process state doesn't recover quickly, fall back to restart.
await new Promise((resolve) => setTimeout(resolve, 1500));
if (this.status.state !== 'running' || !this.process?.pid) {
logger.warn('[gateway-refresh] mode=reload result=fallback_restart cause=post_signal_unhealthy');
logger.warn('Gateway did not stay running after reload signal, falling back to restart');
await this.restart();
} else {
const pidAfter = this.process.pid;
logger.info(
`[gateway-refresh] mode=reload result=applied_in_place pidBefore=${pidBefore} pidAfter=${pidAfter}`,
);
}
} catch (error) {
logger.warn('[gateway-refresh] mode=reload result=fallback_restart cause=signal_error');
logger.warn('Gateway reload signal failed, falling back to restart:', error);
await this.restart();
}
}
/**
* Debounced reload — coalesces multiple rapid config-change events into one
* in-process reload when possible.
*/
debouncedReload(delayMs?: number): void {
void this.refreshReloadPolicy();
const effectiveDelay = delayMs ?? this.reloadPolicy.debounceMs;
if (this.reloadPolicy.mode === 'off' || this.reloadPolicy.mode === 'restart') {
logger.debug(
`Gateway reload policy=${this.reloadPolicy.mode}; routing debouncedReload to debouncedRestart (${effectiveDelay}ms)`,
);
this.debouncedRestart(effectiveDelay);
return;
}
if (this.reloadDebounceTimer) {
clearTimeout(this.reloadDebounceTimer);
}
logger.debug(`Gateway reload debounced (will fire in ${effectiveDelay}ms)`);
this.reloadDebounceTimer = setTimeout(() => {
this.reloadDebounceTimer = null;
void this.reload().catch((err) => {
logger.warn('Debounced Gateway reload failed:', err);
});
}, effectiveDelay);
}
private async refreshReloadPolicy(force = false): Promise<void> {
const now = Date.now();
if (!force && now - this.reloadPolicyLoadedAt < GatewayManager.RELOAD_POLICY_REFRESH_MS) {
return;
}
if (this.reloadPolicyRefreshPromise) {
await this.reloadPolicyRefreshPromise;
return;
}
this.reloadPolicyRefreshPromise = (async () => {
const nextPolicy = await loadGatewayReloadPolicy();
this.reloadPolicy = nextPolicy;
this.reloadPolicyLoadedAt = Date.now();
})();
try {
await this.reloadPolicyRefreshPromise;
} finally {
this.reloadPolicyRefreshPromise = null;
}
}
/**
* Clear all active timers
*/
@@ -787,12 +698,7 @@ export class GatewayManager extends EventEmitter {
}
this.connectionMonitor.clear();
this.restartController.clearDebounceTimer();
if (this.reloadDebounceTimer) {
clearTimeout(this.reloadDebounceTimer);
this.reloadDebounceTimer = null;
}
this.resetGatewayReadyFallback();
this.clearInitialReadyHeartbeatRecoveryTimer();
}
private clearGatewayReadyFallbackTimer(): void {
@@ -845,6 +751,10 @@ export class GatewayManager extends EventEmitter {
logger.info('Gateway ready fallback RPC router probe succeeded');
this.resetGatewayReadyFallback();
this.setStatus({ gatewayReady: true });
// A fast Gateway can emit gateway.ready before the WebSocket client is
// attached. A successful router probe is equivalent readiness, so it
// must also complete the one-time migration snapshot lifecycle.
void this.cleanupOpenClawUpgradeSnapshot();
}
} catch (error) {
this.capabilityMonitor.recordCoreProbe({
@@ -999,7 +909,6 @@ export class GatewayManager extends EventEmitter {
}
private recordGatewayAlive(): void {
this.clearInitialReadyHeartbeatRecoveryTimer();
this.diagnostics.lastAliveAt = Date.now();
this.diagnostics.consecutiveHeartbeatMisses = 0;
}
@@ -1034,8 +943,10 @@ export class GatewayManager extends EventEmitter {
await unloadLaunchctlGatewayService();
this.processExitCode = null;
// Per-process dedup map for stderr lines — resets on each new spawn.
// Per-process diagnostics reset on each new spawn so retries never mix
// timings or stderr deduplication state from different Gateway children.
const stderrDedup = new Map<string, number>();
this.startupTraceCollector.reset();
const { child, lastSpawnSummary } = await launchGatewayProcess({
port: this.status.port,
@@ -1045,6 +956,7 @@ export class GatewayManager extends EventEmitter {
getShouldReconnect: () => this.shouldReconnect,
onStderrLine: (line) => {
recordGatewayStartupStderrLine(this.recentStartupStderrLines, line);
const traceStage = this.startupTraceCollector.record(line);
const classified = classifyGatewayStderrMessage(line);
if (classified.level === 'drop') return;
@@ -1059,10 +971,24 @@ export class GatewayManager extends EventEmitter {
return;
}
if (traceStage) {
const message = `[gateway-startup] stage=${traceStage.name} durationMs=${traceStage.durationMs}`
+ (traceStage.totalMs === undefined ? '' : ` totalMs=${traceStage.totalMs}`);
if (traceStage.durationMs >= GATEWAY_STARTUP_SLOW_STAGE_MS) {
logger.warn(`${message} slow=true`);
} else {
logger.info(message);
}
return;
}
if (classified.level === 'debug') {
logger.debug(`[Gateway stderr] ${classified.normalized}`);
return;
}
if (classified.level === 'info') {
logger.info(`[Gateway stderr] ${classified.normalized}`);
return;
}
logger.warn(`[Gateway stderr] ${classified.normalized}`);
},
onSpawn: (pid) => {
@@ -1081,16 +1007,23 @@ export class GatewayManager extends EventEmitter {
this.setStatus({ state: 'stopped' });
}
// Always attempt reconnect from process exit. scheduleReconnect()
// internally checks shouldReconnect and reconnect-timer guards, so
// calling it unconditionally is safe — intentional stop() calls set
// shouldReconnect=false which makes scheduleReconnect() no-op.
//
// On Windows, the WS close handler intentionally skips reconnect
// (to avoid racing with this exit handler). However, WS close
// fires *before* process exit and sets state='stopped', which
// previously caused this handler to also skip reconnect — leaving
// the gateway permanently dead with no recovery path.
const orchestratedStartupFailure = isOpenClawFatalConfigExitCode(code)
|| hasFatalRuntimeFailureSignal(undefined, this.recentStartupStderrLines)
|| hasStartupMigrationLockSignal(undefined, this.recentStartupStderrLines)
|| hasInvalidConfigFailureSignal(undefined, this.recentStartupStderrLines);
if (orchestratedStartupFailure) {
// During startup the orchestrator may still perform its one bounded
// doctor repair. Do not race it with an independent reconnect timer.
// If orchestration cannot recover, start() disables reconnect in its
// catch path so migration/config failures cannot create an outer loop.
if (this.status.state !== 'starting') this.shouldReconnect = false;
logger.error(`Gateway process reported a non-retriable startup condition (code=${String(code)}); reconnect not scheduled`);
return;
}
// Always attempt reconnect from non-fatal process exits.
// scheduleReconnect() internally checks shouldReconnect and timer
// guards, so intentional stop() remains a no-op.
this.scheduleReconnect();
},
onError: () => {
@@ -1131,14 +1064,21 @@ export class GatewayManager extends EventEmitter {
});
this.startPing();
this.scheduleGatewayReadyFallback();
scheduleLocalDeviceAutoApproval(this);
},
onMessage: (message) => {
this.handleMessage(message);
},
onCloseAfterHandshake: (closeCode) => {
cancelLocalDeviceAutoApproval();
this.connectionMonitor.clear();
this.recordSocketClose(closeCode);
this.diagnostics.consecutiveHeartbeatMisses = 0;
if (closeCode === 1012) {
for (const id of [...this.pendingRequests.keys()]) {
rejectPendingGatewayRequest(this.pendingRequests, id, new Error('Gateway service restart'));
}
}
if (this.status.state === 'running') {
this.setStatus({ state: 'stopped' });
// On Windows, skip reconnect from WS close. The Gateway is a local
@@ -1220,7 +1160,7 @@ export class GatewayManager extends EventEmitter {
}
/**
* Start ping interval to keep connection alive
* Observe Gateway control-plane responsiveness and recover after a sustained outage.
*/
private startPing(): void {
this.connectionMonitor.startPing({
@@ -1244,16 +1184,7 @@ export class GatewayManager extends EventEmitter {
logger.warn('Gateway heartbeat recovery skipped (lifecycle is not in auto-recoverable running state)');
return;
}
const initialReadyRecoveryDelayMs = this.getInitialReadyHeartbeatRecoveryDelayMs();
if (initialReadyRecoveryDelayMs > 0) {
logger.warn(
`Gateway heartbeat recovery deferred while waiting for initial gateway.ready ` +
`(retryAfterMs=${initialReadyRecoveryDelayMs})`,
);
this.scheduleInitialReadyHeartbeatRecovery(initialReadyRecoveryDelayMs);
return;
}
logger.warn('Gateway heartbeat recovery: restarting unresponsive gateway process');
logger.warn('Gateway heartbeat recovery: restarting persistently unresponsive gateway process');
void this.restart().catch((error) => {
logger.warn('Gateway heartbeat recovery failed:', error);
});
@@ -1261,34 +1192,18 @@ export class GatewayManager extends EventEmitter {
});
}
private getInitialReadyHeartbeatRecoveryDelayMs(now = Date.now()): number {
if (this.status.gatewayReady || !this.status.connectedAt) return 0;
const connectedForMs = Math.max(0, now - this.status.connectedAt);
return Math.max(0, GatewayManager.INITIAL_READY_HEARTBEAT_RECOVERY_GRACE_MS - connectedForMs);
}
private async cleanupOpenClawUpgradeSnapshot(): Promise<void> {
if (this.upgradeSnapshotCleanupAttempted) return;
this.upgradeSnapshotCleanupAttempted = true;
private scheduleInitialReadyHeartbeatRecovery(delayMs: number): void {
if (this.initialReadyHeartbeatRecoveryTimer) return;
this.initialReadyHeartbeatRecoveryTimer = setTimeout(() => {
this.initialReadyHeartbeatRecoveryTimer = null;
if (
!this.shouldReconnect
|| this.status.state !== 'running'
|| this.status.gatewayReady
) {
return;
try {
const result = await removeOpenClaw2026_7_1UpgradeSnapshot();
if (result.status === 'removed') {
logger.info(`[upgrade] Removed OpenClaw 2026.7.1 pre-migration snapshot: ${result.snapshotDir}`);
}
logger.warn('Gateway heartbeat recovery: initial gateway.ready grace expired, restarting unresponsive gateway process');
void this.restart().catch((error) => {
logger.warn('Gateway heartbeat recovery failed:', error);
});
}, delayMs);
}
private clearInitialReadyHeartbeatRecoveryTimer(): void {
if (!this.initialReadyHeartbeatRecoveryTimer) return;
clearTimeout(this.initialReadyHeartbeatRecoveryTimer);
this.initialReadyHeartbeatRecoveryTimer = null;
} catch (error) {
logger.warn('[upgrade] Failed to remove OpenClaw 2026.7.1 pre-migration snapshot:', error);
}
}
/**
+17 -2
View File
@@ -80,6 +80,20 @@ const GATEWAY_FETCH_PRELOAD_SOURCE = `'use strict';
})();
`;
export function buildGatewayRuntimeEnv(
forkEnv: Record<string, string | undefined>,
): Record<string, string | undefined> {
return {
...forkEnv,
// ClawX does not expose LAN discovery, so keep Bonjour disabled even if
// the parent process inherited an explicit opt-in value.
OPENCLAW_DISABLE_BONJOUR: '1',
// OpenClaw's built-in trace contains stage names and timings only. Keep it
// enabled so packaged startup incidents are diagnosable from normal logs.
OPENCLAW_GATEWAY_STARTUP_TRACE: '1',
};
}
function ensureGatewayFetchPreload(): string {
const dest = path.join(app.getPath('userData'), 'gateway-fetch-preload.cjs');
try {
@@ -118,7 +132,7 @@ export async function launchGatewayProcess(options: {
);
const lastSpawnSummary = `mode=${mode}, entry="${entryScript}", args="${options.sanitizeSpawnArgs(gatewayArgs).join(' ')}", cwd="${openclawDir}"`;
const runtimeEnv = { ...forkEnv };
const runtimeEnv = buildGatewayRuntimeEnv(forkEnv);
// Disable OpenClaw's mDNS/Bonjour gateway advertiser unconditionally.
//
@@ -136,7 +150,8 @@ export async function launchGatewayProcess(options: {
// `startGatewayBonjourAdvertiser()` (openclaw `src/infra/bonjour.ts`,
// `isDisabledByEnv()`). Set after the `forkEnv` spread so any
// pre-existing value inherited from the user shell cannot re-enable it.
runtimeEnv.OPENCLAW_DISABLE_BONJOUR = '1';
// buildGatewayRuntimeEnv() applies both this policy and startup tracing
// before any development-only environment augmentation below.
// Only apply the fetch/child_process preload in dev mode.
// In packaged builds Electron's UtilityProcess rejects NODE_OPTIONS
+7
View File
@@ -10,6 +10,13 @@ export const DEFAULT_RECONNECT_CONFIG: ReconnectConfig = {
maxDelay: 30000,
};
/** sysexits(3) EX_CONFIG, used by OpenClaw 2026.7.1 for fatal config startup errors. */
export const OPENCLAW_EX_CONFIG_EXIT_CODE = 78;
export function isOpenClawFatalConfigExitCode(code: number | null | undefined): boolean {
return code === OPENCLAW_EX_CONFIG_EXIT_CODE;
}
export function nextLifecycleEpoch(currentEpoch: number): number {
return currentEpoch + 1;
}
-63
View File
@@ -1,63 +0,0 @@
import { readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
export type GatewayReloadMode = 'hybrid' | 'reload' | 'restart' | 'off';
export type GatewayReloadPolicy = {
mode: GatewayReloadMode;
debounceMs: number;
};
export const DEFAULT_GATEWAY_RELOAD_POLICY: GatewayReloadPolicy = {
mode: 'hybrid',
debounceMs: 1200,
};
const OPENCLAW_CONFIG_PATH = join(homedir(), '.openclaw', 'openclaw.json');
const MAX_DEBOUNCE_MS = 60_000;
function normalizeMode(value: unknown): GatewayReloadMode {
if (value === 'off' || value === 'reload' || value === 'restart' || value === 'hybrid') {
return value;
}
return DEFAULT_GATEWAY_RELOAD_POLICY.mode;
}
function normalizeDebounceMs(value: unknown): number {
if (typeof value !== 'number' || !Number.isFinite(value)) {
return DEFAULT_GATEWAY_RELOAD_POLICY.debounceMs;
}
const rounded = Math.round(value);
if (rounded < 0) return 0;
if (rounded > MAX_DEBOUNCE_MS) return MAX_DEBOUNCE_MS;
return rounded;
}
export function parseGatewayReloadPolicy(config: unknown): GatewayReloadPolicy {
if (!config || typeof config !== 'object') {
return { ...DEFAULT_GATEWAY_RELOAD_POLICY };
}
const root = config as Record<string, unknown>;
const gateway = (root.gateway && typeof root.gateway === 'object'
? root.gateway
: {}) as Record<string, unknown>;
const reload = (gateway.reload && typeof gateway.reload === 'object'
? gateway.reload
: {}) as Record<string, unknown>;
return {
mode: normalizeMode(reload.mode),
debounceMs: normalizeDebounceMs(reload.debounceMs),
};
}
export async function loadGatewayReloadPolicy(): Promise<GatewayReloadPolicy> {
try {
const raw = await readFile(OPENCLAW_CONFIG_PATH, 'utf-8');
return parseGatewayReloadPolicy(JSON.parse(raw));
} catch {
return { ...DEFAULT_GATEWAY_RELOAD_POLICY };
}
}
-101
View File
@@ -1,101 +0,0 @@
type GatewayRpcRunner = (method: string, params?: unknown, timeoutMs?: number) => Promise<unknown>;
type QueuedRpc = {
run: () => Promise<void>;
};
function stableStringify(value: unknown): string {
if (value === null || typeof value !== 'object') {
return JSON.stringify(value);
}
if (Array.isArray(value)) {
return `[${value.map((item) => stableStringify(item)).join(',')}]`;
}
const record = value as Record<string, unknown>;
return `{${Object.keys(record).sort().map((key) => (
`${JSON.stringify(key)}:${stableStringify(record[key])}`
)).join(',')}}`;
}
export interface GatewayRpcBackpressureOptions {
maxConcurrentHistory?: number;
}
/**
* Prevents renderer fan-out from forwarding an unbounded number of expensive
* chat.history RPCs to OpenClaw. The Gateway still owns the canonical response;
* this class only coalesces duplicate in-flight history calls and runs distinct
* history requests through a small FIFO queue.
*/
export class GatewayRpcBackpressure {
private readonly maxConcurrentHistory: number;
private readonly inFlightHistory = new Map<string, Promise<unknown>>();
private readonly queue: QueuedRpc[] = [];
private activeHistory = 0;
constructor(options: GatewayRpcBackpressureOptions = {}) {
this.maxConcurrentHistory = Math.max(1, options.maxConcurrentHistory ?? 2);
}
run(
method: string,
params: unknown,
timeoutMs: number | undefined,
runner: GatewayRpcRunner,
): Promise<unknown> {
if (method !== 'chat.history') {
return runner(method, params, timeoutMs);
}
const key = `${method}:${stableStringify(params)}:${timeoutMs ?? 'default'}`;
const existing = this.inFlightHistory.get(key);
if (existing) return existing;
const promise = this.enqueueHistory(() => runner(method, params, timeoutMs))
.finally(() => {
if (this.inFlightHistory.get(key) === promise) {
this.inFlightHistory.delete(key);
}
});
this.inFlightHistory.set(key, promise);
return promise;
}
getDiagnostics(): { activeHistory: number; queuedHistory: number; inFlightHistory: number } {
return {
activeHistory: this.activeHistory,
queuedHistory: this.queue.length,
inFlightHistory: this.inFlightHistory.size,
};
}
private enqueueHistory(work: () => Promise<unknown>): Promise<unknown> {
return new Promise((resolve, reject) => {
const queued: QueuedRpc = {
run: async () => {
this.activeHistory += 1;
try {
resolve(await work());
} catch (error) {
reject(error);
} finally {
this.activeHistory -= 1;
this.drain();
}
},
};
this.queue.push(queued);
this.drain();
});
}
private drain(): void {
while (this.activeHistory < this.maxConcurrentHistory) {
const next = this.queue.shift();
if (!next) return;
void next.run();
}
}
}
+8 -1
View File
@@ -23,6 +23,7 @@ type StartupHooks = {
waitForPortFree: (port: number) => Promise<void>;
startProcess: () => Promise<void>;
waitForReady: (port: number) => Promise<void>;
terminateStaleOwnedProcess: () => Promise<void>;
onConnectedToManagedGateway: () => void;
runDoctorRepair: () => Promise<boolean>;
onDoctorRepairSuccess: () => void;
@@ -75,7 +76,13 @@ export async function runGatewayStartupSequence(hooks: StartupHooks): Promise<vo
// become ready and reconnect to it.
if (hooks.hasOwnedProcess()) {
logger.info('Owned Gateway process still alive (likely in-process restart); waiting for it to become ready');
await hooks.waitForReady(hooks.port);
try {
await hooks.waitForReady(hooks.port);
} catch (error) {
logger.warn('Owned Gateway process did not recover after an in-process restart; terminating the stale process');
await hooks.terminateStaleOwnedProcess();
throw new Error('Gateway process exited before becoming ready after an in-process restart', { cause: error });
}
hooks.assertLifecycle('start/wait-ready-owned');
await connectWithStartupRetry(hooks, hooks.port);
hooks.assertLifecycle('start/connect-owned');
+54 -6
View File
@@ -8,10 +8,25 @@
const INVALID_CONFIG_PATTERNS: RegExp[] = [
/\binvalid config\b/i,
/\bconfig invalid\b/i,
/\bfatal configuration error\b/i,
/\bunrecognized key\b/i,
/\bstartup migration(?:s)?\b.*\b(?:blocked|failed|did not complete cleanly)\b/i,
/\bmigration\b.*\bopenclaw doctor --fix\b/i,
/\brun:\s*openclaw doctor --fix\b/i,
];
const FATAL_RUNTIME_PATTERNS: RegExp[] = [
/\bNode(?:\.js)?\b.*\boutside the supported range\b/i,
/\buses SQLite\b.*\bnot WAL-reset-safe\b/i,
/\bSQLite\b.*\bWAL-reset-safe runtime required\b/i,
/\bInstall Node 24\.15\+.*\bNode 22\.22\.3\+\b/i,
];
const STARTUP_MIGRATION_LOCK_PATTERNS: RegExp[] = [
/\bstartup migrations? (?:is|are) already running\b/i,
/\bretry after the other gateway finishes\b/i,
];
const TRANSIENT_START_ERROR_PATTERNS: RegExp[] = [
/WebSocket closed before handshake/i,
/ECONNREFUSED/i,
@@ -61,6 +76,33 @@ export function hasInvalidConfigFailureSignal(
return isInvalidConfigSignal(errorText);
}
function startupFailureCandidates(startupError: unknown, startupStderrLines: string[]): string[] {
return [
...startupStderrLines,
startupError instanceof Error
? `${startupError.name}: ${startupError.message}`
: String(startupError ?? ''),
];
}
/** Returns true for OpenClaw runtime/SQLite failures that doctor cannot repair. */
export function hasFatalRuntimeFailureSignal(
startupError: unknown,
startupStderrLines: string[],
): boolean {
return startupFailureCandidates(startupError, startupStderrLines)
.some((text) => FATAL_RUNTIME_PATTERNS.some((pattern) => pattern.test(text)));
}
/** Returns true while another/stale OpenClaw startup migration lease is active. */
export function hasStartupMigrationLockSignal(
startupError: unknown,
startupStderrLines: string[],
): boolean {
return startupFailureCandidates(startupError, startupStderrLines)
.some((text) => STARTUP_MIGRATION_LOCK_PATTERNS.some((pattern) => pattern.test(text)));
}
/**
* Retry guard for one-time config repair during a single startup flow.
*/
@@ -136,12 +178,18 @@ export function getGatewayStartupRecoveryAction(options: {
attempt: number;
maxAttempts: number;
}): GatewayStartupRecoveryAction {
if (shouldAttemptConfigAutoRepair(
options.startupError,
options.startupStderrLines,
options.configRepairAttempted,
)) {
return 'repair';
if (
hasFatalRuntimeFailureSignal(options.startupError, options.startupStderrLines)
|| hasStartupMigrationLockSignal(options.startupError, options.startupStderrLines)
) {
return 'fail';
}
if (hasInvalidConfigFailureSignal(options.startupError, options.startupStderrLines)) {
// One doctor pass is the only automated repair. If the same migration or
// config failure remains afterward, stop instead of treating the generic
// process-exited error as transient.
return options.configRepairAttempted ? 'fail' : 'repair';
}
if (options.attempt < options.maxAttempts && isTransientGatewayStartError(options.startupError)) {
+107 -10
View File
@@ -1,40 +1,137 @@
export type GatewayStderrClassification = {
level: 'drop' | 'debug' | 'warn';
level: 'drop' | 'debug' | 'info' | 'warn';
normalized: string;
};
export type GatewayStartupTraceStage = {
name: string;
durationMs: number;
totalMs?: number;
};
export type GatewayStartupTraceSummary = {
stageCount: number;
lastStage?: string;
traceTotalMs?: number;
slowestStage?: string;
slowestStageMs?: number;
};
export const GATEWAY_STARTUP_SLOW_STAGE_MS = 10_000;
export const GATEWAY_STARTUP_SLOW_TOTAL_MS = 30_000;
const MAX_STDERR_LINES = 120;
const ANSI_ESCAPE_PATTERN = new RegExp(String.raw`\u001B\[[0-?]*[ -/]*[@-~]`, 'g');
const STARTUP_TRACE_PATTERN = /startup trace:\s+([^\s]+)\s+(\d+(?:\.\d+)?)ms(?:\s+total=(\d+(?:\.\d+)?)ms)?/i;
export function parseGatewayStartupTraceStage(message: string): GatewayStartupTraceStage | null {
const match = STARTUP_TRACE_PATTERN.exec(message.replace(ANSI_ESCAPE_PATTERN, ''));
if (!match) return null;
const durationMs = Number(match[2]);
const totalMs = match[3] === undefined ? undefined : Number(match[3]);
if (!Number.isFinite(durationMs) || (totalMs !== undefined && !Number.isFinite(totalMs))) {
return null;
}
return {
name: match[1]!,
durationMs,
...(totalMs === undefined ? {} : { totalMs }),
};
}
export class GatewayStartupTraceCollector {
private stageCount = 0;
private lastStage: GatewayStartupTraceStage | null = null;
private slowestStage: GatewayStartupTraceStage | null = null;
private maxTraceTotalMs: number | undefined;
reset(): void {
this.stageCount = 0;
this.lastStage = null;
this.slowestStage = null;
this.maxTraceTotalMs = undefined;
}
record(message: string): GatewayStartupTraceStage | null {
const stage = parseGatewayStartupTraceStage(message);
if (!stage) return null;
this.stageCount += 1;
this.lastStage = stage;
if (!this.slowestStage || stage.durationMs > this.slowestStage.durationMs) {
this.slowestStage = stage;
}
if (stage.totalMs !== undefined) {
this.maxTraceTotalMs = Math.max(this.maxTraceTotalMs ?? 0, stage.totalMs);
}
return stage;
}
getSummary(): GatewayStartupTraceSummary {
return {
stageCount: this.stageCount,
...(this.lastStage ? { lastStage: this.lastStage.name } : {}),
...(this.maxTraceTotalMs === undefined ? {} : { traceTotalMs: this.maxTraceTotalMs }),
...(this.slowestStage ? {
slowestStage: this.slowestStage.name,
slowestStageMs: this.slowestStage.durationMs,
} : {}),
};
}
}
export function classifyGatewayStderrMessage(message: string): GatewayStderrClassification {
const msg = message.trim();
if (!msg) {
return { level: 'drop', normalized: msg };
}
const plain = msg.replace(ANSI_ESCAPE_PATTERN, '');
// OpenClaw startup timing traces are expected diagnostics, not failures.
if (plain.includes('startup trace:')) {
return { level: 'info', normalized: msg };
}
// Known noisy lines that are not actionable for Gateway lifecycle debugging.
if (msg.includes('openclaw-control-ui') && msg.includes('token_mismatch')) {
if (plain.includes('openclaw-control-ui') && plain.includes('token_mismatch')) {
return { level: 'drop', normalized: msg };
}
if (msg.includes('closed before connect') && msg.includes('token mismatch')) {
if (plain.includes('closed before connect') && plain.includes('token mismatch')) {
return { level: 'drop', normalized: msg };
}
if (msg.includes('[ws] closed before connect') && msg.includes('code=1005')) {
if (plain.includes('[ws] closed before connect') && plain.includes('code=1005')) {
return { level: 'debug', normalized: msg };
}
if (msg.includes('security warning: dangerous config flags enabled')) {
if (
plain.includes('[ws] closed before connect')
&& plain.includes('code=1006')
&& plain.includes('phase=ws_upgrade_started')
&& plain.includes('ua=n/a')
) {
return { level: 'debug', normalized: msg };
}
if (plain.includes('security warning: dangerous config flags enabled')) {
return { level: 'debug', normalized: msg };
}
// Downgrade frequent non-fatal noise.
if (msg.includes('ExperimentalWarning')) return { level: 'debug', normalized: msg };
if (msg.includes('DeprecationWarning')) return { level: 'debug', normalized: msg };
if (msg.includes('Debugger attached')) return { level: 'debug', normalized: msg };
if (plain.includes('ExperimentalWarning')) return { level: 'debug', normalized: msg };
if (plain.includes('DeprecationWarning')) return { level: 'debug', normalized: msg };
if (plain.includes('Rename them by replacing the legacy prefix with OPENCLAW_')) {
return { level: 'debug', normalized: msg };
}
if (plain.includes('--trace-deprecation') && plain.includes('show where the warning was created')) {
return { level: 'debug', normalized: msg };
}
if (plain.includes('Debugger attached')) return { level: 'debug', normalized: msg };
// Gateway config warnings (e.g. stale plugin entries) are informational, not actionable.
if (msg.includes('Config warnings:')) return { level: 'debug', normalized: msg };
if (plain.includes('Config warnings:')) return { level: 'debug', normalized: msg };
// Electron restricts NODE_OPTIONS in packaged apps; this is expected and harmless.
if (msg.includes('node: --require is not allowed in NODE_OPTIONS')) {
if (plain.includes('node: --require is not allowed in NODE_OPTIONS')) {
return { level: 'debug', normalized: msg };
}
+10 -1
View File
@@ -9,6 +9,7 @@ const SECRET_KEYS = new Set([
'accesstoken',
'refreshtoken',
]);
const CONFIG_WRITE_METHODS = new Set(['config.set', 'config.patch', 'config.apply']);
export function isGatewayWsTraceEnabled(): boolean {
return process.env.CLAWX_GATEWAY_WS_TRACE === '1';
@@ -22,9 +23,17 @@ export function redactGatewayFrameForTrace(value: unknown): unknown {
return value;
}
const record = value as Record<string, unknown>;
const redactConfigRaw = typeof record.method === 'string' && CONFIG_WRITE_METHODS.has(record.method);
const result: Record<string, unknown> = {};
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
for (const [key, item] of Object.entries(record)) {
const normalizedKey = key.toLowerCase();
if (redactConfigRaw && key === 'params' && item && typeof item === 'object' && !Array.isArray(item)) {
const params = redactGatewayFrameForTrace(item) as Record<string, unknown>;
if (Object.hasOwn(params, 'raw')) params.raw = '[redacted]';
result[key] = params;
continue;
}
result[key] = SECRET_KEYS.has(normalizedKey)
? '[redacted]'
: redactGatewayFrameForTrace(item);
+47 -34
View File
@@ -2,9 +2,10 @@
* Electron Main Process Entry
* Manages window creation, system tray, and IPC handlers
*/
import { app, BrowserWindow, nativeImage, session, shell } from 'electron';
import { app, BrowserWindow, nativeImage, session, shell, type Session } from 'electron';
import { join } from 'path';
import { GatewayManager } from '../gateway/manager';
import { registerOpenClawConfigCoordinator } from '../gateway/config-delivery';
import { registerIpcHandlers } from './ipc-handlers';
import { HostApiRegistry } from './ipc/host-invoke';
import { createTray } from './tray';
@@ -32,6 +33,8 @@ import { getMacTrafficLightPosition, syncMacTrafficLightPosition } from './traff
import { getSetting } from '../utils/store';
import { applyProxySettings } from './proxy';
import { syncLaunchAtStartupSettingFromStore } from './launch-at-startup';
import { WebBrowserGuestRegistry, installWebBrowserGuestPolicy } from './web-browser-policy';
import { configureWebBrowserSession } from './web-browser-session';
import {
clearPendingSecondInstanceFocus,
consumeMainWindowReady,
@@ -65,22 +68,6 @@ if (isE2EMode && requestedUserDataDir) {
app.setPath('userData', requestedUserDataDir);
}
// Disable GPU hardware acceleration globally for maximum stability across
// all GPU configurations (no GPU, integrated, discrete).
//
// Rationale (following VS Code's philosophy):
// - Page/file loading is async data fetching — zero GPU dependency.
// - The original per-platform GPU branching was added to avoid CPU rendering
// competing with sync I/O on Windows, but all file I/O is now async
// (fs/promises), so that concern no longer applies.
// - Software rendering is deterministic across all hardware; GPU compositing
// behaviour varies between vendors (Intel, AMD, NVIDIA, Apple Silicon) and
// driver versions, making it the #1 source of rendering bugs in Electron.
//
// Users who want GPU acceleration can pass `--enable-gpu` on the CLI or
// set `"disable-hardware-acceleration": false` in the app config (future).
app.disableHardwareAcceleration();
// On Linux, set CHROME_DESKTOP so Chromium can find the correct .desktop file.
// On Wayland this maps the running window to clawx.desktop (→ icon + app grouping);
// on X11 it supplements the StartupWMClass matching.
@@ -133,6 +120,8 @@ let mainWindow: BrowserWindow | null = null;
let gatewayManager!: GatewayManager;
let clawHubService!: ClawHubService;
const hostApiRegistry = new HostApiRegistry();
const webBrowserGuestRegistry = new WebBrowserGuestRegistry();
let webBrowserSession!: Session;
const mainWindowFocusState = createMainWindowFocusState();
const quitLifecycleState = createQuitLifecycleState();
@@ -176,8 +165,6 @@ function createWindow(): BrowserWindow {
const isMac = process.platform === 'darwin';
const isWindows = process.platform === 'win32';
const useCustomTitleBar = isWindows;
const shouldSkipSetupForE2E = process.env.CLAWX_E2E_SKIP_SETUP === '1';
const win = new BrowserWindow({
width: 1280,
height: 800,
@@ -199,6 +186,11 @@ function createWindow(): BrowserWindow {
show: false,
});
installWebBrowserGuestPolicy(win.webContents, {
browserSession: webBrowserSession,
registry: webBrowserGuestRegistry,
});
registerZoomShortcuts(win);
// Handle external links — only allow safe protocols to prevent arbitrary
@@ -217,7 +209,12 @@ function createWindow(): BrowserWindow {
return { action: 'deny' };
});
// Load the app
return win;
}
function loadMainWindow(win: BrowserWindow): void {
const shouldSkipSetupForE2E = process.env.CLAWX_E2E_SKIP_SETUP === '1';
if (process.env.VITE_DEV_SERVER_URL) {
const rendererUrl = new URL(process.env.VITE_DEV_SERVER_URL);
if (shouldSkipSetupForE2E) {
@@ -234,8 +231,6 @@ function createWindow(): BrowserWindow {
: undefined,
});
}
return win;
}
function focusWindow(win: BrowserWindow): void {
@@ -311,6 +306,11 @@ async function initialize(): Promise<void> {
`Runtime: platform=${process.platform}/${process.arch}, electron=${process.versions.electron}, node=${process.versions.node}, packaged=${app.isPackaged}, pid=${process.pid}, ppid=${process.ppid}`
);
webBrowserSession = configureWebBrowserSession({
registry: webBrowserGuestRegistry,
getMainWindow: () => mainWindow,
});
if (!isE2EMode) {
// Warm up network optimization (non-blocking)
void warmupNetworkOptimization();
@@ -331,11 +331,6 @@ async function initialize(): Promise<void> {
// Create the main window
const window = createMainWindow();
// Create system tray
if (!isE2EMode) {
createTray(window);
}
// Override security headers ONLY for the OpenClaw Gateway Control UI.
// The URL filter ensures this callback only fires for gateway requests,
// avoiding unnecessary overhead on every other HTTP response.
@@ -360,7 +355,21 @@ async function initialize(): Promise<void> {
);
// Register IPC handlers
registerIpcHandlers(gatewayManager, clawHubService, window, hostApiRegistry);
registerIpcHandlers(
gatewayManager,
clawHubService,
window,
hostApiRegistry,
webBrowserSession,
webBrowserGuestRegistry,
);
loadMainWindow(window);
// Create system tray
if (!isE2EMode) {
createTray(window);
}
// Initialize extension system
await extensionRegistry.initialize({
@@ -580,6 +589,7 @@ if (gotTheLock) {
}
gatewayManager = new GatewayManager();
registerOpenClawConfigCoordinator(gatewayManager);
clawHubService = new ClawHubService();
// Register builtin extensions and load manifest
@@ -607,16 +617,19 @@ if (gotTheLock) {
});
// Application lifecycle
app.whenReady().then(() => {
void initialize().catch((error) => {
app.whenReady().then(async () => {
try {
await initialize();
} catch (error) {
logger.error('Application initialization failed:', error);
});
return;
}
// Register activate handler AFTER app is ready to prevent
// "Cannot create BrowserWindow before app is ready" on macOS.
// Register only after initialization so activation cannot race the initial
// window or claim the single browser guest before host handlers are ready.
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createMainWindow();
loadMainWindow(createMainWindow());
} else {
focusMainWindow();
}
+52 -99
View File
@@ -2,7 +2,7 @@
* IPC Handlers
* Registers all IPC handlers for main-renderer communication
*/
import { ipcMain, BrowserWindow, shell, dialog, app } from 'electron';
import { ipcMain, BrowserWindow, shell, dialog, app, type Session } from 'electron';
import { existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { join, extname, basename, resolve, sep, relative } from 'node:path';
@@ -25,8 +25,6 @@ import { resolveAgentIdFromChannel } from '../utils/agent-config';
import { resolveAccountIdFromSessionHistory } from '../utils/session-util';
import { whatsAppLoginManager } from '../utils/whatsapp-login';
import { getProviderConfig } from '../utils/provider-registry';
import { deviceOAuthManager } from '../utils/device-oauth';
import { browserOAuthManager } from '../utils/browser-oauth';
import { applyProxySettings } from './proxy';
import { syncLaunchAtStartupSettingFromStore } from './launch-at-startup';
import { getRecentTokenUsageHistory } from '../utils/token-usage';
@@ -42,7 +40,6 @@ import {
} from '../services/providers/provider-runtime-sync';
import { validateApiKeyWithProvider } from '../services/providers/provider-validation';
import { appUpdater } from './updater';
import { GatewayRpcBackpressure } from '../gateway/rpc-backpressure';
import { HostApiRegistry, registerHostInvokeHandler } from './ipc/host-invoke';
import { createAppApi } from '../services/app-api';
import { createOpenClawApi } from '../services/openclaw-api';
@@ -57,6 +54,9 @@ import { createSettingsApi } from '../services/settings-api';
import { createChannelsApi } from '../services/channels-api';
import { createAgentsApi } from '../services/agents-api';
import { createChatApi } from '../services/chat-api';
import { AcpSessionAccessRegistry } from '../services/acp-session-access-registry';
import { createAttachmentAccess, StagedAttachmentRegistry } from '../services/attachment-access';
import { createAttachmentOpenWithService } from '../services/attachment-open-with';
import { createCronApi } from '../services/cron-api';
import { createFilesApi } from '../services/files-api';
import { createMediaApi } from '../services/media-api';
@@ -64,6 +64,8 @@ import { createProvidersApi } from '../services/providers-api';
import { createSessionsApi } from '../services/sessions-api';
import { createSkillsApi } from '../services/skills-api';
import { createUsageApi } from '../services/usage-api';
import { createWebBrowserApi } from '../services/web-browser-api';
import type { WebBrowserGuestRegistry } from './web-browser-policy';
import {
isLaunchAtStartupKey,
isProxyKey,
@@ -73,8 +75,6 @@ import {
} from './ipc/request-helpers';
import { createMenu } from './menu';
const gatewayRpcBackpressure = new GatewayRpcBackpressure();
/**
* Register all IPC handlers
*/
@@ -83,12 +83,21 @@ export function registerIpcHandlers(
clawHubService: ClawHubService,
mainWindow: BrowserWindow,
hostApiRegistry: HostApiRegistry,
browserSession: Session,
registry: WebBrowserGuestRegistry,
): void {
// Unified request protocol (non-breaking: legacy channels remain available)
registerUnifiedRequestHandlers(gatewayManager);
// Typed host invoke handlers (new renderer facade; legacy channels remain available)
registerTypedHostHandlers(gatewayManager, clawHubService, mainWindow, hostApiRegistry);
registerTypedHostHandlers(
gatewayManager,
clawHubService,
mainWindow,
hostApiRegistry,
browserSession,
registry,
);
// Gateway handlers
registerGatewayHandlers(gatewayManager);
@@ -132,25 +141,40 @@ function registerTypedHostHandlers(
clawHubService: ClawHubService,
mainWindow: BrowserWindow,
hostApiRegistry: HostApiRegistry,
browserSession: Session,
registry: WebBrowserGuestRegistry,
): void {
const acpSessionAccessRegistry = new AcpSessionAccessRegistry();
const stagedAttachments = new StagedAttachmentRegistry();
const attachmentOpenWith = createAttachmentOpenWithService();
const attachmentAccess = createAttachmentAccess({
sessionAccessRegistry: acpSessionAccessRegistry,
stagedAttachments,
openWith: attachmentOpenWith,
});
hostApiRegistry.registerCoreServices({
app: createAppApi(),
openclaw: createOpenClawApi(),
shell: createShellApi(),
webBrowser: createWebBrowserApi({ browserSession, registry }),
dialog: createDialogApi(),
window: createWindowApi(mainWindow),
updates: createUpdatesApi(appUpdater),
uv: createUvApi(),
settings: createSettingsApi(gatewayManager),
gateway: createGatewayApi(gatewayManager, gatewayRpcBackpressure),
gateway: createGatewayApi(gatewayManager),
logs: createLogsApi(),
channels: createChannelsApi({ gatewayManager, mainWindow }),
agents: createAgentsApi({ gatewayManager }),
providers: createProvidersApi({ gatewayManager, mainWindow }),
files: createFilesApi(),
media: createMediaApi(),
files: createFilesApi({
attachmentAccess,
openWith: attachmentOpenWith,
stagedAttachments,
}),
media: createMediaApi({ attachmentAccess }),
sessions: createSessionsApi(),
chat: createChatApi({ gatewayManager }),
chat: createChatApi({ gatewayManager, mainWindow, acpSessionAccessRegistry }),
cron: createCronApi({ gatewayManager }),
skills: createSkillsApi({ clawHubService, gatewayManager }),
usage: createUsageApi(),
@@ -269,11 +293,7 @@ function registerUnifiedRequestHandlers(gatewayManager: GatewayManager): void {
}
}
try {
await syncSavedProviderToRuntime(config, apiKey, gatewayManager);
} catch (err) {
console.warn('Failed to sync openclaw provider config:', err);
}
await syncSavedProviderToRuntime(config, apiKey, gatewayManager);
data = { success: true };
} catch (error) {
@@ -288,14 +308,10 @@ function registerUnifiedRequestHandlers(gatewayManager: GatewayManager): void {
try {
const existing = await providerService.getLegacyProvider(providerId);
await providerService.deleteLegacyProvider(providerId);
if (existing?.type) {
try {
await syncDeletedProviderToRuntime(existing, providerId, gatewayManager);
} catch (err) {
console.warn('Failed to completely remove provider from OpenClaw:', err);
}
await syncDeletedProviderToRuntime(existing, providerId, gatewayManager);
}
await providerService.deleteLegacyProvider(providerId);
data = { success: true };
} catch (error) {
data = { success: false, error: String(error) };
@@ -316,11 +332,7 @@ function registerUnifiedRequestHandlers(gatewayManager: GatewayManager): void {
const provider = await providerService.getLegacyProvider(providerId);
const providerType = provider?.type || providerId;
const ock = getOpenClawProviderKey(providerType, providerId);
try {
await saveProviderKeyToOpenClaw(ock, apiKey);
} catch (err) {
console.warn('Failed to save key to OpenClaw auth-profiles:', err);
}
await saveProviderKeyToOpenClaw(ock, apiKey);
data = { success: true };
} catch (error) {
data = { success: false, error: String(error) };
@@ -366,11 +378,7 @@ function registerUnifiedRequestHandlers(gatewayManager: GatewayManager): void {
}
}
try {
await syncUpdatedProviderToRuntime(nextConfig, apiKey, gatewayManager);
} catch (err) {
console.warn('Failed to sync openclaw config after provider update:', err);
}
await syncUpdatedProviderToRuntime(nextConfig, apiKey, gatewayManager);
data = { success: true };
} catch (error) {
@@ -400,12 +408,8 @@ function registerUnifiedRequestHandlers(gatewayManager: GatewayManager): void {
const provider = await providerService.getLegacyProvider(providerId);
const providerType = provider?.type || providerId;
const ock = getOpenClawProviderKey(providerType, providerId);
try {
if (ock) {
await removeProviderFromOpenClaw(ock);
}
} catch (err) {
console.warn('Failed to completely remove provider from OpenClaw:', err);
if (ock) {
await removeProviderFromOpenClaw(ock);
}
data = { success: true };
} catch (error) {
@@ -422,11 +426,7 @@ function registerUnifiedRequestHandlers(gatewayManager: GatewayManager): void {
await providerService.setDefaultLegacyProvider(providerId);
const provider = await providerService.getLegacyProvider(providerId);
if (provider) {
try {
await syncDefaultProviderToRuntime(providerId, gatewayManager);
} catch (err) {
console.warn('Failed to set OpenClaw default model:', err);
}
await syncDefaultProviderToRuntime(providerId, gatewayManager);
}
data = { success: true };
@@ -695,12 +695,7 @@ function registerGatewayHandlers(gatewayManager: GatewayManager): void {
// Gateway RPC call
ipcMain.handle('gateway:rpc', async (_, method: string, params?: unknown, timeoutMs?: number) => {
try {
const result = await gatewayRpcBackpressure.run(
method,
params,
timeoutMs,
(rpcMethod, rpcParams, rpcTimeoutMs) => gatewayManager.rpc(rpcMethod, rpcParams, rpcTimeoutMs),
);
const result = await gatewayManager.rpc(method, params, timeoutMs);
return { success: true, result };
} catch (error) {
logger.warn(`[gateway:rpc] ${method} failed (timeoutMs=${timeoutMs ?? 30000}): ${String(error)}`);
@@ -789,18 +784,6 @@ function registerProviderHandlers(gatewayManager: GatewayManager): void {
);
};
// Listen for OAuth success to automatically restart the Gateway with new tokens/configs.
// Keep a longer debounce (8s) so provider config writes and OAuth token persistence
// can settle before applying the process-level refresh.
deviceOAuthManager.on('oauth:success', ({ provider, accountId }) => {
logger.info(`[IPC] Scheduling Gateway restart after ${provider} OAuth success for ${accountId}...`);
gatewayManager.debouncedRestart(8000);
});
browserOAuthManager.on('oauth:success', ({ provider, accountId }) => {
logger.info(`[IPC] Scheduling Gateway restart after ${provider} OAuth success for ${accountId}...`);
gatewayManager.debouncedRestart(8000);
});
// Get all providers with key info
ipcMain.handle('provider:list', async () => {
logLegacyProviderChannel('provider:list');
@@ -827,20 +810,12 @@ function registerProviderHandlers(gatewayManager: GatewayManager): void {
await providerService.setLegacyProviderApiKey(config.id, trimmedKey);
// Also write to OpenClaw auth-profiles.json so the gateway can use it
try {
await syncProviderApiKeyToRuntime(config.type, config.id, trimmedKey);
} catch (err) {
console.warn('Failed to save key to OpenClaw auth-profiles:', err);
}
await syncProviderApiKeyToRuntime(config.type, config.id, trimmedKey);
}
}
// Sync the provider configuration to openclaw.json so Gateway knows about it
try {
await syncSavedProviderToRuntime(config, apiKey, gatewayManager);
} catch (err) {
console.warn('Failed to sync openclaw provider config:', err);
}
await syncSavedProviderToRuntime(config, apiKey, gatewayManager);
return { success: true };
} catch (error) {
@@ -853,16 +828,10 @@ function registerProviderHandlers(gatewayManager: GatewayManager): void {
logLegacyProviderChannel('provider:delete');
try {
const existing = await providerService.getLegacyProvider(providerId);
await providerService.deleteLegacyProvider(providerId);
// Best-effort cleanup in OpenClaw auth profiles & openclaw.json config
if (existing?.type) {
try {
await syncDeletedProviderToRuntime(existing, providerId, gatewayManager);
} catch (err) {
console.warn('Failed to completely remove provider from OpenClaw:', err);
}
await syncDeletedProviderToRuntime(existing, providerId, gatewayManager);
}
await providerService.deleteLegacyProvider(providerId);
return { success: true };
} catch (error) {
@@ -879,11 +848,7 @@ function registerProviderHandlers(gatewayManager: GatewayManager): void {
// Also write to OpenClaw auth-profiles.json
const provider = await providerService.getLegacyProvider(providerId);
const providerType = provider?.type || providerId;
try {
await syncProviderApiKeyToRuntime(providerType, providerId, apiKey);
} catch (err) {
console.warn('Failed to save key to OpenClaw auth-profiles:', err);
}
await syncProviderApiKeyToRuntime(providerType, providerId, apiKey);
return { success: true };
} catch (error) {
@@ -932,11 +897,7 @@ function registerProviderHandlers(gatewayManager: GatewayManager): void {
}
// Sync the provider configuration to openclaw.json so Gateway knows about it
try {
await syncUpdatedProviderToRuntime(nextConfig, apiKey, gatewayManager);
} catch (err) {
console.warn('Failed to sync openclaw config after provider update:', err);
}
await syncUpdatedProviderToRuntime(nextConfig, apiKey, gatewayManager);
return { success: true };
} catch (error) {
@@ -967,11 +928,7 @@ function registerProviderHandlers(gatewayManager: GatewayManager): void {
// Keep OpenClaw auth-profiles.json in sync with local key storage
const provider = await providerService.getLegacyProvider(providerId);
try {
await syncDeletedProviderApiKeyToRuntime(provider, providerId);
} catch (err) {
console.warn('Failed to completely remove provider from OpenClaw:', err);
}
await syncDeletedProviderApiKeyToRuntime(provider, providerId);
return { success: true };
} catch (error) {
@@ -998,11 +955,7 @@ function registerProviderHandlers(gatewayManager: GatewayManager): void {
await providerService.setDefaultLegacyProvider(providerId);
// Update OpenClaw config to use this provider's default model
try {
await syncDefaultProviderToRuntime(providerId, gatewayManager);
} catch (err) {
console.warn('Failed to set OpenClaw default model:', err);
}
await syncDefaultProviderToRuntime(providerId, gatewayManager);
return { success: true };
} catch (error) {
+252
View File
@@ -0,0 +1,252 @@
import type { Session, WebContents, WebPreferences } from 'electron';
import {
WEB_BROWSER_INITIAL_URL,
WEB_BROWSER_PARTITION,
WEB_BROWSER_USER_AGENT,
normalizeWebBrowserHtmlFileUrl,
} from '../../shared/web-browser';
import { logger } from '../utils/logger';
const DENY_WINDOW_OPEN = { action: 'deny' } as const;
const INERT_LINK_CSS = `
a, area {
color: inherit !important;
cursor: inherit !important;
pointer-events: none !important;
text-decoration: none !important;
}
`;
export class WebBrowserGuestRegistry {
private guest: WebContents | null = null;
private pendingAttachment = false;
beginAttachment(): boolean {
this.dropDestroyedGuest();
if (this.pendingAttachment || this.guest) {
return false;
}
this.pendingAttachment = true;
return true;
}
completeAttachment(guest: WebContents): void {
if (!this.pendingAttachment || this.guest) {
return;
}
this.pendingAttachment = false;
this.guest = guest;
guest.once('destroyed', () => {
if (this.guest === guest) {
this.guest = null;
}
});
}
cancelAttachment(): void {
this.pendingAttachment = false;
}
current(): WebContents | null {
this.dropDestroyedGuest();
return this.guest;
}
owns(contents: WebContents | null): boolean {
return contents !== null && this.current() === contents;
}
hasLiveGuest(): boolean {
return this.current() !== null;
}
private dropDestroyedGuest(): void {
if (this.guest?.isDestroyed()) {
this.guest = null;
}
}
}
export function isExpectedWebBrowserAttachment(
params: Record<string, unknown>,
): boolean {
return params.partition === WEB_BROWSER_PARTITION
&& params.src === WEB_BROWSER_INITIAL_URL
&& params.useragent === WEB_BROWSER_USER_AGENT
&& params.allowpopups !== true
&& params.preload === '';
}
export function hardenWebBrowserPreferences(preferences: WebPreferences): void {
delete preferences.preload;
preferences.nodeIntegration = false;
preferences.nodeIntegrationInSubFrames = false;
preferences.nodeIntegrationInWorker = false;
preferences.plugins = false;
preferences.allowRunningInsecureContent = false;
preferences.contextIsolation = true;
preferences.sandbox = true;
preferences.webSecurity = true;
}
export function installWebBrowserGuestPolicy(
embedder: WebContents,
options: {
browserSession: Session;
registry: WebBrowserGuestRegistry;
},
): () => void {
const { browserSession, registry } = options;
let attachmentPending = false;
let cleanupGuestPolicy: (() => void) | null = null;
const handleWillAttach = (
event: Electron.Event,
preferences: WebPreferences,
params: Record<string, unknown>,
): void => {
if (!isExpectedWebBrowserAttachment(params)) {
logger.warn('[WebBrowser] Rejected webview attachment with unexpected identity');
event.preventDefault();
return;
}
if (!registry.beginAttachment()) {
logger.warn('[WebBrowser] Rejected additional webview attachment');
event.preventDefault();
return;
}
attachmentPending = true;
hardenWebBrowserPreferences(preferences);
};
const handleDidAttach = (_event: Electron.Event, guest: WebContents): void => {
if (!attachmentPending) {
logger.warn('[WebBrowser] Ignored attached guest without a reserved slot');
return;
}
attachmentPending = false;
if (guest.getType() !== 'webview' || guest.session !== browserSession) {
logger.warn('[WebBrowser] Rejected attached guest with unexpected type or session');
registry.cancelAttachment();
return;
}
registry.completeAttachment(guest);
if (!registry.owns(guest)) {
logger.warn('[WebBrowser] Failed to register reserved guest');
return;
}
guest.setUserAgent(WEB_BROWSER_USER_AGENT);
let committedHtmlUrl = normalizeWebBrowserHtmlFileUrl(guest.getURL());
let restoringCommittedUrl = false;
const blockPageNavigation = (
details: Electron.Event<Electron.WebContentsWillFrameNavigateEventParams>,
): void => {
logger.warn(`[WebBrowser] Blocked guest navigation to ${details.url}`);
details.preventDefault();
};
const stopInvalidProgrammaticNavigation = (
details: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
): void => {
if (!details.isMainFrame || normalizeWebBrowserHtmlFileUrl(details.url)) {
return;
}
logger.warn(`[WebBrowser] Stopped invalid programmatic navigation to ${details.url}`);
guest.stop();
};
const blockRedirect = (
details: Electron.Event<Electron.WebContentsWillRedirectEventParams>,
): void => {
logger.warn(`[WebBrowser] Blocked guest redirect to ${details.url}`);
details.preventDefault();
};
guest.setWindowOpenHandler(({ url }) => {
logger.warn(`[WebBrowser] Blocked popup target ${url}`);
return DENY_WINDOW_OPEN;
});
const makeLinksVisuallyInert = (): void => {
void guest.insertCSS(INERT_LINK_CSS, { cssOrigin: 'user' }).catch((error) => {
logger.warn('[WebBrowser] Failed to neutralize HTML links:', error);
});
};
const rememberCommittedHtml = (_event: Electron.Event, url: string): void => {
const normalizedUrl = normalizeWebBrowserHtmlFileUrl(url);
if (normalizedUrl) {
committedHtmlUrl = normalizedUrl;
}
restoringCommittedUrl = false;
};
const restoreAfterInPageNavigation = (
_event: Electron.Event,
url: string,
isMainFrame: boolean,
): void => {
if (!isMainFrame || !committedHtmlUrl || url === committedHtmlUrl || restoringCommittedUrl) {
return;
}
restoringCommittedUrl = true;
logger.warn(`[WebBrowser] Reverting blocked in-page navigation to ${url}`);
void guest.loadURL(committedHtmlUrl).catch((error) => {
restoringCommittedUrl = false;
logger.warn(`[WebBrowser] Failed to restore local HTML preview ${committedHtmlUrl}:`, error);
});
};
let cleaned = false;
const cleanup = (): void => {
if (cleaned) {
return;
}
cleaned = true;
guest.off('will-frame-navigate', blockPageNavigation);
guest.off('did-start-navigation', stopInvalidProgrammaticNavigation);
guest.off('will-redirect', blockRedirect);
guest.off('did-finish-load', makeLinksVisuallyInert);
guest.off('did-navigate', rememberCommittedHtml);
guest.off('did-navigate-in-page', restoreAfterInPageNavigation);
guest.off('destroyed', cleanup);
if (!guest.isDestroyed()) {
guest.setWindowOpenHandler(() => DENY_WINDOW_OPEN);
}
if (cleanupGuestPolicy === cleanup) {
cleanupGuestPolicy = null;
}
};
guest.on('will-frame-navigate', blockPageNavigation);
guest.on('did-start-navigation', stopInvalidProgrammaticNavigation);
guest.on('will-redirect', blockRedirect);
guest.on('did-finish-load', makeLinksVisuallyInert);
guest.on('did-navigate', rememberCommittedHtml);
guest.on('did-navigate-in-page', restoreAfterInPageNavigation);
guest.once('destroyed', cleanup);
cleanupGuestPolicy = cleanup;
};
embedder.on('will-attach-webview', handleWillAttach);
embedder.on('did-attach-webview', handleDidAttach);
return () => {
embedder.off('will-attach-webview', handleWillAttach);
embedder.off('did-attach-webview', handleDidAttach);
attachmentPending = false;
registry.cancelAttachment();
cleanupGuestPolicy?.();
};
}
+56
View File
@@ -0,0 +1,56 @@
import {
session,
type BrowserWindow,
type Session,
} from 'electron';
import {
WEB_BROWSER_PARTITION,
WEB_BROWSER_USER_AGENT,
normalizeWebBrowserHtmlFileUrl,
} from '@shared/web-browser';
import type { WebBrowserGuestRegistry } from './web-browser-policy';
const DOWNLOAD_OBSERVED_SESSIONS = new WeakSet<Session>();
export interface ConfigureWebBrowserSessionOptions {
registry: WebBrowserGuestRegistry;
getMainWindow: () => BrowserWindow | null;
getLanguage?: () => Promise<string | undefined>;
}
export function configureWebBrowserSession(
_options: ConfigureWebBrowserSessionOptions,
): Session {
const browserSession = session.fromPartition(WEB_BROWSER_PARTITION, { cache: true });
// Keep a deterministic identity even though this session may load only local HTML.
browserSession.setUserAgent(WEB_BROWSER_USER_AGENT);
browserSession.setPermissionCheckHandler(() => false);
browserSession.setPermissionRequestHandler((_contents, _permission, callback) => {
callback(false);
});
browserSession.setDevicePermissionHandler(() => false);
browserSession.setDisplayMediaRequestHandler((_request, callback) => {
callback({});
});
browserSession.webRequest.onBeforeRequest(
{ urls: ['file://*/*', 'http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*'] },
(details, callback) => {
const isNetworkRequest = /^(?:https?|wss?):/i.test(details.url);
const isInvalidMainDocument = details.resourceType === 'mainFrame'
&& normalizeWebBrowserHtmlFileUrl(details.url) === null;
callback({ cancel: isNetworkRequest || isInvalidMainDocument });
},
);
if (!DOWNLOAD_OBSERVED_SESSIONS.has(browserSession)) {
DOWNLOAD_OBSERVED_SESSIONS.add(browserSession);
browserSession.on('will-download', (event) => {
event.preventDefault();
});
}
return browserSession;
}
+778
View File
@@ -0,0 +1,778 @@
import type { BrowserWindow } from 'electron';
import { fork, type ChildProcess } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { Readable, Writable } from 'node:stream';
import {
ClientSideConnection,
ndJsonStream,
PROTOCOL_VERSION,
type Client,
type ContentBlock,
type RequestPermissionRequest,
type RequestPermissionResponse,
type SessionNotification,
} from '@agentclientprotocol/sdk';
import { HOST_EVENT_CHANNELS } from '@shared/host-events/contract';
import type {
AcpChatCancelPayload,
AcpChatLoadPayload,
AcpChatOperationResult,
AcpChatPromptPayload,
AcpChatRespondPermissionPayload,
AcpPermissionRequestEnvelope,
AcpSessionUpdateEnvelope,
} from '@shared/acp-chat/types';
import { getOpenClawEmbeddedForkSpec } from '../utils/openclaw-cli';
import {
approvePendingLocalDeviceRequests,
type GatewayPairingRpcClient,
} from '../utils/control-ui-device-pairing';
import { logger } from '../utils/logger';
import { recordAcpTrace } from './acp-trace';
import { AcpSessionAccessRegistry, type AcpSessionAccessContext } from './acp-session-access-registry';
import { expandPath } from '../utils/paths';
import { getSetting } from '../utils/store';
type AcpConnection = Pick<ClientSideConnection, 'initialize' | 'newSession' | 'loadSession' | 'prompt' | 'cancel'>;
type MainWindowLike = {
webContents: Pick<BrowserWindow['webContents'], 'send'>;
};
type PermissionWaiter = {
sessionKey: string;
generation: number;
resolve: (response: RequestPermissionResponse) => void;
};
type AcpSessionLoadBatch = {
sessionKey: string;
generation: number;
sessionUpdates: Array<{
acpSessionId: string;
envelope: AcpSessionUpdateEnvelope;
}>;
};
type AcpLivePromptContext = {
sessionKey: string;
acpSessionId: string;
generation: number;
accessGrant: AcpSessionAccessContext;
};
type AcpChildProcess = ChildProcess & {
stdin: NonNullable<ChildProcess['stdin']>;
stdout: NonNullable<ChildProcess['stdout']>;
stderr: NonNullable<ChildProcess['stderr']>;
};
function ok(generation?: number, sessionUpdates?: AcpSessionUpdateEnvelope[]): AcpChatOperationResult {
return {
success: true,
...(generation != null ? { generation } : {}),
...(sessionUpdates?.length ? { sessionUpdates } : {}),
};
}
function fail(error: unknown): AcpChatOperationResult {
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
function cancelledPermissionResponse(): RequestPermissionResponse {
return { outcome: { outcome: 'cancelled' } };
}
function isValidSessionKey(value: unknown): value is string {
return typeof value === 'string' && value.startsWith('agent:') && value.length > 'agent:'.length;
}
function sessionUpdateType(notification: SessionNotification): string | undefined {
const update = (notification as { update?: { sessionUpdate?: unknown } }).update;
return typeof update?.sessionUpdate === 'string' ? update.sessionUpdate : undefined;
}
// OpenClaw can emit clack/doctor diagnostics to stdout during ACP startup.
// Keep those lines away from the SDK's strict NDJSON parser.
// Upstream fixed this in https://github.com/openclaw/openclaw/pull/89997 .
function filterAcpStdoutDiagnostics(output: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {
const decoder = new TextDecoder();
const encoder = new TextEncoder();
return new ReadableStream<Uint8Array>({
async start(controller) {
const reader = output.getReader();
let buffered = '';
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
if (!value) continue;
buffered += decoder.decode(value, { stream: true });
const lines = buffered.split('\n');
buffered = lines.pop() ?? '';
for (const line of lines) {
const trimmedLine = line.trim();
if (!trimmedLine) continue;
if (trimmedLine.startsWith('{')) {
controller.enqueue(encoder.encode(`${line}\n`));
} else {
logger.info(`[acp-chat] [stdout] ${line}`);
}
}
}
} finally {
reader.releaseLock();
controller.close();
}
},
});
}
export class AcpChatService {
private child: AcpChildProcess | null = null;
private connection: AcpConnection | null;
private initializing: Promise<AcpConnection> | null = null;
private initialized = false;
private generation = 0;
private generationSeq = 0;
private activeSessionKey: string | null = null;
private activeAcpSessionId: string | null = null;
private loadedSessionKey: string | null = null;
private loadedAcpSessionId: string | null = null;
private historicalSessionKey: string | null = null;
private historicalGeneration: number | null = null;
private permissionsEnabled = false;
private loadQueue: Promise<void> | null = null;
private activeLoadBatch: AcpSessionLoadBatch | null = null;
private readonly livePrompts = new Map<string, AcpLivePromptContext>();
private permissionSeq = 0;
private readonly permissionWaiters = new Map<string, PermissionWaiter>();
readonly client: Client;
constructor(
private readonly mainWindow: MainWindowLike,
private readonly accessRegistry: AcpSessionAccessRegistry,
injectedConnection?: AcpConnection,
private readonly gateway?: GatewayPairingRpcClient,
) {
this.connection = injectedConnection ?? null;
this.client = {
sessionUpdate: async (notification) => this.emitSessionUpdate(notification),
requestPermission: async (request) => this.requestPermission(request),
};
}
private trace(
event: string,
input: { direction?: string; sessionKey?: string | null; generation?: number; details?: unknown } = {},
): void {
try {
const sessionKey = input.sessionKey === null
? undefined
: input.sessionKey ?? this.activeSessionKey ?? undefined;
const generation = input.generation ?? (this.generation > 0 ? this.generation : undefined);
recordAcpTrace({
source: 'main',
event,
...(input.direction ? { direction: input.direction } : {}),
...(sessionKey ? { sessionKey } : {}),
...(generation != null ? { generation } : {}),
...(input.details !== undefined ? { details: input.details } : {}),
});
} catch (error) {
logger.warn(`[acp-chat] trace failed: ${String(error)}`);
}
}
loadSession(payload: AcpChatLoadPayload): Promise<AcpChatOperationResult> {
const previousLoad = this.loadQueue;
let releaseLoad!: () => void;
const currentLoad = new Promise<void>((resolve) => {
releaseLoad = resolve;
});
this.loadQueue = currentLoad;
const run = async () => {
if (previousLoad) await previousLoad;
try {
return await this.performLoadSession(payload);
} finally {
releaseLoad();
if (this.loadQueue === currentLoad) this.loadQueue = null;
}
};
return run();
}
private async performLoadSession(payload: AcpChatLoadPayload): Promise<AcpChatOperationResult> {
if (!isValidSessionKey(payload.sessionKey) || !payload.workspaceRoot || !payload.cwd) {
return fail('Invalid ACP session load payload');
}
const previousPermissionsEnabled = this.permissionsEnabled;
this.permissionsEnabled = false;
this.trace('session/load:start', {
sessionKey: payload.sessionKey,
details: { createIfMissing: !!payload.createIfMissing, cwdPresent: Boolean(payload.cwd) },
});
let previousSessionKey = this.activeSessionKey;
let previousAcpSessionId = this.activeAcpSessionId;
let previousLoadedSessionKey = this.loadedSessionKey;
let previousLoadedAcpSessionId = this.loadedAcpSessionId;
let previousHistoricalSessionKey = this.historicalSessionKey;
let previousHistoricalGeneration = this.historicalGeneration;
let previousGeneration = this.generation;
let nextGeneration = this.generationSeq + 1;
let stateAdvanced = false;
let loadBatch: AcpSessionLoadBatch | null = null;
let previousAccessGrant: AcpSessionAccessContext | null = null;
try {
const connection = await this.ensureConnection();
const livePrompt = this.livePrompts.get(payload.sessionKey);
if (livePrompt) {
const preparedAccessGrant = await this.accessRegistry.prepareGrant({
sessionKey: payload.sessionKey,
generation: livePrompt.generation,
workspaceRoot: payload.workspaceRoot,
executionCwd: payload.cwd,
});
if (
preparedAccessGrant.workspaceRoot !== livePrompt.accessGrant.workspaceRoot
|| preparedAccessGrant.executionCwd !== livePrompt.accessGrant.executionCwd
) {
throw new Error('Cannot change workspace while an ACP prompt is active');
}
this.generation = livePrompt.generation;
this.activeSessionKey = livePrompt.sessionKey;
this.activeAcpSessionId = livePrompt.acpSessionId;
this.loadedSessionKey = livePrompt.sessionKey;
this.loadedAcpSessionId = livePrompt.acpSessionId;
this.historicalSessionKey = null;
this.historicalGeneration = null;
this.permissionsEnabled = true;
this.accessRegistry.commitGrant(livePrompt.accessGrant);
this.trace('session/load:resumed-active-prompt', {
sessionKey: livePrompt.sessionKey,
generation: livePrompt.generation,
details: { acpSessionId: livePrompt.acpSessionId },
});
return {
success: true,
generation: livePrompt.generation,
resumedActivePrompt: true,
};
}
previousSessionKey = this.activeSessionKey;
previousAcpSessionId = this.activeAcpSessionId;
previousLoadedSessionKey = this.loadedSessionKey;
previousLoadedAcpSessionId = this.loadedAcpSessionId;
previousHistoricalSessionKey = this.historicalSessionKey;
previousHistoricalGeneration = this.historicalGeneration;
previousGeneration = this.generation;
nextGeneration = this.generationSeq + 1;
previousAccessGrant = this.accessRegistry.snapshot();
const preparedAccessGrant = await this.accessRegistry.prepareGrant({
sessionKey: payload.sessionKey,
generation: nextGeneration,
workspaceRoot: payload.workspaceRoot,
executionCwd: payload.cwd,
});
this.generation = nextGeneration;
this.activeSessionKey = payload.sessionKey;
this.activeAcpSessionId = payload.createIfMissing ? null : payload.sessionKey;
this.loadedSessionKey = null;
this.loadedAcpSessionId = null;
this.historicalSessionKey = payload.createIfMissing ? null : payload.sessionKey;
this.historicalGeneration = payload.createIfMissing ? null : nextGeneration;
loadBatch = {
sessionKey: payload.sessionKey,
generation: nextGeneration,
sessionUpdates: [],
};
this.activeLoadBatch = loadBatch;
stateAdvanced = true;
if (previousSessionKey && !this.livePrompts.has(previousSessionKey)) {
this.resolvePermissionWaitersForSession(previousSessionKey, cancelledPermissionResponse());
}
let acpSessionId = payload.sessionKey;
if (payload.createIfMissing) {
const created = await connection.newSession({
cwd: preparedAccessGrant.executionCwd,
mcpServers: [],
_meta: { sessionKey: payload.sessionKey, prefixCwd: true },
});
acpSessionId = created.sessionId;
} else {
await connection.loadSession({
sessionId: payload.sessionKey,
cwd: preparedAccessGrant.executionCwd,
mcpServers: [],
});
}
this.activeAcpSessionId = acpSessionId;
this.loadedSessionKey = payload.sessionKey;
this.loadedAcpSessionId = acpSessionId;
this.generationSeq = nextGeneration;
this.accessRegistry.commitGrant(preparedAccessGrant);
this.trace('session/load:success', {
sessionKey: payload.sessionKey,
generation: nextGeneration,
details: { createIfMissing: !!payload.createIfMissing, acpSessionId },
});
if (this.activeLoadBatch === loadBatch) this.activeLoadBatch = null;
return ok(
nextGeneration,
loadBatch.sessionUpdates
.filter((entry) => entry.acpSessionId === acpSessionId)
.map((entry) => entry.envelope),
);
} catch (error) {
if (this.activeLoadBatch === loadBatch) this.activeLoadBatch = null;
this.resolvePermissionWaitersForSession(payload.sessionKey, cancelledPermissionResponse());
if (
stateAdvanced
&& this.activeSessionKey === payload.sessionKey
&& this.generation === nextGeneration
) {
this.generation = previousGeneration;
this.activeSessionKey = previousSessionKey;
this.activeAcpSessionId = previousAcpSessionId;
this.loadedSessionKey = previousLoadedSessionKey;
this.loadedAcpSessionId = previousLoadedAcpSessionId;
this.historicalSessionKey = previousHistoricalSessionKey;
this.historicalGeneration = previousHistoricalGeneration;
this.permissionsEnabled = previousPermissionsEnabled;
this.accessRegistry.restore(previousAccessGrant);
}
logger.error(`[acp-chat] loadSession failed: ${String(error)}`);
this.trace('session/load:failed', {
sessionKey: payload.sessionKey,
generation: previousGeneration,
details: { error: error instanceof Error ? error.message : String(error) },
});
return fail(error);
}
}
async sendPrompt(payload: AcpChatPromptPayload): Promise<AcpChatOperationResult> {
if (!isValidSessionKey(payload.sessionKey) || !payload.cwd) return fail('Invalid ACP prompt payload');
if (!this.activeSessionKey) return fail('No active ACP session');
if (payload.sessionKey !== this.activeSessionKey) return fail('ACP prompt session is not active');
if (this.loadedSessionKey !== payload.sessionKey || !this.loadedAcpSessionId) return fail('ACP session is not loaded');
if (this.livePrompts.has(payload.sessionKey)) return fail('ACP prompt is already active');
const generation = this.generation;
const acpSessionId = this.loadedAcpSessionId;
const accessGrant = this.accessRegistry.get(payload.sessionKey, generation);
if (!accessGrant) return fail('ACP session access grant is not active');
const promptContext: AcpLivePromptContext = {
sessionKey: payload.sessionKey,
acpSessionId,
generation,
accessGrant,
};
this.livePrompts.set(payload.sessionKey, promptContext);
try {
const promptCwd = payload.cwd === accessGrant.executionCwd
? payload.cwd
: await import('node:fs/promises')
.then((fsP) => fsP.realpath(expandPath(payload.cwd)))
.catch(() => null);
if (promptCwd !== accessGrant.executionCwd) {
return fail('ACP prompt cwd does not match the registered execution cwd');
}
this.trace('session/prompt:start', {
sessionKey: payload.sessionKey,
generation,
details: { messageLength: payload.message?.length ?? 0, mediaCount: payload.media?.length ?? 0 },
});
const connection = await this.ensureConnection();
const prompt = await this.buildPromptBlocks(payload);
if (this.historicalSessionKey === payload.sessionKey) {
this.historicalSessionKey = null;
this.historicalGeneration = null;
}
this.permissionsEnabled = true;
const messageId = payload.messageId ?? randomUUID();
const isSlashCommand = payload.message?.trimStart().startsWith('/') === true;
await connection.prompt({
sessionId: acpSessionId,
prompt,
// ACP 1.1 removed messageId from the PromptRequest wire shape. Keep
// ClawX correlation metadata in the protocol extension envelope.
// OpenClaw must receive slash commands without its textual cwd prefix
// so the Gateway can classify and fold command replies into chat final.
_meta: { sessionKey: payload.sessionKey, prefixCwd: !isSlashCommand, messageId },
});
this.trace('session/prompt:success', {
sessionKey: payload.sessionKey,
generation,
details: { blockCount: prompt.length, acpSessionId },
});
return ok(generation);
} catch (error) {
logger.error(`[acp-chat] prompt failed: ${String(error)}`);
this.trace('session/prompt:failed', {
sessionKey: payload.sessionKey,
details: { error: error instanceof Error ? error.message : String(error) },
});
return fail(error);
} finally {
if (this.livePrompts.get(payload.sessionKey) === promptContext) {
this.livePrompts.delete(payload.sessionKey);
this.resolvePermissionWaitersForSession(payload.sessionKey, cancelledPermissionResponse());
}
this.permissionsEnabled = this.activeSessionKey != null && this.livePrompts.has(this.activeSessionKey);
}
}
async cancelSession(payload: AcpChatCancelPayload): Promise<AcpChatOperationResult> {
if (!isValidSessionKey(payload.sessionKey)) return fail('Invalid ACP cancel payload');
if (payload.sessionKey !== this.activeSessionKey || !this.loadedAcpSessionId) return fail('ACP session is not loaded');
try {
this.trace('session/cancel:start', { sessionKey: payload.sessionKey });
const connection = await this.ensureConnection();
await connection.cancel({ sessionId: this.loadedAcpSessionId });
this.permissionsEnabled = false;
this.resolvePermissionWaitersForSession(payload.sessionKey, cancelledPermissionResponse());
this.trace('session/cancel:success', { sessionKey: payload.sessionKey });
return ok(this.generation);
} catch (error) {
logger.error(`[acp-chat] cancel failed: ${String(error)}`);
this.trace('session/cancel:failed', {
sessionKey: payload.sessionKey,
details: { error: error instanceof Error ? error.message : String(error) },
});
return fail(error);
}
}
async respondPermission(payload: AcpChatRespondPermissionPayload): Promise<AcpChatOperationResult> {
const waiter = this.permissionWaiters.get(payload.requestId);
if (!waiter || waiter.sessionKey !== payload.sessionKey) return fail('Unknown ACP permission request');
waiter.resolve({ outcome: payload.outcome });
this.permissionWaiters.delete(payload.requestId);
this.trace('permission/responded', {
sessionKey: payload.sessionKey,
details: { requestId: payload.requestId, outcome: payload.outcome.outcome },
});
return ok(waiter.generation);
}
private async ensureConnection(): Promise<AcpConnection> {
if (this.connection && this.initialized) return this.connection;
if (this.initializing) return this.initializing;
this.initializing = this.initializeConnection();
try {
return await this.initializing;
} finally {
this.initializing = null;
}
}
private async initializeConnection(): Promise<AcpConnection> {
await this.approveLocalDeviceRequests();
for (let attempt = 1; attempt <= 2; attempt++) {
try {
return await this.initializeConnectionOnce(attempt);
} catch (error) {
if (attempt >= 2) throw error;
logger.info(
`[acp-chat] ACP connect failed on attempt ${attempt}; auto-approving local device requests and retrying: ${
error instanceof Error ? error.message : String(error)
}`,
);
await this.approveLocalDeviceRequests();
}
}
throw new Error('ACP connection failed');
}
private async initializeConnectionOnce(attempt: number): Promise<AcpConnection> {
if (!this.connection) this.connection = await this.spawnConnection();
const connection = this.connection;
const child = this.child;
this.trace('connection/initialize:start', { details: { attempt } });
const initOutcome = await Promise.race([
connection.initialize({
protocolVersion: PROTOCOL_VERSION,
clientCapabilities: {},
}).then((result) => ({ kind: 'initialized' as const, result })),
this.waitForChildExit(child).then((exitCode) => ({ kind: 'exited' as const, exitCode })),
]);
if (initOutcome.kind === 'exited') {
if (child) this.dropConnectionForChild(child);
throw new Error(`ACP process exited with code ${String(initOutcome.exitCode)}`);
}
const result = initOutcome.result;
if (this.connection !== connection) {
throw new Error('ACP connection closed during initialization');
}
if (!result.agentCapabilities?.loadSession) {
this.trace('connection/initialize:failed', { details: { reason: 'missing-loadSession-capability' } });
throw new Error('ACP agent does not support session/load');
}
this.initialized = true;
this.trace('connection/initialize:success', { details: { protocolVersion: PROTOCOL_VERSION, attempt } });
return connection;
}
private async approveLocalDeviceRequests(): Promise<void> {
if (!this.gateway) return;
try {
await approvePendingLocalDeviceRequests(this.gateway);
} catch (error) {
logger.debug(`[acp-chat] Local device auto-approve skipped: ${String(error)}`);
}
}
private waitForChildExit(child: AcpChildProcess | null): Promise<number | null> {
if (!child) return Promise.resolve(null);
if (child.exitCode !== null) return Promise.resolve(child.exitCode);
if (child.signalCode) return Promise.resolve(child.exitCode);
return new Promise((resolve) => {
const onExit = (code: number | null) => {
child.off('exit', onExit);
resolve(code);
};
child.on('exit', onExit);
});
}
private async spawnConnection(): Promise<ClientSideConnection> {
const gatewayToken = await getSetting('gatewayToken');
const spec = getOpenClawEmbeddedForkSpec(['acp']);
const forked = fork(spec.modulePath, spec.args, {
...spec.options,
// ACP is a local Gateway client, so it must use the token that started
// this ClawX-owned Gateway instead of relying on config-file fallback.
env: { ...spec.options.env, OPENCLAW_GATEWAY_TOKEN: gatewayToken },
});
if (!forked.stdin || !forked.stdout || !forked.stderr) {
forked.kill();
throw new Error('ACP process did not expose stdio pipes');
}
this.child = forked as AcpChildProcess;
const child = this.child;
child.stderr.on('data', (chunk) => {
const message = String(chunk).trimEnd();
if (message) logger.info(`[acp-chat] ${message}`);
});
child.on('error', (error) => {
logger.error(`[acp-chat] ACP process error: ${String(error)}`);
this.dropConnectionForChild(child);
});
child.on('exit', (code) => {
logger.info(`[acp-chat] ACP process exited with code ${String(code)}`);
this.dropConnectionForChild(child);
});
const input = Writable.toWeb(child.stdin) as WritableStream<Uint8Array>;
const output = filterAcpStdoutDiagnostics(Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>);
const stream = ndJsonStream(input, output);
return new ClientSideConnection(() => this.client, stream);
}
private dropConnectionForChild(child: AcpChildProcess): void {
if (this.child !== child) return;
this.trace('connection/dropped', { details: { pendingPermissionCount: this.permissionWaiters.size } });
this.resolveAllPermissionWaiters(cancelledPermissionResponse());
this.initialized = false;
this.initializing = null;
this.connection = null;
this.child = null;
this.loadedSessionKey = null;
this.loadedAcpSessionId = null;
this.historicalSessionKey = null;
this.historicalGeneration = null;
this.permissionsEnabled = false;
this.livePrompts.clear();
}
private emitSessionUpdate(notification: SessionNotification): void {
const acpSessionId = notification.sessionId;
const livePrompt = [...this.livePrompts.values()].find((context) => context.acpSessionId === acpSessionId);
const sessionKey = livePrompt?.sessionKey ?? this.activeSessionKey;
const generation = livePrompt?.generation ?? this.generation;
const updateType = sessionUpdateType(notification);
this.trace('session-update:received', {
direction: 'upstream',
sessionKey: sessionKey ?? null,
details: { acpSessionId, updateType },
});
if (!sessionKey) {
this.trace('session-update:ignored', {
direction: 'upstream',
sessionKey: null,
details: { reason: 'no-active-session', acpSessionId, updateType },
});
return;
}
if (!livePrompt && this.activeAcpSessionId && acpSessionId !== this.activeAcpSessionId) {
this.trace('session-update:ignored', {
direction: 'upstream',
sessionKey,
details: { reason: 'session-mismatch', acpSessionId, activeAcpSessionId: this.activeAcpSessionId, updateType },
});
return;
}
const envelope: AcpSessionUpdateEnvelope = {
sessionKey,
generation,
...(!livePrompt && this.historicalSessionKey === sessionKey && this.historicalGeneration === generation
? { historical: true }
: {}),
notification: { ...notification, sessionId: sessionKey },
};
const loadBatch = this.activeLoadBatch;
if (loadBatch?.sessionKey === sessionKey && loadBatch.generation === generation) {
loadBatch.sessionUpdates.push({ acpSessionId, envelope });
this.trace('session-update:buffered', {
direction: 'downstream',
sessionKey,
details: { acpSessionId, updateType, historical: !!envelope.historical },
});
return;
}
this.mainWindow.webContents.send(HOST_EVENT_CHANNELS.chat.acpSessionUpdate, envelope);
this.trace('session-update:forwarded', {
direction: 'downstream',
sessionKey,
details: { acpSessionId, updateType, historical: !!envelope.historical },
});
}
private requestPermission(request: RequestPermissionRequest): Promise<RequestPermissionResponse> {
const acpSessionId = request.sessionId;
const livePrompt = [...this.livePrompts.values()].find((context) => context.acpSessionId === acpSessionId);
const sessionKey = livePrompt?.sessionKey ?? this.activeSessionKey;
const generation = livePrompt?.generation ?? this.generation;
if (!livePrompt && !this.permissionsEnabled) {
this.trace('permission:ignored', {
direction: 'upstream',
sessionKey: sessionKey ?? null,
details: { reason: 'no-active-prompt', acpSessionId },
});
return Promise.resolve(cancelledPermissionResponse());
}
if (this.activeLoadBatch && !livePrompt) {
this.trace('permission:ignored', {
direction: 'upstream',
sessionKey: sessionKey ?? null,
details: { reason: 'session-loading', acpSessionId },
});
return Promise.resolve(cancelledPermissionResponse());
}
if (!sessionKey || (!livePrompt && this.activeAcpSessionId && acpSessionId !== this.activeAcpSessionId)) {
this.trace('permission:ignored', {
direction: 'upstream',
sessionKey: sessionKey ?? null,
details: {
reason: !sessionKey ? 'no-active-session' : 'session-mismatch',
acpSessionId,
activeAcpSessionId: this.activeAcpSessionId,
},
});
return Promise.resolve(cancelledPermissionResponse());
}
const requestId = `acp-permission-${Date.now()}-${this.permissionSeq += 1}`;
const envelope: AcpPermissionRequestEnvelope = {
sessionKey,
generation,
requestId,
request: { ...request, sessionId: sessionKey },
};
this.mainWindow.webContents.send(HOST_EVENT_CHANNELS.chat.acpPermissionRequest, envelope);
this.trace('permission:forwarded', {
direction: 'downstream',
sessionKey,
details: { requestId, acpSessionId, optionCount: request.options.length },
});
return new Promise((resolve) => {
this.permissionWaiters.set(requestId, { sessionKey, generation, resolve });
});
}
private resolvePermissionWaitersForSession(sessionKey: string, response: RequestPermissionResponse): void {
for (const [requestId, waiter] of this.permissionWaiters) {
if (waiter.sessionKey !== sessionKey) continue;
waiter.resolve(response);
this.permissionWaiters.delete(requestId);
}
}
private resolveAllPermissionWaiters(response: RequestPermissionResponse): void {
for (const [requestId, waiter] of this.permissionWaiters) {
waiter.resolve(response);
this.permissionWaiters.delete(requestId);
}
}
private async buildPromptBlocks(payload: AcpChatPromptPayload): Promise<ContentBlock[]> {
const blocks: ContentBlock[] = [];
const text = payload.message?.trim();
if (text) blocks.push({ type: 'text', text });
const media = payload.media ?? [];
if (media.length > 0) {
const fsP = await import('node:fs/promises');
for (const item of media) {
const mimeType = item.mimeType || 'application/octet-stream';
if (mimeType.startsWith('image/')) {
const data = await fsP.readFile(item.filePath, 'base64');
blocks.push({
type: 'image',
data,
mimeType,
uri: item.filePath,
_meta: {
clawx: {
stagingId: item.stagingId,
...(item.fileName ? { fileName: item.fileName } : {}),
},
},
});
} else {
blocks.push({
type: 'resource_link',
uri: item.filePath,
name: item.fileName ?? item.filePath,
mimeType: item.mimeType,
_meta: {
clawx: {
stagingId: item.stagingId,
},
},
});
}
}
}
if (blocks.length === 0) blocks.push({ type: 'text', text: '' });
return blocks;
}
}
export function createAcpChatService(
mainWindow: MainWindowLike,
accessRegistry: AcpSessionAccessRegistry,
gateway?: GatewayPairingRpcClient,
): AcpChatService {
return new AcpChatService(mainWindow, accessRegistry, undefined, gateway);
}
@@ -0,0 +1,53 @@
import { realpath, stat } from 'node:fs/promises';
import { isAbsolute, relative, sep } from 'node:path';
import { expandPath } from '../utils/paths';
export type AcpSessionAccessContext = {
sessionKey: string;
generation: number;
workspaceRoot: string;
executionCwd: string;
};
async function canonicalDirectory(input: string, label: string): Promise<string> {
const canonicalPath = await realpath(expandPath(input));
const directoryStat = await stat(canonicalPath);
if (!directoryStat.isDirectory()) throw new Error(`${label} must be a directory`);
return canonicalPath;
}
function isInside(child: string, parent: string): boolean {
const relativePath = relative(parent, child);
return relativePath === ''
|| (!isAbsolute(relativePath) && relativePath !== '..' && !relativePath.startsWith(`..${sep}`));
}
export class AcpSessionAccessRegistry {
private activeGrant: AcpSessionAccessContext | null = null;
async prepareGrant(input: AcpSessionAccessContext): Promise<AcpSessionAccessContext> {
const workspaceRoot = await canonicalDirectory(input.workspaceRoot, 'ACP workspace root');
const executionCwd = await canonicalDirectory(input.executionCwd, 'ACP execution cwd');
if (!isInside(executionCwd, workspaceRoot)) {
throw new Error('ACP execution cwd must be inside the workspace root');
}
return { ...input, workspaceRoot, executionCwd };
}
snapshot(): AcpSessionAccessContext | null {
return this.activeGrant ? { ...this.activeGrant } : null;
}
commitGrant(context: AcpSessionAccessContext): void {
this.activeGrant = { ...context };
}
restore(snapshot: AcpSessionAccessContext | null): void {
this.activeGrant = snapshot ? { ...snapshot } : null;
}
get(sessionKey: string, generation: number): AcpSessionAccessContext | null {
if (this.activeGrant?.sessionKey !== sessionKey || this.activeGrant.generation !== generation) return null;
return { ...this.activeGrant };
}
}
+137
View File
@@ -0,0 +1,137 @@
import type {
AcpTraceEntry,
AcpTraceRecordPayload,
AcpTraceSnapshot,
AttachmentAccessError,
} from '@shared/host-api/contract';
import { isRecord } from './payload-utils';
type AcpTraceRecordInput = Omit<AcpTraceEntry, 'seq' | 'timestamp'>;
const MAX_ACP_TRACE_ENTRIES = 500;
const MAX_STRING_LENGTH = 300;
const SENSITIVE_KEY_RE = /(authorization|api[_-]?key|token|secret|password|bearer)/i;
const OPENCLAW_MEDIA_DETAIL_KEYS = new Set([
'source',
'reason',
'candidateCount',
'matchedCount',
'rejectedCount',
'attachmentCount',
'imageCount',
'missingCount',
'previewCount',
'evidenceHash',
'identityHash',
'operationId',
'latestGeneration',
'error',
]);
let sequence = 0;
let entries: AcpTraceEntry[] = [];
function sanitize(value: unknown, depth = 0): unknown {
if (value == null || typeof value === 'boolean' || typeof value === 'number') return value;
if (typeof value === 'string') {
if (/bearer\s+\S+/i.test(value) || /^sk-[A-Za-z0-9_-]{8,}/.test(value)) return '[redacted]';
if (value.length <= MAX_STRING_LENGTH) return value;
return `${value.slice(0, MAX_STRING_LENGTH)}...[truncated ${value.length - MAX_STRING_LENGTH} chars]`;
}
if (depth >= 4) return '[max-depth]';
if (Array.isArray(value)) {
const items = value.slice(0, 20).map((item) => sanitize(item, depth + 1));
return value.length > 20 ? { type: 'array', length: value.length, items } : items;
}
if (!isRecord(value)) return String(value);
const output: Record<string, unknown> = {};
for (const [key, nested] of Object.entries(value)) {
output[key] = SENSITIVE_KEY_RE.test(key) ? '[redacted]' : sanitize(nested, depth + 1);
}
return output;
}
function optionalString(value: unknown, maxLength = 120): string | undefined {
return typeof value === 'string' && value.trim() ? value.trim().slice(0, maxLength) : undefined;
}
export function recordAcpTrace(input: AcpTraceRecordInput): AcpTraceEntry {
const entry: AcpTraceEntry = {
seq: sequence += 1,
timestamp: new Date().toISOString(),
source: input.source,
event: input.event.slice(0, 120),
...(input.direction ? { direction: input.direction } : {}),
...(input.sessionKey ? { sessionKey: input.sessionKey } : {}),
...(typeof input.generation === 'number' ? { generation: input.generation } : {}),
...(input.details !== undefined ? { details: sanitize(input.details) } : {}),
};
entries.push(entry);
if (entries.length > MAX_ACP_TRACE_ENTRIES) entries = entries.slice(-MAX_ACP_TRACE_ENTRIES);
return entry;
}
export function getAcpTraceSnapshot(): AcpTraceSnapshot {
return {
capturedAt: Date.now(),
maxSize: MAX_ACP_TRACE_ENTRIES,
size: entries.length,
entries: entries.map((entry) => ({ ...entry })),
};
}
export function normalizeRendererAcpTracePayload(payload: unknown): AcpTraceRecordInput | null {
if (!isRecord(payload)) return null;
const event = optionalString(payload.event);
if (!event) return null;
const sessionKey = optionalString(payload.sessionKey, 200);
const direction = optionalString(payload.direction, 80) ?? 'projection';
const generation = typeof payload.generation === 'number' && Number.isFinite(payload.generation)
? payload.generation
: undefined;
const details = event.startsWith('openclaw-media:') && isRecord(payload.details)
? Object.fromEntries(Object.entries(payload.details).filter(([key]) => OPENCLAW_MEDIA_DETAIL_KEYS.has(key)))
: payload.details;
return {
source: 'renderer',
event,
direction,
...(sessionKey ? { sessionKey } : {}),
...(generation != null ? { generation } : {}),
...(details !== undefined ? { details } : {}),
};
}
export function recordRendererAcpTrace(payload: AcpTraceRecordPayload): { success: boolean; error?: string } {
const normalized = normalizeRendererAcpTracePayload(payload);
if (!normalized) return { success: false, error: 'Invalid ACP trace payload' };
recordAcpTrace(normalized);
return { success: true };
}
export function recordAttachmentOpenTrace(input: {
ok: boolean;
reason: AttachmentAccessError | 'success';
sourceKind: 'local' | 'remote' | 'invalid';
sessionKey: string;
generation: number;
identity: string;
}): AcpTraceEntry {
return recordAcpTrace({
source: 'main',
event: `attachment/open:${input.ok ? 'success' : 'failure'}`,
direction: 'open',
sessionKey: input.sessionKey,
generation: input.generation,
details: {
reason: input.reason,
sourceKind: input.sourceKind,
identity: input.identity.slice(0, 64),
},
});
}
export function clearAcpTraceForTests(): void {
sequence = 0;
entries = [];
}
+3 -29
View File
@@ -27,24 +27,7 @@ function requireString(payload: unknown, key: string): string {
return payload[key].trim();
}
function scheduleGatewayReload(ctx: AgentsApiContext, reason: string): void {
if (ctx.gatewayManager.getStatus().state !== 'stopped') {
ctx.gatewayManager.debouncedReload();
return;
}
void reason;
}
async function restartGatewayForAgentDeletion(ctx: AgentsApiContext): Promise<void> {
try {
await ctx.gatewayManager.restart();
console.log('[agents] Gateway restart completed after agent deletion');
} catch (err) {
console.warn('[agents] Gateway restart after agent deletion failed:', err);
}
}
export function createAgentsApi(ctx: AgentsApiContext): CompleteHostServiceRegistry['agents'] {
export function createAgentsApi(_ctx: AgentsApiContext): CompleteHostServiceRegistry['agents'] {
return {
list: async () => ({ success: true, ...(await listAgentsSnapshot()) }),
create: async (payload) => {
@@ -54,7 +37,6 @@ export function createAgentsApi(ctx: AgentsApiContext): CompleteHostServiceRegis
syncAllProviderAuthToRuntime().catch((err) => {
console.warn('[agents] Failed to sync provider auth after agent creation:', err);
});
scheduleGatewayReload(ctx, 'create-agent');
void ensureClawXContext({ waitForAllConfiguredWorkspaces: true }).catch((err) => {
console.warn('[agents] Failed to ensure ClawX context after agent creation:', err);
});
@@ -64,25 +46,19 @@ export function createAgentsApi(ctx: AgentsApiContext): CompleteHostServiceRegis
const agentId = requireString(payload, 'id');
const name = requireString(payload, 'name');
const snapshot = await updateAgentName(agentId, name);
scheduleGatewayReload(ctx, 'update-agent');
return { success: true, ...snapshot };
},
updateModel: async (payload) => {
const agentId = requireString(payload, 'id');
const modelRef = isRecord(payload) && typeof payload.modelRef === 'string' ? payload.modelRef : null;
const snapshot = await updateAgentModel(agentId, modelRef);
try {
await syncAllProviderAuthToRuntime();
await syncAgentModelOverrideToRuntime(agentId);
} catch (syncError) {
console.warn('[agents] Failed to sync runtime after updating agent model:', syncError);
}
await syncAllProviderAuthToRuntime();
await syncAgentModelOverrideToRuntime(agentId);
return { success: true, ...snapshot };
},
delete: async (payload) => {
const agentId = requireString(payload, 'id');
const { snapshot, removedEntry } = await deleteAgentConfig(agentId);
await restartGatewayForAgentDeletion(ctx);
await removeAgentWorkspaceDirectory(removedEntry).catch((err) => {
console.warn('[agents] Failed to remove workspace after agent deletion:', err);
});
@@ -92,7 +68,6 @@ export function createAgentsApi(ctx: AgentsApiContext): CompleteHostServiceRegis
const agentId = requireString(payload, 'id');
const channelType = requireString(payload, 'channelType');
const snapshot = await assignChannelToAgent(agentId, channelType);
scheduleGatewayReload(ctx, 'assign-channel');
return { success: true, ...snapshot };
},
removeChannel: async (payload) => {
@@ -118,7 +93,6 @@ export function createAgentsApi(ctx: AgentsApiContext): CompleteHostServiceRegis
await clearChannelBinding(channelType, accountId);
}
const snapshot = await listAgentsSnapshot();
scheduleGatewayReload(ctx, 'remove-agent-channel');
return { success: true, ...snapshot };
},
};
+903
View File
@@ -0,0 +1,903 @@
import { shell as electronShell } from 'electron';
import { createHash } from 'node:crypto';
import { constants } from 'node:fs';
import type { Stats } from 'node:fs';
import type { FileHandle } from 'node:fs/promises';
import {
basename,
extname,
isAbsolute,
join,
posix,
relative,
resolve,
sep,
win32,
} from 'node:path';
import { fileURLToPath } from 'node:url';
import type {
AttachmentAccessError,
AttachmentFileRef,
AttachmentOpenHandlersResult,
AttachmentSourceRef,
OpenAttachmentResult,
OpenAttachmentWithPayload,
ReadAttachmentBinaryPayload,
ReadAttachmentBinaryResult,
ReadAttachmentTextResult,
ResolveAttachmentPayload,
ResolveAttachmentResult,
} from '@shared/host-api/contract';
import {
FILE_PREVIEW_MAX_BINARY_BYTES,
FILE_PREVIEW_MAX_TEXT_BYTES,
} from '@shared/file-preview/limits';
import type { AcpSessionAccessRegistry } from './acp-session-access-registry';
import { recordAttachmentOpenTrace } from './acp-trace';
import {
HANDLER_ID_MAX_LENGTH,
type AttachmentOpenWithService,
} from './attachment-open-with';
import {
expandPath,
resolveOpenClawConfigDir,
resolveOpenClawStateDir,
} from '../utils/paths';
const MAX_REFERENCE_LENGTH = 4096;
const MAX_DISPLAY_NAME_LENGTH = 160;
const MAX_OUTGOING_RECORD_BYTES = 64 * 1024;
const SAFE_ATTACHMENT_ID = /^[A-Za-z0-9._-]+$/;
const DIRECTORY_MIME_TYPE = 'application/x-directory';
const EXT_MIME_MAP: Record<string, string> = {
'.bmp': 'image/bmp',
'.csv': 'text/csv',
'.gif': 'image/gif',
'.htm': 'text/html',
'.html': 'text/html',
'.jpeg': 'image/jpeg',
'.jpg': 'image/jpeg',
'.json': 'application/json',
'.md': 'text/markdown',
'.pdf': 'application/pdf',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.txt': 'text/plain',
'.webp': 'image/webp',
'.xls': 'application/vnd.ms-excel',
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.zip': 'application/zip',
};
type AttachmentFs = {
lstat: (path: string) => Promise<Stats>;
open: (path: string, flags: number) => Promise<FileHandle>;
realpath: (path: string) => Promise<string>;
stat: (path: string) => Promise<Stats>;
};
type AttachmentShell = {
openPath: (path: string) => Promise<string>;
openExternal: (url: string) => Promise<void>;
showItemInFolder: (path: string) => void;
};
export type AttachmentAccess = {
resolveAttachment: (payload: ResolveAttachmentPayload) => Promise<ResolveAttachmentResult>;
readAttachmentText: (ref: AttachmentFileRef) => Promise<ReadAttachmentTextResult>;
readAttachmentBinary: (payload: ReadAttachmentBinaryPayload) => Promise<ReadAttachmentBinaryResult>;
openAttachment: (ref: AttachmentSourceRef) => Promise<OpenAttachmentResult>;
listAttachmentOpenHandlers: (ref: AttachmentFileRef) => Promise<AttachmentOpenHandlersResult>;
openAttachmentWith: (payload: OpenAttachmentWithPayload) => Promise<OpenAttachmentResult>;
revealAttachment: (ref: AttachmentFileRef) => Promise<OpenAttachmentResult>;
};
type AttachmentAccessDependencies = {
sessionAccessRegistry: AcpSessionAccessRegistry;
stagedAttachments: StagedAttachmentRegistry;
stateDir?: string;
configDir?: string;
fs?: AttachmentFs;
shell?: AttachmentShell;
openWith: AttachmentOpenWithService;
};
type LocalScope = 'workspace' | 'openclaw-media' | 'staging';
type ResolvedLocal = {
kind: 'local';
entryKind: 'file' | 'directory';
canonicalPath: string;
scope: LocalScope;
mimeType: string;
size: number;
authorizationRoot?: string;
};
type ResolvedRemote = {
kind: 'remote';
normalizedUrl: string;
mimeType: string;
size: number;
};
type ResolvedTarget = ResolvedLocal | ResolvedRemote;
type PinnedDirectory = {
canonicalPath: string;
dev: number;
ino: number;
};
type ManagedAuthoritySlot = {
lexicalParent: string;
parent?: PinnedDirectory;
media?: PinnedDirectory;
pinning?: Promise<void>;
mediaPinning?: Promise<void>;
};
class AttachmentFailure extends Error {
constructor(readonly code: AttachmentAccessError) {
super(code);
}
}
export class StagedAttachmentRegistry {
private readonly files = new Map<string, { canonicalPath: string; displayPath?: string }>();
register(id: string, canonicalPath: string, displayPath?: string): void {
if (id && canonicalPath) this.files.set(id, {
canonicalPath,
...(displayPath ? { displayPath } : {}),
});
}
get(id: string): string | null {
return this.files.get(id)?.canonicalPath ?? null;
}
getDisplayPath(id: string): string | null {
return this.files.get(id)?.displayPath ?? null;
}
hasPath(canonicalPath: string): boolean {
return Array.from(this.files.values()).some((file) => isSamePath(file.canonicalPath, canonicalPath));
}
}
export function resolveClawXStagingDir(stateDir = resolveOpenClawStateDir()): string {
return join(resolve(stateDir), 'media', 'outbound', 'clawx-staging');
}
function attachmentFailure(error: unknown): AttachmentAccessError {
if (error instanceof AttachmentFailure) return error.code;
const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
if (code === 'ENOENT') return 'unavailable';
return 'operationFailed';
}
function opaqueIdentity(value: string): string {
return createHash('sha256').update(value).digest('hex');
}
function safeDisplayName(value: unknown, fallback: string): string {
const raw = typeof value === 'string' && value.trim() ? value : fallback;
const filename = posix.basename(raw.replace(/\\/gu, '/'));
const withoutControls = Array.from(filename.slice(0, MAX_DISPLAY_NAME_LENGTH * 4), (character) => {
const codePoint = character.codePointAt(0) ?? 0;
const isControl = codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
const isBidiFormatting = codePoint === 0x061c
|| codePoint === 0x200e
|| codePoint === 0x200f
|| (codePoint >= 0x202a && codePoint <= 0x202e)
|| (codePoint >= 0x2066 && codePoint <= 0x2069);
return isControl || isBidiFormatting ? ' ' : character;
}).join('');
const cleaned = withoutControls
.replace(/\s+/gu, ' ')
.trim()
.slice(0, MAX_DISPLAY_NAME_LENGTH);
return cleaned || 'attachment';
}
function decodedBasename(uri: string): string {
try {
if (/^https?:/i.test(uri)) {
const url = new URL(uri);
return decodeURIComponent(posix.basename(url.pathname)) || url.hostname;
}
if (/^file:/i.test(uri)) return basename(fileURLToPath(uri));
} catch {
// A safe generic label is returned below for malformed input.
}
return basename(uri.replace(/[?#].*$/u, '')) || 'attachment';
}
function mimeTypeForPath(path: string): string {
return EXT_MIME_MAP[extname(path).toLowerCase()] ?? 'application/octet-stream';
}
function hasTraversal(value: string): boolean {
return value.split(/[\\/]+/u).includes('..');
}
function validateReferenceSyntax(uri: unknown): asserts uri is string {
if (typeof uri !== 'string' || !uri.trim() || uri.length > MAX_REFERENCE_LENGTH || uri.includes('\0')) {
throw new AttachmentFailure('invalidReference');
}
if (uri.startsWith('\\\\') || uri.startsWith('//')) throw new AttachmentFailure('invalidReference');
if (hasTraversal(uri)) throw new AttachmentFailure('invalidReference');
if (uri.includes('%')) {
let decoded: string;
try {
decoded = decodeURIComponent(uri);
} catch {
throw new AttachmentFailure('invalidReference');
}
if (decoded.includes('\0') || hasTraversal(decoded)) throw new AttachmentFailure('invalidReference');
}
}
function isInside(child: string, parent: string): boolean {
const relativePath = relative(parent, child);
return relativePath === ''
|| (!isAbsolute(relativePath) && relativePath !== '..' && !relativePath.startsWith(`..${sep}`));
}
function isSamePath(left: string, right: string): boolean {
const resolvedLeft = resolve(left);
const resolvedRight = resolve(right);
return process.platform === 'win32'
? resolvedLeft.toLowerCase() === resolvedRight.toLowerCase()
: resolvedLeft === resolvedRight;
}
function localPathFromUri(uri: string, executionCwd: string): string {
if (/^file:/i.test(uri)) {
let url: URL;
try {
url = new URL(uri);
} catch {
throw new AttachmentFailure('invalidReference');
}
if (url.username || url.password || (url.hostname && url.hostname.toLowerCase() !== 'localhost')) {
throw new AttachmentFailure('invalidReference');
}
try {
return fileURLToPath(url);
} catch {
throw new AttachmentFailure('invalidReference');
}
}
if (/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(uri) && !win32.isAbsolute(uri)) {
throw new AttachmentFailure('invalidReference');
}
if (uri.startsWith('~')) return resolve(expandPath(uri));
if (isAbsolute(uri) || win32.isAbsolute(uri)) return resolve(uri);
return resolve(executionCwd, uri);
}
function parseOutgoingUrl(uri: string): { attachmentId: string; sessionKey: string } | null {
let url: URL;
try {
url = uri.startsWith('/') ? new URL(uri, 'http://clawx.local') : new URL(uri);
} catch {
return null;
}
const isRelativeGatewayUrl = uri.startsWith('/');
const isLocalGatewayUrl = (url.protocol === 'http:' || url.protocol === 'https:')
&& (url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]');
if (!isRelativeGatewayUrl && !isLocalGatewayUrl) return null;
if (url.username || url.password) throw new AttachmentFailure('unsafeUrl');
const segments = url.pathname.split('/');
if (segments.length !== 8
|| segments[1] !== 'api'
|| segments[2] !== 'chat'
|| segments[3] !== 'media'
|| segments[4] !== 'outgoing'
|| segments[7] !== 'full') {
return null;
}
let sessionKey: string;
let attachmentId: string;
try {
sessionKey = decodeURIComponent(segments[5]);
attachmentId = decodeURIComponent(segments[6]);
} catch {
throw new AttachmentFailure('invalidReference');
}
if (!sessionKey || !SAFE_ATTACHMENT_ID.test(attachmentId)) {
throw new AttachmentFailure('invalidReference');
}
return { attachmentId, sessionKey };
}
async function canonicalManagedMediaRoots(
stateDir: string,
configDir: string,
fs: AttachmentFs,
): Promise<string[]> {
// OpenClaw 2026.6.10 exposes only resolveStateDir()/media and resolveConfigDir()/media.
// Keep this list exact until the distributed runtime adds a real media-root setting.
const managedRoots = await Promise.all([stateDir, configDir].map(async (parentPath) => {
try {
const parent = await fs.realpath(parentPath);
if (!(await fs.stat(parent)).isDirectory()) return null;
const mediaPath = join(parentPath, 'media');
if ((await fs.lstat(mediaPath)).isSymbolicLink()) return null;
const media = await fs.realpath(mediaPath);
return (await fs.stat(media)).isDirectory() && isInside(media, parent) ? media : null;
} catch {
return null;
}
}));
return Array.from(new Set([
...managedRoots.filter((root): root is string => root !== null),
]));
}
function pinnedDirectory(path: string, stat: Stats): PinnedDirectory {
return { canonicalPath: path, dev: stat.dev, ino: stat.ino };
}
async function ensureManagedAuthority(
slot: ManagedAuthoritySlot,
fs: AttachmentFs,
): Promise<{ parent: PinnedDirectory; media: PinnedDirectory | null } | null> {
if (!slot.parent) {
if (!slot.pinning) {
slot.pinning = (async () => {
try {
const parentPath = await fs.realpath(slot.lexicalParent);
const parentStat = await fs.stat(parentPath);
if (!parentStat.isDirectory()) return;
slot.parent = pinnedDirectory(parentPath, parentStat);
} catch {
// A configured parent that does not exist yet is retried on a later operation.
}
})().finally(() => {
slot.pinning = undefined;
});
}
await slot.pinning;
}
if (!slot.parent) return null;
const mediaPath = join(slot.lexicalParent, 'media');
if (!slot.media) {
if (!slot.mediaPinning) {
slot.mediaPinning = (async () => {
try {
if ((await fs.lstat(mediaPath)).isSymbolicLink()) return;
const canonicalMedia = await fs.realpath(mediaPath);
const mediaStat = await fs.stat(canonicalMedia);
if (!mediaStat.isDirectory() || !isInside(canonicalMedia, slot.parent!.canonicalPath)) return;
slot.media = pinnedDirectory(canonicalMedia, mediaStat);
} catch {
// Media dir not available yet.
}
})().finally(() => {
slot.mediaPinning = undefined;
});
}
try {
await slot.mediaPinning;
} catch {
return { parent: slot.parent, media: null };
}
}
return { parent: slot.parent, media: slot.media ?? null };
}
async function frozenCanonicalDirectory(path: string, fs: AttachmentFs): Promise<string> {
try {
return await fs.realpath(path);
} catch {
return path;
}
}
async function readOpenedFile(handle: FileHandle, maxBytes: number): Promise<Buffer | null> {
const chunks: Buffer[] = [];
let total = 0;
while (total <= maxBytes) {
const length = Math.min(64 * 1024, maxBytes + 1 - total);
const chunk = Buffer.allocUnsafe(length);
const { bytesRead } = await handle.read(chunk, 0, length, total);
if (bytesRead === 0) break;
chunks.push(chunk.subarray(0, bytesRead));
total += bytesRead;
}
return total > maxBytes ? null : Buffer.concat(chunks, total);
}
function looksLikeBinary(buffer: Buffer): boolean {
const length = Math.min(buffer.length, 8192);
for (let index = 0; index < length; index += 1) {
if (buffer[index] === 0) return true;
}
return false;
}
async function openRevalidatedLocal(local: ResolvedLocal, fs: AttachmentFs): Promise<{
handle: FileHandle;
stat: Stats;
}> {
let handle: FileHandle | undefined;
try {
const noFollow = process.platform === 'win32' ? 0 : constants.O_NOFOLLOW;
handle = await fs.open(local.canonicalPath, constants.O_RDONLY | noFollow);
const handleStat = await handle.stat();
if (!handleStat.isFile()) {
throw new AttachmentFailure('notFile');
}
return { handle, stat: handleStat };
} catch (error) {
await handle?.close().catch(() => undefined);
throw error;
}
}
function normalizeRemote(uri: string): string {
let url: URL;
try {
url = new URL(uri);
} catch {
throw new AttachmentFailure('unsafeUrl');
}
if ((url.protocol !== 'http:' && url.protocol !== 'https:') || !url.hostname || url.username || url.password) {
throw new AttachmentFailure('unsafeUrl');
}
return url.href;
}
function boundedBinaryCap(value: unknown): number {
const requested = typeof value === 'number' && Number.isFinite(value) ? value : FILE_PREVIEW_MAX_BINARY_BYTES;
return Math.max(1, Math.min(requested, FILE_PREVIEW_MAX_BINARY_BYTES));
}
export async function resolveOutgoingMediaAttachment(input: {
uri: string;
expectedSessionKey?: string;
transcriptMessageId?: string;
stateDir?: string;
configDir?: string;
managedMediaRoots?: string[];
fs?: AttachmentFs;
}): Promise<{ path: string; mimeType: string; size: number; authorizationRoot: string } | null> {
try {
validateReferenceSyntax(input.uri);
const outgoing = parseOutgoingUrl(input.uri);
if (!outgoing || (input.expectedSessionKey && outgoing.sessionKey !== input.expectedSessionKey)) return null;
const fs = input.fs ?? await import('node:fs/promises');
const stateDir = resolve(input.stateDir ?? resolveOpenClawStateDir());
const configDir = resolve(input.configDir ?? resolveOpenClawConfigDir());
const recordPath = join(stateDir, 'media', 'outgoing', 'records', `${outgoing.attachmentId}.json`);
let handle: FileHandle | undefined;
let raw: Buffer | null;
try {
const noFollow = process.platform === 'win32' ? 0 : constants.O_NOFOLLOW;
handle = await fs.open(recordPath, constants.O_RDONLY | noFollow);
if (!(await handle.stat()).isFile()) return null;
raw = await readOpenedFile(handle, MAX_OUTGOING_RECORD_BYTES);
} finally {
await handle?.close().catch(() => undefined);
}
if (!raw) return null;
const record = JSON.parse(raw.toString('utf8')) as Record<string, unknown>;
const original = record.original && typeof record.original === 'object'
? record.original as Record<string, unknown>
: null;
const recordId = typeof record.attachmentId === 'string' ? record.attachmentId : undefined;
if (recordId !== outgoing.attachmentId
|| record.sessionKey !== outgoing.sessionKey
|| (input.transcriptMessageId && typeof record.messageId === 'string'
&& record.messageId !== input.transcriptMessageId)
|| !original
|| typeof original.path !== 'string') {
return null;
}
validateReferenceSyntax(original.path);
const originalPath = localPathFromUri(original.path, stateDir);
const roots = input.managedMediaRoots ?? await canonicalManagedMediaRoots(stateDir, configDir, fs);
const canonicalPath = await fs.realpath(originalPath);
const authorizationRoot = roots.find((root) => isInside(canonicalPath, root));
if (!authorizationRoot) return null;
const fileStat = await fs.stat(canonicalPath);
if (!fileStat.isFile()) return null;
return {
path: canonicalPath,
mimeType: typeof original.contentType === 'string' && original.contentType
? original.contentType
: mimeTypeForPath(canonicalPath),
size: fileStat.size,
authorizationRoot,
};
} catch {
return null;
}
}
export function createAttachmentAccess(dependencies: AttachmentAccessDependencies): AttachmentAccess {
const stateDir = resolve(dependencies.stateDir ?? resolveOpenClawStateDir());
const configDir = resolve(dependencies.configDir ?? resolveOpenClawConfigDir());
const shell = dependencies.shell ?? electronShell;
const getFs = async (): Promise<AttachmentFs> => dependencies.fs ?? await import('node:fs/promises');
const stateAuthority: ManagedAuthoritySlot = { lexicalParent: stateDir };
const configAuthority: ManagedAuthoritySlot = { lexicalParent: configDir };
const initializeAuthorities = async () => {
const fs = await getFs();
await Promise.all([
ensureManagedAuthority(stateAuthority, fs),
ensureManagedAuthority(configAuthority, fs),
]);
};
void initializeAuthorities().catch(() => undefined);
const verifyManagedAuthorities = async (fs: AttachmentFs) => {
const [state, config] = await Promise.all([
ensureManagedAuthority(stateAuthority, fs),
ensureManagedAuthority(configAuthority, fs),
]);
return {
stateParent: state?.parent ?? null,
mediaRoots: Array.from(new Set([
...(state?.media ? [state.media.canonicalPath] : []),
...(config?.media ? [config.media.canonicalPath] : []),
])),
};
};
const resolveLocalCandidate = async (
ref: AttachmentSourceRef,
candidateInput: string,
mimeTypeHint?: string,
mediaOnly = false,
): Promise<ResolvedLocal> => {
const context = dependencies.sessionAccessRegistry.get(ref.sessionKey, ref.generation);
if (!context) throw new AttachmentFailure('staleSession');
const fs = await getFs();
const candidate = resolve(candidateInput);
if (ref.stagingId) {
const stagedPath = dependencies.stagedAttachments.get(ref.stagingId);
if (stagedPath) {
let canonicalCandidate: string;
try {
canonicalCandidate = await fs.realpath(candidate);
} catch (error) {
throw new AttachmentFailure(attachmentFailure(error));
}
if (!isSamePath(canonicalCandidate, stagedPath)) throw new AttachmentFailure('invalidReference');
const stagedStat = await fs.stat(canonicalCandidate);
const entryKind = stagedStat.isFile()
? 'file'
: stagedStat.isDirectory()
? 'directory'
: null;
if (!entryKind) throw new AttachmentFailure('notFile');
return {
kind: 'local',
entryKind,
canonicalPath: canonicalCandidate,
scope: 'staging',
mimeType: entryKind === 'directory'
? DIRECTORY_MIME_TYPE
: mimeTypeHint || mimeTypeForPath(canonicalCandidate),
size: entryKind === 'directory' ? 0 : stagedStat.size,
};
}
}
let canonicalCandidate: string;
try {
canonicalCandidate = await fs.realpath(candidate);
} catch (error) {
throw new AttachmentFailure(attachmentFailure(error));
}
const targetStat = await fs.stat(canonicalCandidate);
const entryKind = targetStat.isFile()
? 'file'
: targetStat.isDirectory()
? 'directory'
: null;
if (!entryKind) throw new AttachmentFailure('notFile');
const workspaceRoot = mediaOnly ? null : await frozenCanonicalDirectory(context.workspaceRoot, fs);
const scope: LocalScope = workspaceRoot && isInside(canonicalCandidate, workspaceRoot)
? 'workspace'
: 'openclaw-media';
return {
kind: 'local',
entryKind,
canonicalPath: canonicalCandidate,
scope,
mimeType: entryKind === 'directory'
? DIRECTORY_MIME_TYPE
: mimeTypeHint || mimeTypeForPath(canonicalCandidate),
size: entryKind === 'directory' ? 0 : targetStat.size,
};
};
const resolveOutgoing = async (
ref: AttachmentSourceRef,
outgoing: { attachmentId: string; sessionKey: string },
): Promise<ResolvedLocal> => {
if (outgoing.sessionKey !== ref.sessionKey) throw new AttachmentFailure('invalidReference');
const fs = await getFs();
const { mediaRoots } = await verifyManagedAuthorities(fs);
const resolved = await resolveOutgoingMediaAttachment({
uri: ref.uri,
expectedSessionKey: ref.sessionKey,
transcriptMessageId: ref.transcriptMessageId,
stateDir,
configDir,
managedMediaRoots: mediaRoots,
fs,
});
if (!resolved) throw new AttachmentFailure('invalidReference');
return {
kind: 'local',
entryKind: 'file',
canonicalPath: resolved.path,
scope: 'openclaw-media',
mimeType: resolved.mimeType,
size: resolved.size,
authorizationRoot: resolved.authorizationRoot,
};
};
const resolveTarget = async (
ref: AttachmentSourceRef,
metadata: Pick<ResolveAttachmentPayload, 'mimeType' | 'size'> = {},
): Promise<ResolvedTarget> => {
if (!ref || typeof ref.sessionKey !== 'string' || !Number.isFinite(ref.generation)) {
throw new AttachmentFailure('invalidReference');
}
validateReferenceSyntax(ref.uri);
const context = dependencies.sessionAccessRegistry.get(ref.sessionKey, ref.generation);
if (!context) throw new AttachmentFailure('staleSession');
const outgoing = parseOutgoingUrl(ref.uri);
if (outgoing) return resolveOutgoing(ref, outgoing);
if (/^https?:/i.test(ref.uri)) {
return {
kind: 'remote',
normalizedUrl: normalizeRemote(ref.uri),
mimeType: metadata.mimeType || mimeTypeForPath(new URL(ref.uri).pathname),
size: typeof metadata.size === 'number' && Number.isFinite(metadata.size) && metadata.size >= 0
? metadata.size
: 0,
};
}
const localPath = localPathFromUri(ref.uri, context.executionCwd);
return resolveLocalCandidate(ref, localPath, metadata.mimeType);
};
const resolveAttachment = async (payload: ResolveAttachmentPayload): Promise<ResolveAttachmentResult> => {
const ref = payload?.ref;
const fallbackName = decodedBasename(typeof ref?.uri === 'string' ? ref.uri : 'attachment');
const displayName = safeDisplayName(payload?.name, fallbackName);
try {
const target = await resolveTarget(ref, payload);
const localName = target.kind === 'local' ? basename(target.canonicalPath) : fallbackName;
const finalDisplayName = safeDisplayName(payload?.name, localName);
if (target.kind === 'remote') {
return {
ok: true,
identity: opaqueIdentity(target.normalizedUrl),
displayName: finalDisplayName,
mimeType: target.mimeType,
size: target.size,
target: { kind: 'remote', ref, url: target.normalizedUrl },
};
}
const displayPath = ref.stagingId
? dependencies.stagedAttachments.getDisplayPath(ref.stagingId)
: null;
return {
ok: true,
identity: opaqueIdentity(target.canonicalPath),
displayName: finalDisplayName,
...(displayPath ? { displayPath } : {}),
mimeType: target.mimeType,
size: target.size,
target: { kind: 'local', scope: target.scope, entryKind: target.entryKind, ref },
};
} catch (error) {
return { ok: false, displayName, error: attachmentFailure(error) };
}
};
const readAttachmentText = async (ref: AttachmentFileRef): Promise<ReadAttachmentTextResult> => {
let opened: { handle: FileHandle; stat: Stats } | undefined;
try {
const target = await resolveTarget(ref);
if (target.kind !== 'local') throw new AttachmentFailure('invalidReference');
if (target.entryKind !== 'file') throw new AttachmentFailure('notFile');
opened = await openRevalidatedLocal(target, await getFs());
if (!dependencies.sessionAccessRegistry.get(ref.sessionKey, ref.generation)) {
throw new AttachmentFailure('staleSession');
}
if (opened.stat.size > FILE_PREVIEW_MAX_TEXT_BYTES) {
return { ok: false, error: 'tooLarge', size: opened.stat.size };
}
const buffer = await readOpenedFile(opened.handle, FILE_PREVIEW_MAX_TEXT_BYTES);
if (!buffer) return { ok: false, error: 'tooLarge', size: FILE_PREVIEW_MAX_TEXT_BYTES + 1 };
if (looksLikeBinary(buffer)) return { ok: false, error: 'binary', size: buffer.length };
return {
ok: true,
content: buffer.toString('utf8'),
mimeType: target.mimeType,
size: buffer.length,
readOnly: true,
};
} catch (error) {
return { ok: false, error: attachmentFailure(error) };
} finally {
await opened?.handle.close().catch(() => undefined);
}
};
const readAttachmentBinary = async (
payload: ReadAttachmentBinaryPayload,
): Promise<ReadAttachmentBinaryResult> => {
let opened: { handle: FileHandle; stat: Stats } | undefined;
try {
const target = await resolveTarget(payload?.ref);
if (target.kind !== 'local') throw new AttachmentFailure('invalidReference');
if (target.entryKind !== 'file') throw new AttachmentFailure('notFile');
opened = await openRevalidatedLocal(target, await getFs());
if (!dependencies.sessionAccessRegistry.get(payload.ref.sessionKey, payload.ref.generation)) {
throw new AttachmentFailure('staleSession');
}
const cap = boundedBinaryCap(payload.maxBytes);
if (opened.stat.size > cap) return { ok: false, error: 'tooLarge', size: opened.stat.size };
const buffer = await readOpenedFile(opened.handle, cap);
if (!buffer) return { ok: false, error: 'tooLarge', size: cap + 1 };
return {
ok: true,
data: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength),
mimeType: target.mimeType,
size: buffer.length,
readOnly: true,
};
} catch (error) {
return { ok: false, error: attachmentFailure(error) };
} finally {
await opened?.handle.close().catch(() => undefined);
}
};
const openAttachment = async (ref: AttachmentSourceRef): Promise<OpenAttachmentResult> => {
let identity = opaqueIdentity(typeof ref?.uri === 'string' ? ref.uri : 'invalid');
let sourceKind: 'local' | 'remote' | 'invalid' = typeof ref?.uri === 'string'
? (/^https?:/i.test(ref.uri) ? 'remote' : 'local')
: 'invalid';
try {
const target = await resolveTarget(ref);
if (target.kind === 'remote') {
sourceKind = 'remote';
identity = opaqueIdentity(target.normalizedUrl);
if (!dependencies.sessionAccessRegistry.get(ref.sessionKey, ref.generation)) {
throw new AttachmentFailure('staleSession');
}
await shell.openExternal(target.normalizedUrl);
} else {
sourceKind = 'local';
identity = opaqueIdentity(target.canonicalPath);
const revalidated = await resolveTarget(ref);
if (revalidated.kind !== 'local') throw new AttachmentFailure('invalidReference');
identity = opaqueIdentity(revalidated.canonicalPath);
if (!dependencies.sessionAccessRegistry.get(ref.sessionKey, ref.generation)) {
throw new AttachmentFailure('staleSession');
}
const error = await shell.openPath(revalidated.canonicalPath);
if (error) throw new AttachmentFailure('operationFailed');
}
recordAttachmentOpenTrace({
ok: true,
reason: 'success',
sourceKind,
sessionKey: ref.sessionKey,
generation: ref.generation,
identity,
});
return { ok: true };
} catch (error) {
const reason = attachmentFailure(error);
recordAttachmentOpenTrace({
ok: false,
reason,
sourceKind,
sessionKey: typeof ref?.sessionKey === 'string' ? ref.sessionKey : '',
generation: typeof ref?.generation === 'number' ? ref.generation : -1,
identity,
});
return { ok: false, error: reason };
}
};
const requireCurrentLocalFileTarget = async (ref: AttachmentFileRef): Promise<ResolvedLocal> => {
const target = await resolveTarget(ref);
if (target.kind !== 'local') throw new AttachmentFailure('invalidReference');
if (target.entryKind !== 'file') throw new AttachmentFailure('notFile');
if (!dependencies.sessionAccessRegistry.get(ref.sessionKey, ref.generation)) {
throw new AttachmentFailure('staleSession');
}
return target;
};
const listAttachmentOpenHandlers = async (
ref: AttachmentFileRef,
): Promise<AttachmentOpenHandlersResult> => {
try {
const target = await requireCurrentLocalFileTarget(ref);
if (dependencies.openWith.platform === 'linux') {
return { ok: true, platform: 'linux', handlers: [] };
}
const handlers = await dependencies.openWith.list(target.canonicalPath);
if (!dependencies.sessionAccessRegistry.get(ref.sessionKey, ref.generation)) {
throw new AttachmentFailure('staleSession');
}
return {
ok: true,
platform: dependencies.openWith.platform,
handlers: handlers.map(({ id, name, iconDataUrl, isDefault }) => ({
handlerId: id,
name,
...(iconDataUrl ? { iconDataUrl } : {}),
isDefault,
})),
};
} catch (error) {
return { ok: false, error: attachmentFailure(error) };
}
};
const openAttachmentWith = async (
payload: OpenAttachmentWithPayload,
): Promise<OpenAttachmentResult> => {
try {
const target = await requireCurrentLocalFileTarget(payload?.ref);
if (typeof payload?.handlerId !== 'string'
|| !payload.handlerId.trim()
|| payload.handlerId.length > HANDLER_ID_MAX_LENGTH) {
throw new AttachmentFailure('invalidReference');
}
await dependencies.openWith.open(
target.canonicalPath,
payload.handlerId,
async () => (await requireCurrentLocalFileTarget(payload.ref)).canonicalPath,
);
return { ok: true };
} catch (error) {
return { ok: false, error: attachmentFailure(error) };
}
};
const revealAttachment = async (ref: AttachmentFileRef): Promise<OpenAttachmentResult> => {
try {
await requireCurrentLocalFileTarget(ref);
const revalidated = await requireCurrentLocalFileTarget(ref);
shell.showItemInFolder(revalidated.canonicalPath);
return { ok: true };
} catch (error) {
return { ok: false, error: attachmentFailure(error) };
}
};
return {
resolveAttachment,
readAttachmentText,
readAttachmentBinary,
openAttachment,
listAttachmentOpenHandlers,
openAttachmentWith,
revealAttachment,
};
}
+566
View File
@@ -0,0 +1,566 @@
import { app, type NativeImage } from 'electron';
import {
execFile as nodeExecFile,
spawn as nodeSpawn,
type ChildProcess,
type ChildProcessWithoutNullStreams,
type ExecFileException,
type ExecFileOptionsWithStringEncoding,
type SpawnOptionsWithoutStdio,
} from 'node:child_process';
import { createHash } from 'node:crypto';
import path from 'node:path';
export const PROCESS_TIMEOUT_MS = 5_000;
export const PROCESS_MAX_BUFFER_BYTES = 1_048_576;
export const HANDLER_NAME_MAX_LENGTH = 256;
export const HANDLER_ID_MAX_LENGTH = 512;
export const NATIVE_PATH_MAX_LENGTH = 4_096;
export const ICON_DATA_URL_MAX_BYTES = 65_536;
export const CACHE_TTL_MS = 300_000;
export const CACHE_MAX_ENTRIES = 128;
export type OpenWithPlatform = 'darwin' | 'win32' | 'linux';
export type SystemOpenHandler = {
id: string;
name: string;
iconDataUrl?: string;
isDefault: boolean;
};
export type AttachmentOpenWithService = {
platform: OpenWithPlatform;
list(filePath: string): Promise<SystemOpenHandler[]>;
open(
filePath: string,
handlerId: string,
revalidateFile: () => Promise<string>,
): Promise<void>;
};
type ExecFileDependency = (
file: string,
args: string[],
options: ExecFileOptionsWithStringEncoding,
callback: (error: ExecFileException | null, stdout: string, stderr: string) => void,
) => ChildProcess;
type SpawnDependency = (
command: string,
args: string[],
options: SpawnOptionsWithoutStdio,
) => ChildProcessWithoutNullStreams;
type IconImage = Pick<NativeImage, 'isEmpty' | 'toPNG'>;
export type AttachmentOpenWithDependencies = {
platform?: OpenWithPlatform;
clock?: () => number;
execFile?: ExecFileDependency;
spawn?: SpawnDependency;
loadIcon?: (filePath: string) => Promise<IconImage>;
resolveHelperPath?: () => string;
};
type NativeOpenHandler = SystemOpenHandler & {
nativeId: string;
applicationPath?: string;
iconSourcePath?: string;
};
type CacheEntry = {
createdAt: number;
handlers: NativeOpenHandler[];
};
const cacheSizeReaders = new WeakMap<AttachmentOpenWithService, () => number>();
/** @internal Test-only retention check; never exposes cache keys or values. */
export function getAttachmentOpenWithCacheSizeForTest(service: AttachmentOpenWithService): number {
return cacheSizeReaders.get(service)?.() ?? 0;
}
const WINDOWS_PUBLIC_ID = /^[a-f0-9]{64}$/;
const POWERSHELL_PREFIX_ARGS = [
'-NoLogo',
'-NoProfile',
'-NonInteractive',
'-ExecutionPolicy',
'Bypass',
'-File',
];
const MACOS_JXA_PROGRAM = String.raw`
ObjC.import('Foundation');
ObjC.import('AppKit');
function stringValue(value) {
if (!value) return '';
try { return ObjC.unwrap(value); } catch (_) { return String(value); }
}
function iconPngBase64(workspace, bundlePath) {
try {
var image = workspace.iconForFile(bundlePath);
var targetSize = $.NSMakeSize(32, 32);
var resized = $.NSImage.alloc.initWithSize(targetSize);
resized.lockFocus;
image.drawInRectFromRectOperationFraction(
$.NSMakeRect(0, 0, 32, 32),
$.NSZeroRect,
$.NSCompositingOperationCopy,
1.0
);
resized.unlockFocus;
var bitmap = $.NSBitmapImageRep.imageRepWithData(resized.TIFFRepresentation);
if (!bitmap) return '';
var png = bitmap.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $({}));
if (!png || Number(png.length) === 0) return '';
return stringValue(png.base64EncodedStringWithOptions(0));
} catch (_) {
return '';
}
}
function run(argv) {
if (!argv || (argv.length !== 1 && argv.length !== 2)) return JSON.stringify([]);
var includeIcons = argv.length === 2 && argv[1] === 'icons';
if (argv.length === 2 && !includeIcons) return JSON.stringify([]);
var fileURL = $.NSURL.fileURLWithPath(argv[0]);
var workspace = $.NSWorkspace.sharedWorkspace;
var applicationURLs = workspace.URLsForApplicationsToOpenURL(fileURL);
var defaultURL = workspace.URLForApplicationToOpenURL(fileURL);
var records = [];
for (var index = 0; index < Number(applicationURLs.count); index += 1) {
var applicationURL = applicationURLs.objectAtIndex(index);
var bundle = $.NSBundle.bundleWithURL(applicationURL);
var bundleId = stringValue(bundle.bundleIdentifier);
var bundlePath = stringValue(applicationURL.path);
var name = stringValue($.NSFileManager.defaultManager.displayNameAtPath(bundlePath));
if (!bundleId || !name || !bundlePath) continue;
var record = {
nativeId: bundleId,
name: name,
applicationPath: bundlePath,
isDefault: Boolean(defaultURL && applicationURL.isEqual(defaultURL))
};
if (includeIcons) {
var icon = iconPngBase64(workspace, bundlePath);
if (icon) record.iconPngBase64 = icon;
}
records.push(record);
}
return JSON.stringify(records);
}
`;
function hasControlCharacters(value: string): boolean {
for (let index = 0; index < value.length; index += 1) {
const codeUnit = value.charCodeAt(index);
if (codeUnit <= 0x1f || (codeUnit >= 0x7f && codeUnit <= 0x9f)) return true;
}
return false;
}
function isBoundedString(value: unknown, maxLength: number): value is string {
return typeof value === 'string'
&& value.length > 0
&& value.length <= maxLength
&& !hasControlCharacters(value);
}
function isOptionalBoundedPath(value: unknown): value is string | undefined {
return value === undefined || isBoundedString(value, NATIVE_PATH_MAX_LENGTH);
}
function iconDataUrlFromBase64(value: unknown): string | undefined {
if (typeof value !== 'string' || value.length === 0) return undefined;
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
return undefined;
}
const iconDataUrl = `data:image/png;base64,${value}`;
if (Buffer.byteLength(iconDataUrl, 'utf8') > ICON_DATA_URL_MAX_BYTES) return undefined;
const png = Buffer.from(value, 'base64');
const pngSignature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
if (png.length < pngSignature.length || !png.subarray(0, pngSignature.length).equals(pngSignature)) {
return undefined;
}
return iconDataUrl;
}
function associationKey(platform: OpenWithPlatform, filePath: string): string {
const pathApi = platform === 'win32' ? path.win32 : path.posix;
const basename = pathApi.basename(filePath).toLocaleLowerCase('en-US');
const extension = pathApi.extname(basename);
return extension || basename;
}
function processEnvironment(platform: OpenWithPlatform): NodeJS.ProcessEnv {
if (platform === 'win32') {
const systemRoot = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
const env: NodeJS.ProcessEnv = {
SystemRoot: systemRoot,
WINDIR: systemRoot,
PATH: [
path.win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0'),
path.win32.join(systemRoot, 'System32'),
systemRoot,
].join(';'),
PATHEXT: '.COM;.EXE;.BAT;.CMD',
};
for (const key of ['TEMP', 'TMP', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA'] as const) {
if (process.env[key]) env[key] = process.env[key];
}
return env;
}
const env: NodeJS.ProcessEnv = { PATH: '/usr/bin:/bin:/usr/sbin:/sbin' };
for (const key of ['HOME', 'TMPDIR', 'USER', 'LOGNAME', 'LANG', 'LC_ALL'] as const) {
if (process.env[key]) env[key] = process.env[key];
}
return env;
}
function publicHandlers(handlers: NativeOpenHandler[]): SystemOpenHandler[] {
return handlers.map(({ id, name, iconDataUrl, isDefault }) => ({
id,
name,
...(iconDataUrl ? { iconDataUrl } : {}),
isDefault,
}));
}
function windowsPublicId(nativeId: string): string {
return createHash('sha256').update(`win32\0${nativeId}`, 'utf8').digest('hex');
}
function normalizeRecords(platform: OpenWithPlatform, output: string): NativeOpenHandler[] {
let parsed: unknown;
try {
parsed = JSON.parse(output.replace(/^\uFEFF/, '')) as unknown;
} catch {
return [];
}
if (!Array.isArray(parsed)) return [];
const deduplicated = new Map<string, NativeOpenHandler>();
for (const value of parsed) {
if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
const record = value as Record<string, unknown>;
if (!isBoundedString(record.nativeId, HANDLER_ID_MAX_LENGTH)) continue;
if (!isBoundedString(record.name, HANDLER_NAME_MAX_LENGTH)) continue;
if (typeof record.isDefault !== 'boolean') continue;
if (!isOptionalBoundedPath(record.applicationPath)) continue;
if (!isOptionalBoundedPath(record.iconSourcePath)) continue;
if (platform === 'darwin' && !isBoundedString(record.applicationPath, NATIVE_PATH_MAX_LENGTH)) {
continue;
}
const id = platform === 'win32' ? windowsPublicId(record.nativeId) : record.nativeId;
const iconDataUrl = platform === 'darwin'
? iconDataUrlFromBase64(record.iconPngBase64)
: undefined;
const existing = deduplicated.get(id);
if (existing) {
if (record.isDefault) existing.isDefault = true;
if (!existing.iconDataUrl && iconDataUrl) existing.iconDataUrl = iconDataUrl;
continue;
}
deduplicated.set(id, {
id,
nativeId: record.nativeId,
name: record.name,
...(record.applicationPath ? { applicationPath: record.applicationPath } : {}),
...(record.iconSourcePath ? { iconSourcePath: record.iconSourcePath } : {}),
...(iconDataUrl ? { iconDataUrl } : {}),
isDefault: record.isDefault,
});
}
const handlers = [...deduplicated.values()];
return [
...handlers.filter((handler) => handler.isDefault),
...handlers.filter((handler) => !handler.isDefault),
];
}
function defaultHelperPath(): string {
const root = app.isPackaged ? process.resourcesPath : app.getAppPath();
return path.join(root, 'resources', 'scripts', 'attachment-open-with.ps1');
}
function processError(reason: string): Error {
return new Error(`attachment-open-with:${reason}`);
}
export function createAttachmentOpenWithService(
dependencies: AttachmentOpenWithDependencies = {},
): AttachmentOpenWithService {
const platform = dependencies.platform ?? (
process.platform === 'darwin' || process.platform === 'win32' ? process.platform : 'linux'
);
const clock = dependencies.clock ?? Date.now;
const execFile = dependencies.execFile ?? (nodeExecFile as ExecFileDependency);
const spawn = dependencies.spawn ?? (nodeSpawn as SpawnDependency);
const loadIcon = dependencies.loadIcon ?? ((filePath: string) => app.getFileIcon(filePath, { size: 'normal' }));
const resolveHelperPath = dependencies.resolveHelperPath ?? defaultHelperPath;
const cache = new Map<string, CacheEntry>();
function runExec(command: string, args: string[]): Promise<string> {
return new Promise((resolve, reject) => {
execFile(command, args, {
timeout: PROCESS_TIMEOUT_MS,
maxBuffer: PROCESS_MAX_BUFFER_BYTES,
encoding: 'utf8',
windowsHide: true,
shell: false,
env: processEnvironment(platform),
}, (error, stdout) => {
if (error) {
reject(processError('process-failed'));
return;
}
resolve(stdout);
});
});
}
async function discover(filePath: string, includeIcons = false): Promise<NativeOpenHandler[]> {
try {
if (platform === 'darwin') {
const output = await runExec('/usr/bin/osascript', [
'-l',
'JavaScript',
'-e',
MACOS_JXA_PROGRAM,
'--',
filePath,
...(includeIcons ? ['icons'] : []),
]);
return normalizeRecords(platform, output);
}
if (platform === 'win32') {
const output = await runExec('powershell.exe', [
...POWERSHELL_PREFIX_ARGS,
resolveHelperPath(),
'list',
filePath,
]);
return normalizeRecords(platform, output);
}
return [];
} catch {
return [];
}
}
async function enrichIcons(handlers: NativeOpenHandler[]): Promise<NativeOpenHandler[]> {
if (platform === 'darwin') return handlers;
return await Promise.all(handlers.map(async (handler) => {
const iconPath = handler.iconSourcePath ?? handler.applicationPath;
if (!iconPath) return handler;
try {
const image = await loadIcon(iconPath);
if (image.isEmpty()) return handler;
const png = image.toPNG();
if (png.length === 0) return handler;
const iconDataUrl = `data:image/png;base64,${png.toString('base64')}`;
if (Buffer.byteLength(iconDataUrl, 'utf8') > ICON_DATA_URL_MAX_BYTES) return handler;
return { ...handler, iconDataUrl };
} catch {
return handler;
}
}));
}
async function list(filePath: string): Promise<SystemOpenHandler[]> {
const now = clock();
for (const [key, entry] of cache) {
if (now - entry.createdAt >= CACHE_TTL_MS) cache.delete(key);
}
if (platform === 'linux') return [];
if (!isBoundedString(filePath, NATIVE_PATH_MAX_LENGTH)) return [];
const cacheKey = `${platform}:${associationKey(platform, filePath)}`;
const cached = cache.get(cacheKey);
if (cached && now - cached.createdAt < CACHE_TTL_MS) {
return publicHandlers(cached.handlers);
}
const handlers = await enrichIcons(await discover(filePath, true));
cache.set(cacheKey, { createdAt: now, handlers });
while (cache.size > CACHE_MAX_ENTRIES) {
const oldestKey = cache.keys().next().value;
if (oldestKey === undefined) break;
cache.delete(oldestKey);
}
return publicHandlers(handlers);
}
async function openMac(
filePath: string,
handlerId: string,
revalidateFile: () => Promise<string>,
): Promise<void> {
const handlers = await discover(filePath);
const selected = handlers.find((handler) => handler.id === handlerId && handler.applicationPath);
if (!selected?.applicationPath) throw processError('unknown-handler');
const revalidatedPath = await revalidateFile();
if (!isBoundedString(revalidatedPath, NATIVE_PATH_MAX_LENGTH)) throw processError('invalid-path');
if (associationKey(platform, revalidatedPath) !== associationKey(platform, filePath)) {
throw processError('association-changed');
}
try {
await runExec('/usr/bin/open', ['-a', selected.applicationPath, revalidatedPath]);
} catch {
throw processError('invoke-failed');
}
}
function openWindows(
filePath: string,
handlerId: string,
revalidateFile: () => Promise<string>,
): Promise<void> {
if (!WINDOWS_PUBLIC_ID.test(handlerId)) return Promise.reject(processError('unknown-handler'));
return new Promise((resolve, reject) => {
let child: ChildProcessWithoutNullStreams;
try {
child = spawn('powershell.exe', [
...POWERSHELL_PREFIX_ARGS,
resolveHelperPath(),
'prepare-open',
filePath,
handlerId,
], {
windowsHide: true,
shell: false,
stdio: 'pipe',
env: processEnvironment(platform),
});
} catch {
reject(processError('helper-start-failed'));
return;
}
let settled = false;
let ready = false;
let invokeSent = false;
let outputBytes = 0;
let stdoutBuffer = '';
const finish = (error?: Error) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
if (error) reject(error);
else resolve();
};
const abort = (error: Error) => {
if (settled) return;
try {
child.kill();
} catch {
// The bounded rejection is sufficient if the process already exited.
}
finish(error);
};
const handleReady = async () => {
try {
const revalidatedPath = await revalidateFile();
if (settled) return;
if (!isBoundedString(revalidatedPath, NATIVE_PATH_MAX_LENGTH)) {
abort(processError('invalid-path'));
return;
}
if (associationKey(platform, revalidatedPath) !== associationKey(platform, filePath)) {
abort(processError('association-changed'));
return;
}
invokeSent = true;
child.stdin.end(`${JSON.stringify({ command: 'invoke', path: revalidatedPath })}\n`, 'utf8');
} catch (error) {
abort(error instanceof Error ? error : processError('revalidation-failed'));
}
};
const timeout = setTimeout(() => abort(processError('helper-timeout')), PROCESS_TIMEOUT_MS);
const accountOutput = (chunk: Buffer | string): boolean => {
outputBytes += Buffer.byteLength(chunk);
if (outputBytes > PROCESS_MAX_BUFFER_BYTES) {
abort(processError('helper-output-limit'));
return false;
}
return true;
};
child.stdout.on('data', (chunk: Buffer | string) => {
if (settled || !accountOutput(chunk)) return;
if (ready) {
abort(processError('helper-protocol'));
return;
}
stdoutBuffer += chunk.toString();
const newline = stdoutBuffer.indexOf('\n');
if (newline < 0) return;
const line = stdoutBuffer.slice(0, newline).replace(/\r$/, '');
const remainder = stdoutBuffer.slice(newline + 1);
let message: unknown;
try {
message = JSON.parse(line) as unknown;
} catch {
abort(processError('helper-protocol'));
return;
}
if (!message || typeof message !== 'object' || Array.isArray(message)) {
abort(processError('helper-protocol'));
return;
}
const record = message as Record<string, unknown>;
if (record.ready !== true || Object.keys(record).length !== 1 || remainder.trim()) {
abort(processError('helper-protocol'));
return;
}
ready = true;
stdoutBuffer = '';
void handleReady();
});
child.stderr.on('data', (chunk: Buffer | string) => {
if (!settled) accountOutput(chunk);
});
child.stdin.on('error', () => abort(processError('helper-stdin')));
child.on('error', () => abort(processError('helper-start-failed')));
child.on('close', (code) => {
if (settled) return;
if (code === 0 && invokeSent) {
finish();
return;
}
finish(processError(ready ? 'helper-failed' : 'unknown-handler'));
});
});
}
async function open(
filePath: string,
handlerId: string,
revalidateFile: () => Promise<string>,
): Promise<void> {
if (!isBoundedString(filePath, NATIVE_PATH_MAX_LENGTH)) throw processError('invalid-path');
if (!isBoundedString(handlerId, HANDLER_ID_MAX_LENGTH)) throw processError('unknown-handler');
if (platform === 'linux') throw processError('unsupported-platform');
if (platform === 'darwin') return await openMac(filePath, handlerId, revalidateFile);
return await openWindows(filePath, handlerId, revalidateFile);
}
const service = { platform, list, open };
cacheSizeReaders.set(service, () => cache.size);
return service;
}
+77 -109
View File
@@ -22,6 +22,7 @@ import {
assignChannelAccountToAgent,
clearAllBindingsForChannel,
clearChannelBinding,
ensureScopedChannelBinding as ensureAgentScopedChannelBinding,
listAgentsSnapshot,
listAgentsSnapshotFromConfig,
} from '../utils/agent-config';
@@ -33,6 +34,7 @@ import {
ensureWeChatPluginInstalled,
ensureWeComPluginInstalled,
ensureWhatsAppPluginInstalled,
type PluginInstallResult,
} from '../utils/plugin-install';
import {
computeChannelRuntimeStatus,
@@ -153,11 +155,6 @@ const CHANNEL_TARGET_CACHE_TTL_MS = 60_000;
const CHANNEL_TARGET_CACHE_ENABLED = process.env.VITEST !== 'true';
const channelTargetCache = new Map<string, { expiresAt: number; targets: ChannelTargetOptionView[] }>();
const FORCE_RESTART_CHANNELS = new Set([
'dingtalk', 'wecom', 'whatsapp', 'feishu', 'qqbot', OPENCLAW_WECHAT_CHANNEL_TYPE,
'discord', 'telegram', 'signal', 'imessage', 'matrix', 'line', 'msteams', 'googlechat', 'mattermost',
]);
function requireString(payload: unknown, key: string): string {
if (!isRecord(payload) || typeof payload[key] !== 'string' || !payload[key].trim()) {
throw new Error(`${key} is required`);
@@ -924,83 +921,8 @@ async function listChannelTargetOptions(params: {
return targets;
}
async function readChannelBindingOwner(channelType: string, accountId?: string): Promise<string | null> {
const config = await readOpenClawConfig();
const bindings = Array.isArray((config as { bindings?: unknown }).bindings)
? (config as { bindings: unknown[] }).bindings
: [];
for (const binding of bindings) {
if (!binding || typeof binding !== 'object') continue;
const candidate = binding as {
agentId?: unknown;
match?: { channel?: unknown; accountId?: unknown } | unknown;
};
if (typeof candidate.agentId !== 'string' || !candidate.agentId.trim()) continue;
if (!candidate.match || typeof candidate.match !== 'object' || Array.isArray(candidate.match)) continue;
const match = candidate.match as { channel?: unknown; accountId?: unknown };
if (match.channel !== channelType) continue;
const bindingAccountId = typeof match.accountId === 'string' ? match.accountId.trim() : '';
if ((accountId?.trim() || '') !== bindingAccountId) continue;
return candidate.agentId;
}
return null;
}
async function migrateLegacyChannelWideBinding(channelType: string): Promise<void> {
const explicitDefaultOwner = await readChannelBindingOwner(channelType, 'default');
const legacyOwner = await readChannelBindingOwner(channelType);
if (!legacyOwner) return;
const agents = await listAgentsSnapshot();
const validAgentIds = new Set(agents.agents.map((agent) => agent.id));
const defaultOwner = explicitDefaultOwner && validAgentIds.has(explicitDefaultOwner)
? explicitDefaultOwner
: (legacyOwner && validAgentIds.has(legacyOwner) ? legacyOwner : null);
if (defaultOwner) {
await assignChannelAccountToAgent(defaultOwner, channelType, 'default');
}
await clearChannelBinding(channelType);
}
async function ensureScopedChannelBinding(channelType: string, accountId?: string): Promise<void> {
const storedChannelType = resolveStoredChannelType(channelType);
if (!accountId) return;
const agents = await listAgentsSnapshot();
if (!agents.agents || agents.agents.length === 0) return;
if (accountId === 'default') {
if (agents.agents.some((entry) => entry.id === 'main')) {
await assignChannelAccountToAgent('main', storedChannelType, 'default');
}
return;
}
if (agents.agents.some((entry) => entry.id === accountId)) {
await migrateLegacyChannelWideBinding(storedChannelType);
await assignChannelAccountToAgent(accountId, storedChannelType, accountId);
return;
}
await migrateLegacyChannelWideBinding(storedChannelType);
}
function scheduleGatewayChannelRestart(ctx: ChannelsApiContext, reason: string): void {
if (ctx.gatewayManager.getStatus().state === 'stopped') return;
ctx.gatewayManager.debouncedRestart();
void reason;
}
function scheduleGatewayChannelSaveRefresh(ctx: ChannelsApiContext, channelType: string, reason: string): void {
const storedChannelType = resolveStoredChannelType(channelType);
if (ctx.gatewayManager.getStatus().state === 'stopped') return;
if (FORCE_RESTART_CHANNELS.has(storedChannelType)) {
ctx.gatewayManager.debouncedRestart(150);
void reason;
return;
}
ctx.gatewayManager.debouncedReload(150);
void reason;
await ensureAgentScopedChannelBinding(resolveStoredChannelType(channelType), accountId);
}
function toComparableConfig(input: Record<string, unknown>): Record<string, string> {
@@ -1044,6 +966,43 @@ function emitChannelEvent(
}
}
const CHANNEL_PLUGIN_INSTALLERS: Record<
string,
() => MaybePromise<PluginInstallResult>
> = {
dingtalk: ensureDingTalkPluginInstalled,
wecom: ensureWeComPluginInstalled,
discord: ensureDiscordPluginInstalled,
qqbot: ensureQQBotPluginInstalled,
whatsapp: ensureWhatsAppPluginInstalled,
feishu: ensureFeishuPluginInstalled,
[OPENCLAW_WECHAT_CHANNEL_TYPE]: ensureWeChatPluginInstalled,
};
function isPluginBackedChannel(storedChannelType: string): boolean {
return Object.hasOwn(CHANNEL_PLUGIN_INSTALLERS, storedChannelType);
}
function shouldRestartRunningGateway(ctx: ChannelsApiContext, storedChannelType: string): boolean {
return isPluginBackedChannel(storedChannelType)
&& ctx.gatewayManager.getStatus().state === 'running';
}
function scheduleGatewayRestartForPluginChannel(
ctx: ChannelsApiContext,
storedChannelType: string,
reason: 'noChange' | 'peerLinkRepairFailed' = 'noChange',
): void {
logger.info(
`[channels.saveConfig] scheduling Gateway restart to activate plugin channel=${storedChannelType} reason=${reason}`,
);
// The config and scoped binding are already committed. Let the host request
// return while the guarded lifecycle path performs stop/start/readiness.
// GatewayManager owns error logging, status propagation, and restart
// coalescing, so the Channels page can show the normal connecting state.
ctx.gatewayManager.debouncedRestart(0);
}
async function awaitWeChatQrLogin(
ctx: ChannelsApiContext,
sessionKey: string,
@@ -1070,9 +1029,12 @@ async function awaitWeChatQrLogin(
baseUrl: result.baseUrl,
userId: result.userId,
});
const restartGateway = shouldRestartRunningGateway(ctx, OPENCLAW_WECHAT_CHANNEL_TYPE);
await saveChannelConfig(UI_WECHAT_CHANNEL_TYPE, { enabled: true }, normalizedAccountId);
await ensureScopedChannelBinding(UI_WECHAT_CHANNEL_TYPE, normalizedAccountId);
scheduleGatewayChannelSaveRefresh(ctx, OPENCLAW_WECHAT_CHANNEL_TYPE, `wechat:loginSuccess:${normalizedAccountId}`);
if (restartGateway) {
scheduleGatewayRestartForPluginChannel(ctx, OPENCLAW_WECHAT_CHANNEL_TYPE);
}
if (activeQrLogins.get(loginKey) !== sessionKey) return;
emitChannelEvent(ctx, UI_WECHAT_CHANNEL_TYPE, 'success', {
@@ -1089,22 +1051,14 @@ async function awaitWeChatQrLogin(
}
}
async function ensureChannelPluginInstalled(storedChannelType: string): Promise<void> {
const installers: Record<string, () => MaybePromise<{ installed: boolean; warning?: string }>> = {
dingtalk: ensureDingTalkPluginInstalled,
wecom: ensureWeComPluginInstalled,
discord: ensureDiscordPluginInstalled,
qqbot: ensureQQBotPluginInstalled,
whatsapp: ensureWhatsAppPluginInstalled,
feishu: ensureFeishuPluginInstalled,
[OPENCLAW_WECHAT_CHANNEL_TYPE]: ensureWeChatPluginInstalled,
};
const install = installers[storedChannelType];
if (!install) return;
async function ensureChannelPluginInstalled(storedChannelType: string): Promise<{ peerLinkOk: boolean }> {
const install = CHANNEL_PLUGIN_INSTALLERS[storedChannelType];
if (!install) return { peerLinkOk: true };
const result = await install();
if (!result.installed) {
throw new Error(result.warning || `${toUiChannelType(storedChannelType)} plugin install failed`);
}
return { peerLinkOk: result.peerLinkOk !== false };
}
export function createChannelsApi(ctx: ChannelsApiContext): CompleteHostServiceRegistry['channels'] {
@@ -1135,7 +1089,6 @@ export function createChannelsApi(ctx: ChannelsApiContext): CompleteHostServiceR
const accountId = requireString(payload, 'accountId');
await validateCanonicalAccountId(channelType, accountId, { allowLegacyConfiguredId: true });
await setChannelDefaultAccount(channelType, accountId);
scheduleGatewayChannelSaveRefresh(ctx, channelType, `channel:setDefaultAccount:${channelType}`);
return { success: true };
},
bindingSave: async (payload) => {
@@ -1148,11 +1101,16 @@ export function createChannelsApi(ctx: ChannelsApiContext): CompleteHostServiceR
throw new Error(`Agent "${agentId}" not found`);
}
const storedChannelType = resolveStoredChannelType(channelType);
if (accountId !== 'default') {
await migrateLegacyChannelWideBinding(storedChannelType);
if (accountId === 'default') {
await assignChannelAccountToAgent(agentId, storedChannelType, accountId);
} else {
await assignChannelAccountToAgent(
agentId,
storedChannelType,
accountId,
{ migrateLegacy: true },
);
}
await assignChannelAccountToAgent(agentId, storedChannelType, accountId);
scheduleGatewayChannelSaveRefresh(ctx, channelType, `channel:setBinding:${channelType}`);
return { success: true };
},
bindingDelete: async (payload) => {
@@ -1160,7 +1118,6 @@ export function createChannelsApi(ctx: ChannelsApiContext): CompleteHostServiceR
const accountId = optionalString(payload, 'accountId');
await validateCanonicalAccountId(channelType, accountId, { allowLegacyConfiguredId: true });
await clearChannelBinding(resolveStoredChannelType(channelType), accountId);
scheduleGatewayChannelSaveRefresh(ctx, channelType, `channel:clearBinding:${channelType}`);
return { success: true };
},
validateConfig: async (payload) => {
@@ -1178,23 +1135,36 @@ export function createChannelsApi(ctx: ChannelsApiContext): CompleteHostServiceR
const accountId = optionalString(payload, 'accountId');
await validateCanonicalAccountId(channelType, accountId, { allowLegacyConfiguredId: true });
const storedChannelType = resolveStoredChannelType(channelType);
await ensureChannelPluginInstalled(storedChannelType);
const existingValues = await getChannelFormValues(channelType, accountId);
const restartGateway = shouldRestartRunningGateway(ctx, storedChannelType);
const [installResult, existingValues] = await Promise.all([
ensureChannelPluginInstalled(storedChannelType),
getChannelFormValues(channelType, accountId),
]);
if (isSameConfigValues(existingValues, config)) {
await ensureScopedChannelBinding(channelType, accountId);
scheduleGatewayChannelSaveRefresh(ctx, storedChannelType, `channel:saveConfigNoChange:${storedChannelType}`);
return { success: true, noChange: true };
if (restartGateway) {
scheduleGatewayRestartForPluginChannel(ctx, storedChannelType, 'noChange');
}
return { success: true, noChange: true, ...(restartGateway ? { activationPending: true } : {}) };
}
await saveChannelConfig(channelType, config, accountId);
await ensureScopedChannelBinding(channelType, accountId);
scheduleGatewayChannelSaveRefresh(ctx, storedChannelType, `channel:saveConfig:${storedChannelType}`);
return { success: true };
if (restartGateway && !installResult.peerLinkOk) {
scheduleGatewayRestartForPluginChannel(ctx, storedChannelType, 'peerLinkRepairFailed');
return { success: true, activationPending: true };
}
// A changed running config is delivered through config.set, whose native
// reload activates the plugin. Scheduling another full restart here races
// that code-1012 reload and can trip OpenClaw's restart-loop breaker.
// Keep the explicit restart above only for no-change retries, where no
// config.set reload occurs but a newly copied plugin may still need discovery,
// and when OpenClaw peer link repair failed after plugin install.
return { success: true, ...(restartGateway ? { activationPending: true } : {}) };
},
setEnabled: async (payload) => {
const channelType = requireString(payload, 'channelType');
const enabled = isRecord(payload) && payload.enabled === true;
await setChannelEnabled(channelType, enabled);
scheduleGatewayChannelRestart(ctx, `channel:setEnabled:${resolveStoredChannelType(channelType)}`);
return { success: true };
},
formValues: async (payload) => {
@@ -1209,11 +1179,9 @@ export function createChannelsApi(ctx: ChannelsApiContext): CompleteHostServiceR
if (accountId) {
await deleteChannelAccountConfig(channelType, accountId);
await clearChannelBinding(storedChannelType, accountId);
scheduleGatewayChannelSaveRefresh(ctx, storedChannelType, `channel:deleteAccount:${storedChannelType}`);
} else {
await deleteChannelConfig(channelType);
await clearAllBindingsForChannel(storedChannelType);
scheduleGatewayChannelRestart(ctx, `channel:deleteConfig:${storedChannelType}`);
}
return { success: true };
},
+17 -105
View File
@@ -1,112 +1,24 @@
import type { BrowserWindow } from 'electron';
import type { GatewayManager } from '../gateway/manager';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import { logger } from '../utils/logger';
import { isRecord } from './payload-utils';
import { createAcpChatService } from './acp-chat-service';
import type { AcpSessionAccessRegistry } from './acp-session-access-registry';
const VISION_MIME_TYPES = new Set([
'image/png',
'image/jpeg',
'image/bmp',
'image/webp',
]);
export function createChatApi({
gatewayManager,
mainWindow,
acpSessionAccessRegistry,
}: {
gatewayManager: GatewayManager;
mainWindow: BrowserWindow;
acpSessionAccessRegistry: AcpSessionAccessRegistry;
}): CompleteHostServiceRegistry['chat'] {
const acpChat = createAcpChatService(mainWindow, acpSessionAccessRegistry, gatewayManager);
type ChatSendWithMediaPayload = {
sessionKey?: unknown;
message?: unknown;
deliver?: unknown;
idempotencyKey?: unknown;
media?: unknown;
};
type MediaPayload = {
filePath?: unknown;
mimeType?: unknown;
fileName?: unknown;
};
function normalizeMedia(media: unknown): Array<{ filePath: string; mimeType: string; fileName: string }> {
if (!Array.isArray(media)) return [];
return media.flatMap((entry): Array<{ filePath: string; mimeType: string; fileName: string }> => {
if (!isRecord(entry)) return [];
const item = entry as MediaPayload;
if (typeof item.filePath !== 'string' || !item.filePath) return [];
return [{
filePath: item.filePath,
mimeType: typeof item.mimeType === 'string' && item.mimeType ? item.mimeType : 'application/octet-stream',
fileName: typeof item.fileName === 'string' && item.fileName ? item.fileName : item.filePath.split(/[\\/]/).pop() || 'file',
}];
});
}
export function createChatApi({ gatewayManager }: { gatewayManager: GatewayManager }): CompleteHostServiceRegistry['chat'] {
return {
sendWithMedia: async (payload) => {
const body = isRecord(payload) ? payload as ChatSendWithMediaPayload : {};
const sessionKey = typeof body.sessionKey === 'string' ? body.sessionKey : '';
const idempotencyKey = typeof body.idempotencyKey === 'string' ? body.idempotencyKey : '';
if (!sessionKey || !idempotencyKey) {
return { success: false, error: 'Invalid chat send payload' };
}
try {
let message = typeof body.message === 'string' ? body.message : '';
const imageAttachments: Array<Record<string, unknown>> = [];
const fileReferences: string[] = [];
const media = normalizeMedia(body.media);
if (media.length > 0) {
const fsP = await import('node:fs/promises');
for (const item of media) {
const exists = await fsP.access(item.filePath).then(() => true, () => false);
logger.info(
`[chat:sendWithMedia] Processing file: ${item.fileName} (${item.mimeType}), path: ${item.filePath}, exists: ${exists}, isVision: ${VISION_MIME_TYPES.has(item.mimeType)}`,
);
fileReferences.push(
`[media attached: ${item.filePath} (${item.mimeType}) | ${item.filePath}]`,
);
if (VISION_MIME_TYPES.has(item.mimeType)) {
const fileBuffer = await fsP.readFile(item.filePath);
const base64Data = fileBuffer.toString('base64');
logger.info(`[chat:sendWithMedia] Read ${fileBuffer.length} bytes, base64 length: ${base64Data.length}`);
imageAttachments.push({
content: base64Data,
mimeType: item.mimeType,
fileName: item.fileName,
});
}
}
}
if (fileReferences.length > 0) {
const refs = fileReferences.join('\n');
message = message ? `${message}\n\n${refs}` : refs;
}
const rpcParams: Record<string, unknown> = {
sessionKey,
message,
deliver: body.deliver ?? false,
idempotencyKey,
};
if (imageAttachments.length > 0) {
rpcParams.attachments = imageAttachments;
}
logger.info(
`[chat:sendWithMedia] Sending: message="${message.substring(0, 100)}", attachments=${imageAttachments.length}, fileRefs=${fileReferences.length}`,
);
const result = await gatewayManager.rpc('chat.send', rpcParams, 120000);
logger.info(`[chat:sendWithMedia] RPC result: ${JSON.stringify(result)}`);
const response = isRecord(result) && typeof result.runId === 'string'
? { runId: result.runId }
: undefined;
return { success: true, ...(response ? { result: response } : {}) };
} catch (error) {
logger.error(`[chat:sendWithMedia] Error: ${String(error)}`);
return { success: false, error: String(error) };
}
},
loadAcpSession: (payload) => acpChat.loadSession(payload),
sendAcpPrompt: (payload) => acpChat.sendPrompt(payload),
cancelAcpSession: (payload) => acpChat.cancelSession(payload),
respondAcpPermission: (payload) => acpChat.respondPermission(payload),
};
}
+134 -21
View File
@@ -1,12 +1,14 @@
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import type { RawMessage } from '@shared/chat/types';
import type { CronJob, CronJobDelivery, CronSchedule } from '@shared/types/cron';
import type { GatewayManager } from '../gateway/manager';
import { getOpenClawConfigDir } from '../utils/paths';
import { resolveAgentIdFromChannel } from '../utils/agent-config';
import { toOpenClawChannelType, toUiChannelType } from '../utils/channel-alias';
import { resolveAccountIdFromSessionHistory } from '../utils/session-util';
import { loadSessionTranscriptByKey } from './sessions-api';
import { isRecord } from './payload-utils';
interface GatewayCronJob {
@@ -53,13 +55,14 @@ interface CronSessionKeyParts {
interface CronSessionFallbackMessage {
id: string;
role: 'assistant' | 'system';
role: 'user' | 'assistant';
content: string;
timestamp: number;
isError?: boolean;
}
type JsonRecord = Record<string, unknown>;
const OPENCLAW_CRON_SUMMARY_TRUNCATION_MIN_CHARS = 2_000;
function parseCronSessionKey(sessionKey: string): CronSessionKeyParts | null {
if (!sessionKey.startsWith('agent:')) return null;
@@ -93,14 +96,83 @@ function formatDuration(durationMs: number | undefined): string | null {
return `${Math.round(durationMs / 1000)}s`;
}
function buildCronRunMessage(entry: CronRunLogEntry, index: number): CronSessionFallbackMessage | null {
function getMessageText(content: RawMessage['content']): string {
if (typeof content === 'string') return content.trim();
if (!Array.isArray(content)) return '';
return content
.map((block) => {
if (!block || typeof block !== 'object') return '';
const value = block as { type?: unknown; text?: unknown };
return value.type === 'text' && typeof value.text === 'string' ? value.text : '';
})
.filter(Boolean)
.join('\n')
.trim();
}
function getFinalAssistantReply(messages: RawMessage[]): string {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (message?.role !== 'assistant') continue;
const text = getMessageText(message.content);
if (text) return text;
}
return '';
}
function isBoundedCronSummary(summary: string): boolean {
return summary.length >= OPENCLAW_CRON_SUMMARY_TRUNCATION_MIN_CHARS
&& summary.endsWith('…');
}
function resolveCronRunSessionKey(
parsed: CronSessionKeyParts,
entry: CronRunLogEntry,
): string | null {
const explicitSessionKey = typeof entry.sessionKey === 'string' ? entry.sessionKey.trim() : '';
if (explicitSessionKey && parseCronSessionKey(explicitSessionKey)?.runSessionId) {
return explicitSessionKey;
}
const sessionId = typeof entry.sessionId === 'string' ? entry.sessionId.trim() : '';
if (!sessionId) return null;
return `agent:${parsed.agentId}:cron:${parsed.jobId}:run:${sessionId}`;
}
async function loadFullCronRunReplies(
parsed: CronSessionKeyParts,
runs: CronRunLogEntry[],
): Promise<Map<CronRunLogEntry, string>> {
const replies = new Map<CronRunLogEntry, string>();
await Promise.all(runs.map(async (entry) => {
const summary = typeof entry.summary === 'string' ? entry.summary.trim() : '';
if (!isBoundedCronSummary(summary)) return;
const runSessionKey = resolveCronRunSessionKey(parsed, entry);
if (!runSessionKey) return;
const transcript = await loadSessionTranscriptByKey(runSessionKey, 1_000);
if (!transcript?.length) return;
const fullReply = getFinalAssistantReply(transcript);
const summaryPrefix = summary.slice(0, -1);
if (fullReply.length > summaryPrefix.length && fullReply.startsWith(summaryPrefix)) {
replies.set(entry, fullReply);
}
}));
return replies;
}
function buildCronRunMessage(
entry: CronRunLogEntry,
index: number,
fullReply?: string,
): CronSessionFallbackMessage | null {
const timestamp = normalizeTimestampMs(entry.ts) ?? normalizeTimestampMs(entry.runAtMs);
if (!timestamp) return null;
const status = typeof entry.status === 'string' ? entry.status.toLowerCase() : '';
const summary = typeof entry.summary === 'string' ? entry.summary.trim() : '';
const error = typeof entry.error === 'string' ? entry.error.trim() : '';
let content = summary || error;
let content = fullReply?.trim() || summary || error;
if (!content) {
content = status === 'error' ? 'Scheduled task failed.' : 'Scheduled task completed.';
}
@@ -117,14 +189,14 @@ function buildCronRunMessage(entry: CronRunLogEntry, index: number): CronSession
return {
id: `cron-run-${entry.sessionId ?? entry.ts ?? index}`,
role: status === 'error' ? 'system' : 'assistant',
role: 'assistant',
content,
timestamp,
...(status === 'error' ? { isError: true } : {}),
};
}
async function readCronRunLog(jobId: string): Promise<CronRunLogEntry[]> {
async function readLegacyCronRunLog(jobId: string): Promise<CronRunLogEntry[]> {
const logPath = join(getOpenClawConfigDir(), 'cron', 'runs', `${jobId}.jsonl`);
const raw = await readFile(logPath, 'utf8').catch(() => '');
if (!raw.trim()) return [];
@@ -145,6 +217,24 @@ async function readCronRunLog(jobId: string): Promise<CronRunLogEntry[]> {
return entries;
}
async function readCronRunHistory(
gatewayManager: GatewayManager,
jobId: string,
limit: number,
): Promise<CronRunLogEntry[]> {
try {
const result = await gatewayManager.rpc<{ entries?: CronRunLogEntry[] }>('cron.runs', {
id: jobId,
limit,
sortDir: 'asc',
}, 8000);
if (Array.isArray(result?.entries)) return result.entries;
} catch {
// OpenClaw versions before SQLite cron history may not expose cron.runs.
}
return readLegacyCronRunLog(jobId);
}
async function readSessionStoreEntry(
agentId: string,
sessionKey: string,
@@ -177,6 +267,7 @@ function buildCronSessionFallbackMessages(params: {
sessionKey: string;
job?: Pick<GatewayCronJob, 'name' | 'payload' | 'state'>;
runs: CronRunLogEntry[];
fullReplies?: Map<CronRunLogEntry, string>;
sessionEntry?: { label?: string; updatedAt?: number };
limit?: number;
}): CronSessionFallbackMessage[] {
@@ -204,18 +295,16 @@ function buildCronSessionFallbackMessages(params: {
: (normalizeTimestampMs(params.job?.state?.runningAtMs) ?? params.sessionEntry?.updatedAt);
if (taskName || prompt) {
const lines = [taskName ? `Scheduled task: ${taskName}` : 'Scheduled task'];
if (prompt) lines.push(`Prompt: ${prompt}`);
messages.push({
id: `cron-meta-${parsed.jobId}`,
role: 'system',
content: lines.join('\n'),
role: 'user',
content: prompt || taskName,
timestamp: Math.max(0, (firstRelevantTimestamp ?? Date.now()) - 1),
});
}
matchingRuns.forEach((entry, index) => {
const message = buildCronRunMessage(entry, index);
const message = buildCronRunMessage(entry, index, params.fullReplies?.get(entry));
if (message) messages.push(message);
});
@@ -224,17 +313,10 @@ function buildCronSessionFallbackMessages(params: {
if (runningAt) {
messages.push({
id: `cron-running-${parsed.jobId}`,
role: 'system',
role: 'assistant',
content: 'This scheduled task is still running in OpenClaw, but no chat transcript is available yet.',
timestamp: runningAt,
});
} else if (messages.length === 0) {
messages.push({
id: `cron-empty-${parsed.jobId}`,
role: 'system',
content: 'No chat transcript is available for this scheduled task yet.',
timestamp: params.sessionEntry?.updatedAt ?? Date.now(),
});
}
}
@@ -292,6 +374,35 @@ function normalizeCronSchedule(schedule: GatewayCronJob['schedule']): CronJob['s
return typeof schedule.expr === 'string' ? schedule.expr : '';
}
/**
* Normalize a UI-supplied schedule (plain cron string or structured CronSchedule)
* into the structured form the Gateway expects. Plain strings become a cron
* schedule; structured `at` / `every` / `cron` objects pass through after a
* minimal shape check.
*/
function normalizeScheduleInput(schedule: unknown): CronSchedule {
if (typeof schedule === 'string') {
return { kind: 'cron', expr: schedule };
}
if (schedule && typeof schedule === 'object') {
const record = schedule as Record<string, unknown>;
if (record.kind === 'at' && typeof record.at === 'string' && record.at.trim()) {
return { kind: 'at', at: record.at };
}
if (record.kind === 'every' && typeof record.everyMs === 'number' && Number.isFinite(record.everyMs)) {
return {
kind: 'every',
everyMs: record.everyMs,
...(typeof record.anchorMs === 'number' ? { anchorMs: record.anchorMs } : {}),
};
}
if (record.kind === 'cron' && typeof record.expr === 'string') {
return { kind: 'cron', expr: record.expr, ...(typeof record.tz === 'string' && record.tz ? { tz: record.tz } : {}) };
}
}
throw new Error('Invalid schedule: expected a cron expression string or a CronSchedule object');
}
function normalizeCronDeliveryPatch(rawDelivery: unknown): Record<string, unknown> {
if (!rawDelivery || typeof rawDelivery !== 'object') return {};
@@ -312,7 +423,7 @@ function normalizeCronDeliveryPatch(rawDelivery: unknown): Record<string, unknow
function buildCronUpdatePatch(input: Record<string, unknown>): Record<string, unknown> {
const patch = { ...input };
if (typeof patch.schedule === 'string') patch.schedule = { kind: 'cron', expr: patch.schedule };
if ('schedule' in patch && patch.schedule !== undefined) patch.schedule = normalizeScheduleInput(patch.schedule);
if (typeof patch.message === 'string') {
patch.payload = { kind: 'agentTurn', message: patch.message };
delete patch.message;
@@ -481,7 +592,7 @@ export function createCronApi({ gatewayManager }: { gatewayManager: GatewayManag
}
const result = await gatewayManager.rpc('cron.add', {
name: input.name,
schedule: { kind: 'cron', expr: input.schedule },
schedule: normalizeScheduleInput(input.schedule),
payload: { kind: 'agentTurn', message: input.message },
enabled: typeof input.enabled === 'boolean' ? input.enabled : true,
wakeMode: 'next-heartbeat',
@@ -540,16 +651,18 @@ export function createCronApi({ gatewayManager }: { gatewayManager: GatewayManag
const [jobsResult, runs, sessionEntry] = await Promise.all([
gatewayManager.rpc('cron.list', { includeDisabled: true }, 8000)
.catch(() => ({ jobs: [] as GatewayCronJob[] })),
readCronRunLog(parsedSession.jobId),
readCronRunHistory(gatewayManager, parsedSession.jobId, limit),
readSessionStoreEntry(parsedSession.agentId, sessionKey),
]);
const jobs = (jobsResult as { jobs?: GatewayCronJob[] }).jobs ?? [];
const job = jobs.find((item) => item.id === parsedSession.jobId);
const fullReplies = await loadFullCronRunReplies(parsedSession, runs);
return {
messages: buildCronSessionFallbackMessages({
sessionKey,
job,
runs,
fullReplies,
sessionEntry: sessionEntry ? {
label: typeof sessionEntry.label === 'string' ? sessionEntry.label : undefined,
updatedAt: normalizeTimestampMs(sessionEntry.updatedAt),
+3
View File
@@ -6,6 +6,7 @@ import { logger } from '../utils/logger';
import { getOpenClawConfigDir } from '../utils/paths';
import { buildGatewayHealthSummary } from '../utils/gateway-health';
import { buildChannelAccountsView, getChannelStatusDiagnostics } from './channels-api';
import { getAcpTraceSnapshot, recordRendererAcpTrace } from './acp-trace';
const DEFAULT_TAIL_LINES = 200;
@@ -79,5 +80,7 @@ export function createDiagnosticsApi(ctx: DiagnosticsApiContext): CompleteHostSe
gatewayErrLogTail: await readTail(join(openClawDir, 'logs', 'gateway.err.log')),
};
},
acpTrace: async () => getAcpTraceSnapshot(),
recordAcpTrace: async (payload) => recordRendererAcpTrace(payload),
};
}
+603 -31
View File
@@ -1,14 +1,44 @@
import { app, nativeImage } from 'electron';
import { app, nativeImage, shell } from 'electron';
import crypto from 'node:crypto';
import { constants } from 'node:fs';
import type { Stats } from 'node:fs';
import type { FileHandle } from 'node:fs/promises';
import { homedir } from 'node:os';
import { basename, extname, join, relative, resolve, sep } from 'node:path';
import {
basename,
dirname,
extname,
isAbsolute,
join,
posix,
relative,
resolve,
sep,
win32,
} from 'node:path';
import type {
FilePreviewError,
FilePreviewTreeNode,
FilePreviewTreeOptions,
FileReadBinaryOptions,
WorkspaceNativeFileError,
WorkspaceFileRef,
} from '@shared/host-api/contract';
import {
FILE_PREVIEW_MAX_BINARY_BYTES,
FILE_PREVIEW_MAX_TEXT_BYTES,
} from '@shared/file-preview/limits';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import { expandPath } from '../utils/paths';
import { expandPath, resolveOpenClawStateDir } from '../utils/paths';
import {
resolveClawXStagingDir,
type AttachmentAccess,
type StagedAttachmentRegistry,
} from './attachment-access';
import {
HANDLER_ID_MAX_LENGTH,
type AttachmentOpenWithService,
} from './attachment-open-with';
import { isRecord } from './payload-utils';
const EXT_MIME_MAP: Record<string, string> = {
@@ -54,10 +84,7 @@ const EXT_MIME_MAP: Record<string, string> = {
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
};
const OUTBOUND_DIR = join(homedir(), '.openclaw', 'media', 'outbound');
const DIRECTORY_MIME_TYPE = 'application/x-directory';
const FILE_PREVIEW_MAX_TEXT_BYTES = 2 * 1024 * 1024;
const FILE_PREVIEW_MAX_BINARY_BYTES = 50 * 1024 * 1024;
const FILE_PREVIEW_TREE_MAX_DEPTH = 6;
const FILE_PREVIEW_TREE_MAX_NODES = 5000;
const FILE_PREVIEW_DIR_BLACKLIST = new Set([
@@ -93,6 +120,44 @@ type ResolvedSandboxedPath = {
readOnly: boolean;
};
type ResolvedWorkspaceTarget = {
root: string;
target: string;
};
type OpenWorkspaceTarget = ResolvedWorkspaceTarget & {
handle: FileHandle;
stat: Stats;
};
type WorkspaceFs = {
open: (path: string, flags: number) => Promise<FileHandle>;
realpath: (path: string) => Promise<string>;
stat: (path: string) => Promise<Stats>;
};
type FilesApiDependencies = {
workspaceFs?: WorkspaceFs;
attachmentAccess?: AttachmentAccess;
openWith?: AttachmentOpenWithService;
stagedAttachments?: StagedAttachmentRegistry;
stagingHooks?: {
beforeDestinationOpen?: (input: { stagingDir: string; destinationPath: string }) => Promise<void>;
};
};
type PinnedStagingDirectory = {
lexicalPath: string;
canonicalPath: string;
dev: number;
ino: number;
};
type PinnedStagingArea = {
stagingDir: string;
directories: PinnedStagingDirectory[];
};
function getMimeType(ext: string): string {
return EXT_MIME_MAP[ext.toLowerCase()] || 'application/octet-stream';
}
@@ -124,6 +189,24 @@ async function generateImagePreview(filePath: string, mimeType: string): Promise
}
}
function generateImageBufferPreview(buffer: Buffer, mimeType: string): string | null {
try {
const img = nativeImage.createFromBuffer(buffer);
if (img.isEmpty()) return null;
const size = img.getSize();
const maxDim = 512;
if (size.width > maxDim || size.height > maxDim) {
const resized = size.width >= size.height
? img.resize({ width: maxDim })
: img.resize({ height: maxDim });
return `data:image/png;base64,${resized.toPNG().toString('base64')}`;
}
return `data:${mimeType};base64,${buffer.toString('base64')}`;
} catch {
return null;
}
}
function requirePath(payload: unknown): string {
const path = isRecord(payload) ? payload.path : payload;
if (typeof path !== 'string' || !path.trim()) {
@@ -132,15 +215,165 @@ function requirePath(payload: unknown): string {
return path;
}
function isPathInside(child: string, parent: string): boolean {
const c = resolve(child);
const p = resolve(parent);
if (process.platform === 'win32') {
const cl = c.toLowerCase();
const pl = p.toLowerCase();
return cl === pl || cl.startsWith(pl + sep);
export function isPathInside(
child: string,
parent: string,
platform: NodeJS.Platform = process.platform,
): boolean {
const pathApi = platform === 'win32' ? win32 : posix;
const c = pathApi.resolve(child);
const p = pathApi.resolve(parent);
const childFromParent = pathApi.relative(p, c);
return childFromParent === ''
|| (!childFromParent.startsWith(`..${pathApi.sep}`)
&& childFromParent !== '..'
&& !pathApi.isAbsolute(childFromParent));
}
function workspaceError(error: unknown): FilePreviewError {
const message = error instanceof Error ? error.message : String(error);
if (message === 'outsideSandbox' || message === 'notFound' || message === 'notDirectory') {
return message;
}
return c === p || c.startsWith(p + sep);
const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
if (code === 'ENOENT') return 'notFound';
if (code === 'ENOTDIR') return 'notDirectory';
if (code === 'ELOOP') return 'outsideSandbox';
return 'operationFailed';
}
function workspaceNativeError(error: unknown): WorkspaceNativeFileError {
const message = error instanceof Error ? error.message : String(error);
if (message === 'outsideSandbox' || message === 'notFound' || message === 'notFile') {
return message;
}
const mapped = workspaceError(error);
if (mapped === 'outsideSandbox') return 'outsideSandbox';
if (mapped === 'notFound') return 'notFound';
return 'operationFailed';
}
function isSamePath(left: string, right: string): boolean {
const normalizedLeft = resolve(left);
const normalizedRight = resolve(right);
return process.platform === 'win32'
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
: normalizedLeft === normalizedRight;
}
async function resolveWorkspaceTarget(
ref: WorkspaceFileRef,
fsP: WorkspaceFs,
): Promise<ResolvedWorkspaceTarget> {
if (!ref || typeof ref.workspaceRoot !== 'string' || !ref.workspaceRoot.trim()
|| typeof ref.relativePath !== 'string' || !ref.relativePath.trim()) {
throw new Error('outsideSandbox');
}
const relativePath = ref.relativePath;
if (isAbsolute(relativePath) || posix.isAbsolute(relativePath) || win32.isAbsolute(relativePath)
|| relativePath.split(/[\\/]+/).includes('..')) {
throw new Error('outsideSandbox');
}
let root: string;
try {
root = await fsP.realpath(expandPath(ref.workspaceRoot));
if (!(await fsP.stat(root)).isDirectory()) throw new Error('outsideSandbox');
} catch (error) {
if (error instanceof Error && error.message === 'outsideSandbox') throw error;
throw new Error('outsideSandbox', { cause: error });
}
const candidate = resolve(root, relativePath);
if (!isPathInside(candidate, root)) throw new Error('outsideSandbox');
try {
const target = await fsP.realpath(candidate);
if (!isPathInside(target, root)) throw new Error('outsideSandbox');
return { root, target };
} catch (error) {
if (error instanceof Error && error.message === 'outsideSandbox') throw error;
if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') throw error;
}
let parent = dirname(candidate);
while (true) {
try {
const existingParent = await fsP.realpath(parent);
if (!isPathInside(existingParent, root)) throw new Error('outsideSandbox');
throw new Error('notFound');
} catch (error) {
if (error instanceof Error && (error.message === 'outsideSandbox' || error.message === 'notFound')) {
throw error;
}
if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') throw error;
const nextParent = dirname(parent);
if (nextParent === parent) throw new Error('outsideSandbox', { cause: error });
parent = nextParent;
}
}
}
async function revalidateWorkspaceTarget(
resolvedTarget: ResolvedWorkspaceTarget,
fsP: WorkspaceFs,
): Promise<string> {
const root = await fsP.realpath(resolvedTarget.root);
if (!isSamePath(root, resolvedTarget.root)) throw new Error('outsideSandbox');
if (!(await fsP.stat(root)).isDirectory()) throw new Error('outsideSandbox');
const target = await fsP.realpath(resolvedTarget.target);
if (!isSamePath(target, resolvedTarget.target) || !isPathInside(target, root)) {
throw new Error('outsideSandbox');
}
return target;
}
async function resolveWorkspaceRegularFile(
ref: WorkspaceFileRef,
fsP: WorkspaceFs,
): Promise<string> {
const resolvedTarget = await resolveWorkspaceTarget(ref, fsP);
if (!(await fsP.stat(resolvedTarget.target)).isFile()) throw new Error('notFile');
return resolvedTarget.target;
}
async function openWorkspaceTarget(ref: WorkspaceFileRef, fsP: WorkspaceFs): Promise<OpenWorkspaceTarget> {
const resolvedTarget = await resolveWorkspaceTarget(ref, fsP);
let handle: FileHandle | undefined;
try {
const noFollow = process.platform === 'win32' ? 0 : constants.O_NOFOLLOW;
handle = await fsP.open(resolvedTarget.target, constants.O_RDONLY | noFollow);
const stat = await handle.stat();
const target = await revalidateWorkspaceTarget(resolvedTarget, fsP);
const pathStat = await fsP.stat(target);
if (stat.dev !== pathStat.dev || stat.ino !== pathStat.ino) {
throw new Error('outsideSandbox');
}
return { ...resolvedTarget, handle, stat };
} catch (error) {
await handle?.close().catch(() => undefined);
throw error;
}
}
async function readOpenedFile(handle: FileHandle, maxBytes: number): Promise<Buffer | null> {
const chunks: Buffer[] = [];
let total = 0;
while (total <= maxBytes) {
const length = Math.min(64 * 1024, maxBytes + 1 - total);
const chunk = Buffer.allocUnsafe(length);
const { bytesRead } = await handle.read(chunk, 0, length, total);
if (bytesRead === 0) break;
chunks.push(chunk.subarray(0, bytesRead));
total += bytesRead;
}
return total > maxBytes ? null : Buffer.concat(chunks, total);
}
function getWorkspaceBinaryCap(value: unknown): number {
const maxBytes = typeof value === 'number' && Number.isFinite(value) ? value : undefined;
return Math.max(1, Math.min(maxBytes ?? FILE_PREVIEW_MAX_BINARY_BYTES, FILE_PREVIEW_MAX_BINARY_BYTES));
}
function getFilePreviewWriteRoots(): string[] {
@@ -151,7 +384,7 @@ function getFilePreviewWriteRoots(): string[] {
} catch {
// ignore
}
roots.push(resolve(OUTBOUND_DIR));
roots.push(resolve(resolveClawXStagingDir()));
return roots;
}
@@ -207,7 +440,165 @@ function getBinaryOptions(opts: unknown): FileReadBinaryOptions {
return isRecord(opts) ? opts as FileReadBinaryOptions : {};
}
export function createFilesApi(): CompleteHostServiceRegistry['files'] {
export function createFilesApi(dependencies: FilesApiDependencies = {}): CompleteHostServiceRegistry['files'] {
const getWorkspaceFs = async (): Promise<WorkspaceFs> => dependencies.workspaceFs
?? await import('node:fs/promises');
const stagingAreaName = `clawx-${process.pid}-${crypto.randomUUID()}`;
let stagingAreaPromise: Promise<PinnedStagingArea> | null = null;
const initializeStagingArea = async (): Promise<PinnedStagingArea> => {
const fsP = await import('node:fs/promises');
const directories: PinnedStagingDirectory[] = [];
const ensureDirectory = async (lexicalPath: string, parent?: PinnedStagingDirectory) => {
let entryStat: Stats;
try {
entryStat = await fsP.lstat(lexicalPath);
} catch (error) {
const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
if (code !== 'ENOENT') throw error;
await fsP.mkdir(lexicalPath, { mode: 0o700 });
entryStat = await fsP.lstat(lexicalPath);
}
if (entryStat.isSymbolicLink() || !entryStat.isDirectory()) {
throw new Error('Invalid ClawX staging directory');
}
const canonicalPath = await fsP.realpath(lexicalPath);
const canonicalStat = await fsP.stat(canonicalPath);
if (!canonicalStat.isDirectory()
|| (parent && !isPathInside(canonicalPath, parent.canonicalPath))) {
throw new Error('Invalid ClawX staging directory');
}
const pinned = {
lexicalPath,
canonicalPath,
dev: canonicalStat.dev,
ino: canonicalStat.ino,
};
directories.push(pinned);
return pinned;
};
const stateDir = await ensureDirectory(resolveOpenClawStateDir());
const mediaDir = await ensureDirectory(join(stateDir.canonicalPath, 'media'), stateDir);
const outboundDir = await ensureDirectory(join(mediaDir.canonicalPath, 'outbound'), mediaDir);
const stagingRoot = await ensureDirectory(join(outboundDir.canonicalPath, 'clawx-staging'), outboundDir);
const stagingArea = await ensureDirectory(join(stagingRoot.canonicalPath, stagingAreaName), stagingRoot);
return { stagingDir: stagingArea.canonicalPath, directories };
};
const getStagingArea = () => {
stagingAreaPromise ??= initializeStagingArea();
return stagingAreaPromise;
};
const verifyStagingArea = async (area: PinnedStagingArea) => {
const fsP = await import('node:fs/promises');
for (const directory of area.directories) {
const entryStat = await fsP.lstat(directory.lexicalPath);
if (entryStat.isSymbolicLink()) throw new Error('Invalid ClawX staging directory');
const currentPath = await fsP.realpath(directory.lexicalPath);
const currentStat = await fsP.stat(currentPath);
if (!currentStat.isDirectory()
|| !isSamePath(currentPath, directory.canonicalPath)
|| currentStat.dev !== directory.dev
|| currentStat.ino !== directory.ino) {
throw new Error('Invalid ClawX staging directory');
}
}
};
const cleanupOwnedDestination = async (destinationPath: string, identity?: { dev: number; ino: number }) => {
if (!identity) return;
const fsP = await import('node:fs/promises');
try {
const current = await fsP.stat(destinationPath);
if (current.dev === identity.dev && current.ino === identity.ino) {
await fsP.unlink(destinationPath);
}
} catch {
// The destination was already removed or redirected again.
}
};
const createStagedFile = async (
fileName: string,
write: (handle: FileHandle) => Promise<void>,
): Promise<{ path: string; stat: Stats }> => {
const fsP = await import('node:fs/promises');
const area = await getStagingArea();
await verifyStagingArea(area);
const destinationPath = join(area.stagingDir, fileName);
await dependencies.stagingHooks?.beforeDestinationOpen?.({
stagingDir: area.stagingDir,
destinationPath,
});
let handle: FileHandle | undefined;
let identity: { dev: number; ino: number } | undefined;
try {
const noFollow = process.platform === 'win32' ? 0 : constants.O_NOFOLLOW;
handle = await fsP.open(
destinationPath,
constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow,
0o600,
);
const openedStat = await handle.stat();
identity = { dev: openedStat.dev, ino: openedStat.ino };
// Node has no openat. Validate the unpredictable empty destination before writing bytes.
await verifyStagingArea(area);
const canonicalDestination = await fsP.realpath(destinationPath);
const pathStat = await fsP.stat(canonicalDestination);
if (!isPathInside(canonicalDestination, area.stagingDir)
|| pathStat.dev !== openedStat.dev
|| pathStat.ino !== openedStat.ino) {
throw new Error('Invalid ClawX staging destination');
}
await write(handle);
const finalStat = await handle.stat();
await verifyStagingArea(area);
const finalPath = await fsP.realpath(destinationPath);
const finalPathStat = await fsP.stat(finalPath);
if (!isSamePath(finalPath, canonicalDestination)
|| finalPathStat.dev !== finalStat.dev
|| finalPathStat.ino !== finalStat.ino) {
throw new Error('Invalid ClawX staging destination');
}
await handle.close();
handle = undefined;
await verifyStagingArea(area);
const registrationPath = await fsP.realpath(destinationPath);
const registrationStat = await fsP.stat(registrationPath);
if (!isSamePath(registrationPath, finalPath)
|| registrationStat.dev !== finalStat.dev
|| registrationStat.ino !== finalStat.ino) {
throw new Error('Invalid ClawX staging destination');
}
return { path: registrationPath, stat: finalStat };
} catch (error) {
await handle?.close().catch(() => undefined);
await cleanupOwnedDestination(destinationPath, identity);
throw error;
}
};
const copyIntoHandle = async (sourcePath: string, destination: FileHandle) => {
const fsP = await import('node:fs/promises');
const source = await fsP.open(sourcePath, constants.O_RDONLY);
try {
const buffer = Buffer.allocUnsafe(64 * 1024);
let position = 0;
while (true) {
const { bytesRead } = await source.read(buffer, 0, buffer.length, position);
if (bytesRead === 0) break;
await destination.write(buffer, 0, bytesRead, position);
position += bytesRead;
}
} finally {
await source.close();
}
};
return {
stagePaths: async (payload) => {
const body = isRecord(payload) ? payload as StagePathsPayload : {};
@@ -215,34 +606,35 @@ export function createFilesApi(): CompleteHostServiceRegistry['files'] {
? body.filePaths.filter((value): value is string => typeof value === 'string')
: [];
const fsP = await import('node:fs/promises');
await fsP.mkdir(OUTBOUND_DIR, { recursive: true });
const results = [];
for (const filePath of filePaths) {
const id = crypto.randomUUID();
const fileName = basename(filePath);
const sourceStat = await fsP.stat(filePath);
if (sourceStat.isDirectory()) {
const canonicalPath = await fsP.realpath(filePath);
const canonicalStat = await fsP.stat(canonicalPath);
if (!canonicalStat.isDirectory()) throw new Error('Invalid directory attachment');
dependencies.stagedAttachments?.register(id, canonicalPath, filePath);
results.push({
id,
fileName,
mimeType: DIRECTORY_MIME_TYPE,
fileSize: 0,
stagedPath: filePath,
stagedPath: canonicalPath,
preview: null,
});
continue;
}
const ext = extname(filePath);
const stagedPath = join(OUTBOUND_DIR, `${id}${ext}`);
await fsP.copyFile(filePath, stagedPath);
const s = await fsP.stat(stagedPath);
const mimeType = getMimeType(ext);
const preview = mimeType.startsWith('image/')
? await generateImagePreview(stagedPath, mimeType)
? await generateImagePreview(filePath, mimeType)
: null;
results.push({ id, fileName, mimeType, fileSize: s.size, stagedPath, preview });
const staged = await createStagedFile(`${id}${ext}`, (handle) => copyIntoHandle(filePath, handle));
dependencies.stagedAttachments?.register(id, staged.path, filePath);
results.push({ id, fileName, mimeType, fileSize: staged.stat.size, stagedPath: staged.path, preview });
}
return results;
},
@@ -251,29 +643,209 @@ export function createFilesApi(): CompleteHostServiceRegistry['files'] {
if (typeof body.base64 !== 'string' || typeof body.fileName !== 'string') {
throw new Error('Invalid staged buffer payload');
}
const fsP = await import('node:fs/promises');
await fsP.mkdir(OUTBOUND_DIR, { recursive: true });
const id = crypto.randomUUID();
const payloadMimeType = typeof body.mimeType === 'string' ? body.mimeType : '';
const ext = extname(body.fileName) || mimeToExt(payloadMimeType);
const stagedPath = join(OUTBOUND_DIR, `${id}${ext}`);
const buffer = Buffer.from(body.base64, 'base64');
await fsP.writeFile(stagedPath, buffer);
const mimeType = payloadMimeType || getMimeType(ext);
const preview = mimeType.startsWith('image/')
? await generateImagePreview(stagedPath, mimeType)
? generateImageBufferPreview(buffer, mimeType)
: null;
const staged = await createStagedFile(`${id}${ext}`, async (handle) => {
await handle.writeFile(buffer);
});
dependencies.stagedAttachments?.register(id, staged.path);
return {
id,
fileName: body.fileName,
mimeType,
fileSize: buffer.length,
stagedPath,
stagedPath: staged.path,
preview,
};
},
resolveWorkspaceContext: async (input) => {
if (!input || typeof input.workspaceRoot !== 'string' || !input.workspaceRoot.trim()
|| typeof input.executionCwd !== 'string' || !input.executionCwd.trim()) {
return { ok: false, error: 'outsideSandbox' };
}
const fsP = await getWorkspaceFs();
try {
const [workspaceRoot, executionCwd] = await Promise.all([
fsP.realpath(expandPath(input.workspaceRoot)),
fsP.realpath(expandPath(input.executionCwd)),
]);
const [rootStat, cwdStat] = await Promise.all([
fsP.stat(workspaceRoot),
fsP.stat(executionCwd),
]);
if (!rootStat.isDirectory() || !cwdStat.isDirectory()) {
return { ok: false, error: 'notDirectory' };
}
if (!isPathInside(executionCwd, workspaceRoot)) {
return { ok: false, error: 'outsideSandbox' };
}
return { ok: true, workspaceRoot, executionCwd };
} catch (error) {
return { ok: false, error: workspaceError(error) };
}
},
readWorkspaceText: async (ref) => {
let opened: OpenWorkspaceTarget | undefined;
try {
opened = await openWorkspaceTarget(ref, await getWorkspaceFs());
const { stat, target } = opened;
if (!stat.isFile()) return { ok: false, error: 'notFound' };
if (stat.size > FILE_PREVIEW_MAX_TEXT_BYTES) {
return { ok: false, error: 'tooLarge', size: stat.size };
}
const buf = await readOpenedFile(opened.handle, FILE_PREVIEW_MAX_TEXT_BYTES);
if (!buf) return { ok: false, error: 'tooLarge', size: FILE_PREVIEW_MAX_TEXT_BYTES + 1 };
if (looksLikeBinary(buf)) return { ok: false, error: 'binary', size: buf.length };
return {
ok: true,
content: buf.toString('utf8'),
mimeType: getMimeType(extname(target)),
size: buf.length,
readOnly: true,
};
} catch (error) {
return { ok: false, error: workspaceError(error) };
} finally {
await opened?.handle.close().catch(() => undefined);
}
},
readWorkspaceBinary: async (input) => {
let opened: OpenWorkspaceTarget | undefined;
try {
opened = await openWorkspaceTarget(input, await getWorkspaceFs());
const { stat, target } = opened;
if (!stat.isFile()) return { ok: false, error: 'notFound' };
const cap = getWorkspaceBinaryCap(input.maxBytes);
if (stat.size > cap) return { ok: false, error: 'tooLarge', size: stat.size };
const buf = await readOpenedFile(opened.handle, cap);
if (!buf) return { ok: false, error: 'tooLarge', size: cap + 1 };
return {
ok: true,
data: new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength),
mimeType: getMimeType(extname(target)),
size: buf.length,
readOnly: true,
};
} catch (error) {
return { ok: false, error: workspaceError(error) };
} finally {
await opened?.handle.close().catch(() => undefined);
}
},
statWorkspaceFile: async (ref) => {
let opened: OpenWorkspaceTarget | undefined;
try {
opened = await openWorkspaceTarget(ref, await getWorkspaceFs());
const { stat } = opened;
return {
ok: true,
size: stat.size,
mtime: stat.mtimeMs,
isFile: stat.isFile(),
isDir: stat.isDirectory(),
readOnly: true,
};
} catch (error) {
return { ok: false, error: workspaceError(error) };
} finally {
await opened?.handle.close().catch(() => undefined);
}
},
listWorkspaceOpenHandlers: async (ref) => {
try {
const openWith = dependencies.openWith;
if (!openWith) throw new Error('operationFailed');
const target = await resolveWorkspaceRegularFile(ref, await getWorkspaceFs());
if (openWith.platform === 'linux') {
return { ok: true, platform: 'linux', handlers: [] };
}
const handlers = await openWith.list(target);
return {
ok: true,
platform: openWith.platform,
handlers: handlers.map(({ id, name, iconDataUrl, isDefault }) => ({
handlerId: id,
name,
...(iconDataUrl ? { iconDataUrl } : {}),
isDefault,
})),
};
} catch (error) {
return { ok: false, error: workspaceNativeError(error) };
}
},
openWorkspaceWith: async (payload) => {
try {
const openWith = dependencies.openWith;
if (!openWith) throw new Error('operationFailed');
const fsP = await getWorkspaceFs();
const target = await resolveWorkspaceRegularFile(payload?.ref, fsP);
if (typeof payload?.handlerId !== 'string'
|| !payload.handlerId.trim()
|| payload.handlerId.length > HANDLER_ID_MAX_LENGTH) {
throw new Error('operationFailed');
}
if (openWith.platform === 'linux') {
return { ok: false, error: 'unsupportedPlatform' };
}
await openWith.open(
target,
payload.handlerId,
() => resolveWorkspaceRegularFile(payload.ref, fsP),
);
return { ok: true };
} catch (error) {
return { ok: false, error: workspaceNativeError(error) };
}
},
revealWorkspaceFile: async (ref) => {
try {
const fsP = await getWorkspaceFs();
await resolveWorkspaceRegularFile(ref, fsP);
const target = await resolveWorkspaceRegularFile(ref, fsP);
shell.showItemInFolder(target);
return { ok: true };
} catch (error) {
return { ok: false, error: workspaceNativeError(error) };
}
},
resolveAttachment: async (payload) => dependencies.attachmentAccess?.resolveAttachment(payload) ?? {
ok: false,
displayName: 'attachment',
error: 'operationFailed',
},
readAttachmentText: async (ref) => dependencies.attachmentAccess?.readAttachmentText(ref) ?? {
ok: false,
error: 'operationFailed',
},
readAttachmentBinary: async (payload) => dependencies.attachmentAccess?.readAttachmentBinary(payload) ?? {
ok: false,
error: 'operationFailed',
},
openAttachment: async (ref) => dependencies.attachmentAccess?.openAttachment(ref) ?? {
ok: false,
error: 'operationFailed',
},
listAttachmentOpenHandlers: async (ref) => dependencies.attachmentAccess
?.listAttachmentOpenHandlers(ref) ?? {
ok: false,
error: 'operationFailed',
},
openAttachmentWith: async (payload) => dependencies.attachmentAccess?.openAttachmentWith(payload) ?? {
ok: false,
error: 'operationFailed',
},
revealAttachment: async (ref) => dependencies.attachmentAccess?.revealAttachment(ref) ?? {
ok: false,
error: 'operationFailed',
},
readText: async (payload) => {
try {
const { realPath: real, readOnly } = await resolveSandboxedPath(requirePath(payload), 'read');
+9 -21
View File
@@ -1,8 +1,8 @@
import type { GatewayManager } from '../gateway/manager';
import type { GatewayRpcBackpressure } from '../gateway/rpc-backpressure';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import { PORTS } from '../utils/config';
import { scheduleControlUiDeviceAutoApproval } from '../utils/control-ui-device-pairing';
import { approvePendingLocalDeviceRequests } from '../utils/control-ui-device-pairing';
import { logger } from '../utils/logger';
import { buildOpenClawControlUiUrl } from '../utils/openclaw-control-ui';
import { getSetting } from '../utils/store';
import { isRecord } from './payload-utils';
@@ -11,10 +11,6 @@ type HealthPayload = {
probe?: unknown;
};
type ControlUiPayload = {
view?: unknown;
};
type RpcPayload = {
method?: unknown;
params?: unknown;
@@ -29,10 +25,7 @@ function parseTimeoutMs(timeoutMs: unknown): number | undefined {
return timeoutMs;
}
export function createGatewayApi(
gatewayManager: GatewayManager,
gatewayRpcBackpressure: GatewayRpcBackpressure,
): CompleteHostServiceRegistry['gateway'] {
export function createGatewayApi(gatewayManager: GatewayManager): CompleteHostServiceRegistry['gateway'] {
return {
status: () => gatewayManager.getStatus(),
start: async () => {
@@ -51,14 +44,14 @@ export function createGatewayApi(
const body = isRecord(payload) ? payload as HealthPayload : {};
return gatewayManager.checkHealth({ probe: body.probe === true });
},
controlUi: async (payload) => {
const body = isRecord(payload) ? payload as ControlUiPayload : {};
controlUi: async () => {
const status = gatewayManager.getStatus();
const token = await getSetting('gatewayToken');
const port = status.port || PORTS.OPENCLAW_GATEWAY;
const view = body.view === 'dreams' ? 'dreams' : undefined;
const url = buildOpenClawControlUiUrl(port, token, { view });
scheduleControlUiDeviceAutoApproval(gatewayManager);
const url = buildOpenClawControlUiUrl(port, token);
void approvePendingLocalDeviceRequests(gatewayManager).catch((error) => {
logger.debug(`[gateway] Control UI device auto-approve skipped: ${String(error)}`);
});
return { success: true, url, token, port };
},
rpc: async (payload) => {
@@ -68,12 +61,7 @@ export function createGatewayApi(
throw new Error('Invalid gateway RPC method');
}
const timeoutMs = parseTimeoutMs(body.timeoutMs);
return gatewayRpcBackpressure.run(
method,
body.params,
timeoutMs,
(rpcMethod, rpcParams, rpcTimeoutMs) => gatewayManager.rpc(rpcMethod, rpcParams, rpcTimeoutMs),
);
return gatewayManager.rpc(method, body.params, timeoutMs);
},
};
}
+64 -23
View File
@@ -2,6 +2,9 @@ import { dialog, nativeImage } from 'electron';
import { homedir } from 'node:os';
import { join } from 'node:path';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import type { AttachmentFileRef } from '@shared/host-api/contract';
import { resolveOutgoingMediaAttachment, type AttachmentAccess } from './attachment-access';
import { resolveOpenClawStateDir } from '../utils/paths';
import {
CLAWX_OPENAI_IMAGE_DEFAULT_MODEL,
CLAWX_OPENAI_IMAGE_PROVIDER_KEY,
@@ -19,9 +22,17 @@ import { isRecord } from './payload-utils';
type ThumbnailEntry = {
filePath?: unknown;
gatewayUrl?: unknown;
attachmentFileRef?: unknown;
key?: unknown;
mimeType?: unknown;
};
type MediaApiDependencies = {
attachmentAccess?: Pick<AttachmentAccess, 'resolveAttachment' | 'readAttachmentBinary'>;
};
const OPAQUE_ATTACHMENT_KEY = /^[a-f0-9]{64}$/;
type SaveImagePayload = {
base64?: unknown;
mimeType?: unknown;
@@ -62,28 +73,22 @@ async function generateImagePreview(filePath: string, mimeType: string): Promise
}
}
async function resolveOutgoingMediaUrl(
gatewayUrl: string,
): Promise<{ path: string; mimeType: string } | null> {
function generateImagePreviewFromBuffer(buffer: Buffer, mimeType: string): string | null {
try {
const match = gatewayUrl.match(/\/api\/chat\/media\/outgoing\/[^/]+\/([^/]+)\//);
if (!match) return null;
const attachmentId = decodeURIComponent(match[1]);
if (!/^[A-Za-z0-9._-]+$/.test(attachmentId)) return null;
const recordPath = join(homedir(), '.openclaw', 'media', 'outgoing', 'records', `${attachmentId}.json`);
const fsP = await import('node:fs/promises');
const raw = await fsP.readFile(recordPath, 'utf8');
const record = JSON.parse(raw) as {
original?: { path?: string; contentType?: string };
};
const original = record?.original;
if (!original?.path) return null;
return {
path: original.path,
mimeType: typeof original.contentType === 'string' && original.contentType
? original.contentType
: 'application/octet-stream',
};
if (mimeType === 'image/svg+xml') {
return `data:${mimeType};base64,${buffer.toString('base64')}`;
}
const img = nativeImage.createFromBuffer(buffer);
if (img.isEmpty()) return null;
const size = img.getSize();
const maxDim = 512;
if (size.width > maxDim || size.height > maxDim) {
const resized = size.width >= size.height
? img.resize({ width: maxDim })
: img.resize({ height: maxDim });
return `data:image/png;base64,${resized.toPNG().toString('base64')}`;
}
return `data:${mimeType};base64,${buffer.toString('base64')}`;
} catch {
return null;
}
@@ -94,7 +99,7 @@ function normalizeThumbnailEntries(payload: unknown): ThumbnailEntry[] {
return Array.isArray(value) ? value as ThumbnailEntry[] : [];
}
export function createMediaApi(): CompleteHostServiceRegistry['media'] {
export function createMediaApi(dependencies: MediaApiDependencies = {}): CompleteHostServiceRegistry['media'] {
return {
thumbnails: async (payload) => {
const entries = normalizeThumbnailEntries(payload);
@@ -102,6 +107,39 @@ export function createMediaApi(): CompleteHostServiceRegistry['media'] {
const results: Record<string, { preview: string | null; fileSize: number }> = {};
for (const entry of entries) {
const mimeType = typeof entry.mimeType === 'string' ? entry.mimeType : 'application/octet-stream';
if (entry.attachmentFileRef && typeof entry.attachmentFileRef === 'object') {
const key = typeof entry.key === 'string' && entry.key ? entry.key : null;
if (!key || !OPAQUE_ATTACHMENT_KEY.test(key) || !dependencies.attachmentAccess) continue;
const ref = entry.attachmentFileRef as AttachmentFileRef;
const resolution = await dependencies.attachmentAccess.resolveAttachment({ ref });
if (!resolution.ok
|| resolution.identity !== key
|| resolution.target.kind !== 'local') {
continue;
}
const readResult = await dependencies.attachmentAccess.readAttachmentBinary({
ref,
});
if (!readResult.ok) {
results[key] = { preview: null, fileSize: 0 };
continue;
}
const effectiveMimeType = mimeType === 'application/octet-stream'
? readResult.mimeType
: mimeType;
const buffer = Buffer.from(
readResult.data.buffer,
readResult.data.byteOffset,
readResult.data.byteLength,
);
results[key] = {
preview: effectiveMimeType.startsWith('image/')
? generateImagePreviewFromBuffer(buffer, effectiveMimeType)
: null,
fileSize: readResult.size,
};
continue;
}
if (typeof entry.filePath === 'string' && entry.filePath) {
try {
const stat = await fsP.stat(entry.filePath);
@@ -116,7 +154,10 @@ export function createMediaApi(): CompleteHostServiceRegistry['media'] {
}
if (typeof entry.gatewayUrl === 'string' && entry.gatewayUrl) {
const resolved = await resolveOutgoingMediaUrl(entry.gatewayUrl);
const resolved = await resolveOutgoingMediaAttachment({
uri: entry.gatewayUrl,
stateDir: resolveOpenClawStateDir(),
});
if (!resolved) {
results[entry.gatewayUrl] = { preview: null, fileSize: 0 };
continue;
+7 -4
View File
@@ -34,6 +34,7 @@ type ProviderPayload<Action extends keyof HostApiContract['providers']> =
type ValidationOptions = {
baseUrl?: string;
apiProtocol?: string;
modelId?: string;
};
function hasObjectChanges<T extends Record<string, unknown>>(
@@ -180,9 +181,11 @@ async function validateKey(payload: ProviderPayload<'validateKey'>): Promise<{ v
const registryBaseUrl = getProviderConfig(providerType)?.baseUrl;
const resolvedBaseUrl = options?.baseUrl || account?.baseUrl || legacyProvider?.baseUrl || registryBaseUrl;
const resolvedProtocol = options?.apiProtocol || account?.apiProtocol || legacyProvider?.apiProtocol;
const resolvedModelId = options?.modelId || account?.model || legacyProvider?.model;
return await validateApiKeyWithProvider(providerType, apiKey, {
baseUrl: resolvedBaseUrl,
apiProtocol: resolvedProtocol,
modelId: resolvedModelId,
});
} catch (error) {
return { valid: false, error: String(error) };
@@ -213,8 +216,8 @@ async function deleteProvider(payload: ProviderPayload<'delete'>, gatewayManager
const providerId = getProviderId(payload, 'delete');
try {
const existing = await providerService._getProviderInternal(providerId);
await providerService._deleteProviderInternal(providerId);
await syncDeletedProviderToRuntime(existing, providerId, gatewayManager);
await providerService._deleteProviderInternal(providerId);
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
@@ -369,12 +372,12 @@ async function deleteAccount(
? 'openai'
: undefined;
if (apiKeyOnly) {
await providerService._deleteProviderApiKeyInternal(accountId);
await syncDeletedProviderApiKeyToRuntime(
existing ? providerAccountToConfig(existing) : null,
accountId,
runtimeProviderKey,
);
await providerService._deleteProviderApiKeyInternal(accountId);
return { success: true };
}
const currentDefaultAccountId = await providerService.getDefaultAccountId();
@@ -382,10 +385,9 @@ async function deleteAccount(
? selectReplacementDefaultAccount(await providerService.listAccounts(), accountId)
: undefined;
await providerService.deleteAccount(accountId);
if (replacementDefault) {
await providerService.setDefaultAccount(replacementDefault.id);
await syncDefaultProviderToRuntime(replacementDefault.id);
await providerService.setDefaultAccount(replacementDefault.id);
}
await syncDeletedProviderToRuntime(
existing ? providerAccountToConfig(existing) : null,
@@ -393,6 +395,7 @@ async function deleteAccount(
gatewayManager,
runtimeProviderKey,
);
await providerService.deleteAccount(accountId);
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
@@ -30,7 +30,7 @@ import { listAgentsSnapshot } from '../../utils/agent-config';
/** OpenClaw Codex OAuth hooks only apply to the canonical `openai` provider id. */
const OPENAI_OAUTH_RUNTIME_PROVIDER = 'openai';
const OPENAI_OAUTH_DEFAULT_MODEL_REF = `${OPENAI_OAUTH_RUNTIME_PROVIDER}/gpt-5.5`;
const OPENAI_OAUTH_DEFAULT_MODEL_REF = `${OPENAI_OAUTH_RUNTIME_PROVIDER}/gpt-5.6-sol`;
/**
* Provider types that are not in the built-in provider registry (no `providerConfig.api`).
@@ -98,6 +98,10 @@ export function getOpenClawProviderKey(type: string, providerId: string): string
if (type === 'minimax-portal-cn') {
return 'minimax-portal';
}
// OpenClaw Z.AI provider key is always `zai` (Global UI vendor aliases here).
if (type === 'zai-global') {
return 'zai';
}
return type;
}
@@ -181,29 +185,6 @@ export async function getProviderFallbackModelRefs(config: ProviderConfig): Prom
return results;
}
type GatewayRefreshMode = 'reload' | 'restart';
function scheduleGatewayRefresh(
gatewayManager: GatewayManager | undefined,
message: string,
options?: { delayMs?: number; onlyIfRunning?: boolean; mode?: GatewayRefreshMode },
): void {
if (!gatewayManager) {
return;
}
if (options?.onlyIfRunning && gatewayManager.getStatus().state === 'stopped') {
return;
}
logger.info(message);
if (options?.mode === 'restart') {
gatewayManager.debouncedRestart(options?.delayMs);
return;
}
gatewayManager.debouncedReload(options?.delayMs);
}
export async function syncProviderApiKeyToRuntime(
providerType: string,
providerId: string,
@@ -317,7 +298,8 @@ async function syncRuntimeProviderConfig(
config: ProviderConfig,
context: RuntimeProviderSyncContext,
): Promise<void> {
await syncProviderConfigToOpenClaw(context.runtimeProviderKey, config.model, {
const modelId = normalizeRuntimeModelId(context.runtimeProviderKey, config.model);
await syncProviderConfigToOpenClaw(context.runtimeProviderKey, modelId, {
baseUrl: normalizeProviderBaseUrl(config, config.baseUrl || context.meta?.baseUrl, context.api),
api: context.api,
apiKeyEnv: context.meta?.apiKeyEnv,
@@ -339,7 +321,7 @@ async function syncCustomProviderAgentModel(
return;
}
const modelId = config.model;
const modelId = normalizeRuntimeModelId(runtimeProviderKey, config.model);
await updateAgentModelProvider(runtimeProviderKey, {
baseUrl: normalizeProviderBaseUrl(config, config.baseUrl, config.apiProtocol || 'openai-completions'),
api: config.apiProtocol || 'openai-completions',
@@ -414,6 +396,16 @@ function parseModelRef(modelRef: string): { providerKey: string; modelId: string
};
}
function normalizeRuntimeModelId(
runtimeProviderKey: string,
modelId: string | undefined,
): string | undefined {
const value = modelId?.trim();
if (!value) return undefined;
const prefix = `${runtimeProviderKey}/`;
return value.startsWith(prefix) ? value.slice(prefix.length) : value;
}
async function buildRuntimeProviderConfigMap(): Promise<Map<string, ProviderConfig>> {
const configs = await getAllProviders();
const runtimeMap = new Map<string, ProviderConfig>();
@@ -507,29 +499,21 @@ export async function syncAgentModelOverrideToRuntime(agentId: string): Promise<
export async function syncSavedProviderToRuntime(
config: ProviderConfig,
apiKey: string | undefined,
gatewayManager?: GatewayManager,
_gatewayManager?: GatewayManager,
): Promise<void> {
const context = await syncProviderToRuntime(config, apiKey);
if (!context) {
return;
}
try {
await syncAgentModelsToRuntime();
} catch (err) {
logger.warn('[provider-runtime] Failed to sync per-agent model registries after provider save:', err);
}
await syncAgentModelsToRuntime();
scheduleGatewayRefresh(
gatewayManager,
`Scheduling Gateway reload after saving provider "${context.runtimeProviderKey}" config`,
);
}
export async function syncUpdatedProviderToRuntime(
config: ProviderConfig,
apiKey: string | undefined,
gatewayManager?: GatewayManager,
_gatewayManager?: GatewayManager,
): Promise<void> {
const context = await syncProviderToRuntime(config, apiKey);
if (!context) {
@@ -542,7 +526,8 @@ export async function syncUpdatedProviderToRuntime(
const defaultProviderId = await getDefaultProvider();
const isDefaultProvider = defaultProviderId === config.id;
if (isDefaultProvider) {
const modelOverride = config.model ? `${ock}/${config.model}` : undefined;
const selectedModelId = normalizeRuntimeModelId(ock, config.model);
const modelOverride = selectedModelId ? `${ock}/${selectedModelId}` : undefined;
if (!isUnregisteredProviderType(config.type)) {
if (shouldUseExplicitDefaultOverride(config, ock)) {
await setOpenClawDefaultModelWithOverride(ock, modelOverride, {
@@ -563,22 +548,14 @@ export async function syncUpdatedProviderToRuntime(
}
}
try {
await syncAgentModelsToRuntime();
} catch (err) {
logger.warn('[provider-runtime] Failed to sync per-agent model registries after provider update:', err);
}
await syncAgentModelsToRuntime();
scheduleGatewayRefresh(
gatewayManager,
`Scheduling Gateway reload after updating provider "${ock}" config`,
);
}
export async function syncDeletedProviderToRuntime(
provider: ProviderConfig | null,
providerId: string,
gatewayManager?: GatewayManager,
_gatewayManager?: GatewayManager,
runtimeProviderKey?: string,
): Promise<void> {
if (!provider?.type) {
@@ -588,11 +565,6 @@ export async function syncDeletedProviderToRuntime(
const ock = runtimeProviderKey ?? await resolveRuntimeProviderKey({ ...provider, id: providerId });
await removeDeletedProviderFromOpenClaw(provider, providerId, ock);
scheduleGatewayRefresh(
gatewayManager,
`Scheduling Gateway restart after deleting provider "${ock}"`,
{ mode: 'restart' },
);
}
export async function syncDeletedProviderApiKeyToRuntime(
@@ -610,7 +582,7 @@ export async function syncDeletedProviderApiKeyToRuntime(
export async function syncDefaultProviderToRuntime(
providerId: string,
gatewayManager?: GatewayManager,
_gatewayManager?: GatewayManager,
): Promise<void> {
const provider = await getProvider(providerId);
if (!provider) {
@@ -726,15 +698,7 @@ export async function syncDefaultProviderToRuntime(
fallbackModels.map((fallback) => fallback.replace(/^openai-codex\//, `${browserOAuthRuntimeProvider}/`)),
);
logger.info(`Configured openclaw.json for browser OAuth provider "${provider.id}"`);
try {
await syncAgentModelsToRuntime();
} catch (err) {
logger.warn('[provider-runtime] Failed to sync per-agent model registries after browser OAuth switch:', err);
}
scheduleGatewayRefresh(
gatewayManager,
`Scheduling Gateway reload after provider switch to "${browserOAuthRuntimeProvider}"`,
);
await syncAgentModelsToRuntime();
return;
}
@@ -759,18 +723,14 @@ export async function syncDefaultProviderToRuntime(
logger.info(`Configured openclaw.json for OAuth provider "${provider.type}"`);
try {
const defaultModelId = provider.model?.split('/').pop();
await updateAgentModelProvider(targetProviderKey, {
baseUrl,
api,
authHeader: targetProviderKey === 'minimax-portal' ? true : undefined,
apiKey: targetProviderKey === 'minimax-portal' ? 'minimax-oauth' : 'qwen-oauth',
models: defaultModelId ? [piAiModelsJsonModelEntry(defaultModelId)] : [],
});
} catch (err) {
logger.warn(`Failed to update models.json for OAuth provider "${targetProviderKey}":`, err);
}
const defaultModelId = provider.model?.split('/').pop();
await updateAgentModelProvider(targetProviderKey, {
baseUrl,
api,
authHeader: targetProviderKey === 'minimax-portal' ? true : undefined,
apiKey: targetProviderKey === 'minimax-portal' ? 'minimax-oauth' : 'qwen-oauth',
models: defaultModelId ? [piAiModelsJsonModelEntry(defaultModelId)] : [],
});
}
if (
@@ -787,15 +747,6 @@ export async function syncDefaultProviderToRuntime(
});
}
try {
await syncAgentModelsToRuntime();
} catch (err) {
logger.warn('[provider-runtime] Failed to sync per-agent model registries after default provider switch:', err);
}
await syncAgentModelsToRuntime();
scheduleGatewayRefresh(
gatewayManager,
`Scheduling Gateway reload after provider switch to "${ock}"`,
{ onlyIfRunning: true },
);
}
@@ -73,9 +73,38 @@ function inferProviderVendorIdFromOpenClawEntry(
}
}
// OpenClaw stores a single `zai` key; pick CN vs Global UI vendor from baseUrl.
if (key === 'zai') {
const baseUrl = typeof entry.baseUrl === 'string' ? entry.baseUrl.toLowerCase() : '';
if (baseUrl.includes('api.z.ai')) {
return 'zai-global';
}
return 'zai';
}
return ((BUILTIN_PROVIDER_TYPES as readonly string[]).includes(key) ? key : 'custom') as ProviderType | 'custom';
}
function providerMetadataEquals(
left: ProviderAccount['metadata'] | undefined,
right: ProviderAccount['metadata'] | undefined,
): boolean {
return JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
}
function mergeSyncedProviderMetadata(
existing: ProviderAccount['metadata'] | undefined,
synced: ProviderAccount['metadata'] | undefined,
): ProviderAccount['metadata'] | undefined {
const next = { ...(existing ?? {}) };
if (synced?.customModels && synced.customModels.length > 0) {
next.customModels = synced.customModels;
} else {
delete next.customModels;
}
return Object.keys(next).length > 0 ? next : undefined;
}
export class ProviderService {
async listVendors(): Promise<ProviderDefinition[]> {
return PROVIDER_DEFINITIONS;
@@ -147,10 +176,9 @@ export class ProviderService {
const aliasAccounts = storeGroup.filter((a) => a.vendorId !== key);
const candidates = aliasAccounts.length > 0 ? aliasAccounts : storeGroup;
candidates.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
result.push(candidates[0]);
// Clean up orphaned duplicates from the store.
const kept = candidates[0];
let kept = candidates[0];
for (const account of storeGroup) {
if (account.id !== kept.id) {
logger.info(
@@ -159,6 +187,34 @@ export class ProviderService {
await deleteProviderAccount(account.id);
}
}
const entry = openClawProviders[key];
if (entry) {
const [syncedAccount] = ProviderService.buildAccountsFromOpenClawEntries(
{ [key]: entry },
new Set(),
new Set(),
defaultModel,
);
if (syncedAccount) {
const nextMetadata = mergeSyncedProviderMetadata(kept.metadata, syncedAccount.metadata);
const shouldSyncSelectedModel = defaultModel?.startsWith(`${key}/`) ?? false;
const nextModel = shouldSyncSelectedModel ? syncedAccount.model : kept.model;
const shouldSyncModelState = kept.model !== nextModel
|| !providerMetadataEquals(kept.metadata, nextMetadata);
if (shouldSyncModelState) {
kept = {
...kept,
model: nextModel,
metadata: nextMetadata,
updatedAt: new Date().toISOString(),
};
await saveProviderAccount(kept);
}
}
}
result.push(kept);
} else {
// No store account for this key — create a seed from openclaw.json.
const entry = openClawProviders[key];
@@ -242,6 +298,15 @@ export class ProviderService {
}
const baseUrl = typeof entry.baseUrl === 'string' ? entry.baseUrl : definition?.providerConfig?.baseUrl;
const customModels = Array.isArray(entry.models)
? Array.from(new Set(entry.models
.map((item) => {
if (!item || typeof item !== 'object' || Array.isArray(item)) return '';
const raw = (item as Record<string, unknown>).id;
return typeof raw === 'string' ? raw.trim() : '';
})
.filter(Boolean)))
: undefined;
// Infer model from the default model if it belongs to this provider
let model: string | undefined;
@@ -262,6 +327,9 @@ export class ProviderService {
? (entry.headers as Record<string, string>)
: undefined),
model,
metadata: customModels && customModels.length > 0
? { customModels }
: undefined,
enabled: true,
isDefault: false,
createdAt: now,
@@ -196,6 +196,7 @@ async function validateOpenAiCompatibleKey(
apiKey: string,
apiProtocol: 'openai-completions' | 'openai-responses',
baseUrl?: string,
modelId?: string,
): Promise<ValidationResult> {
const trimmedBaseUrl = baseUrl?.trim();
if (!trimmedBaseUrl) {
@@ -203,6 +204,7 @@ async function validateOpenAiCompatibleKey(
}
const headers = { Authorization: `Bearer ${apiKey}` };
const probeModel = modelId?.trim() || 'validation-probe';
const { modelsUrl, probeUrl } = resolveOpenAiProbeUrls(trimmedBaseUrl, apiProtocol);
const modelsResult = await performProviderValidationRequest(providerType, modelsUrl, headers);
@@ -211,9 +213,9 @@ async function validateOpenAiCompatibleKey(
`[clawx-validate] ${providerType} /models returned ${modelsResult.status}, falling back to ${apiProtocol} probe`,
);
if (apiProtocol === 'openai-responses') {
return await performResponsesProbe(providerType, probeUrl, headers);
return await performResponsesProbe(providerType, probeUrl, headers, probeModel);
}
return await performChatCompletionsProbe(providerType, probeUrl, headers);
return await performChatCompletionsProbe(providerType, probeUrl, headers, probeModel);
}
return modelsResult;
@@ -223,6 +225,7 @@ async function performResponsesProbe(
providerLabel: string,
url: string,
headers: Record<string, string>,
modelId: string,
): Promise<ValidationResult> {
try {
logValidationRequest(providerLabel, 'POST', url, headers);
@@ -230,7 +233,7 @@ async function performResponsesProbe(
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'validation-probe',
model: modelId,
input: 'hi',
}),
});
@@ -249,6 +252,7 @@ async function performChatCompletionsProbe(
providerLabel: string,
url: string,
headers: Record<string, string>,
modelId: string,
): Promise<ValidationResult> {
try {
logValidationRequest(providerLabel, 'POST', url, headers);
@@ -256,7 +260,7 @@ async function performChatCompletionsProbe(
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'validation-probe',
model: modelId,
messages: [{ role: 'user', content: 'hi' }],
max_tokens: 1,
}),
@@ -353,7 +357,7 @@ async function validateOpenRouterKey(
export async function validateApiKeyWithProvider(
providerType: string,
apiKey: string,
options?: { baseUrl?: string; apiProtocol?: string },
options?: { baseUrl?: string; apiProtocol?: string; modelId?: string },
): Promise<ValidationResult> {
const profile = getValidationProfile(providerType, options);
const resolvedBaseUrl = options?.baseUrl || getProviderConfig(providerType)?.baseUrl;
@@ -375,6 +379,7 @@ export async function validateApiKeyWithProvider(
trimmedKey,
'openai-completions',
resolvedBaseUrl,
options?.modelId,
);
case 'openai-responses':
return await validateOpenAiCompatibleKey(
@@ -382,6 +387,7 @@ export async function validateApiKeyWithProvider(
trimmedKey,
'openai-responses',
resolvedBaseUrl,
options?.modelId,
);
case 'google-query-key':
return await validateGoogleQueryKey(providerType, trimmedKey, resolvedBaseUrl);
+254 -33
View File
@@ -1,8 +1,12 @@
import { openSync, closeSync, fstatSync, readSync } from 'node:fs';
import { access } from 'node:fs/promises';
import { join } from 'node:path';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import { stripAcpWorkingDirectoryPrefix } from '@shared/chat/session-title';
import { isOpenClawHeartbeatPollText } from '@shared/chat/openclaw-internal';
import type { RawMessage } from '@shared/chat/types';
import { getOpenClawConfigDir } from '../utils/paths';
import type { SessionTurnTimingCandidate } from '@shared/host-api/contract';
import { resolveOpenClawStateDir } from '../utils/paths';
import { logger } from '../utils/logger';
import {
removeSessionEntry,
@@ -20,15 +24,25 @@ type SessionSummary = {
sessionKey: string;
firstUserText: string | null;
lastTimestamp: number | null;
workspacePath: string | null;
heartbeatOnly?: boolean;
};
type TranscriptMessage = RawMessage;
type ParsedTranscriptLine = {
type?: string;
id?: unknown;
timestamp?: unknown;
message?: TranscriptMessage;
};
type TranscriptMessageRecord = {
id?: string;
timestamp?: unknown;
message: TranscriptMessage;
};
type SessionPayload = {
id?: unknown;
sessionKey?: unknown;
@@ -51,7 +65,8 @@ function extractMessageText(content: unknown): string {
}
function cleanSummaryUserText(text: string): string {
return text
const textAfterInitialPrefix = stripAcpWorkingDirectoryPrefix(text);
const cleaned = textAfterInitialPrefix
.replace(/^Sender\s*\([^)]*\)\s*:\s*```[a-z]*\n[\s\S]*?```\s*/i, '')
.replace(/^Sender\s*\([^)]*\)\s*:\s*\{[\s\S]*?\}\s*/i, '')
.replace(/^Sender\s*\([^)]*\)\s*:[^\n]*(?:\n\s*)*/i, '')
@@ -66,10 +81,14 @@ function cleanSummaryUserText(text: string): string {
.replace(/^Conversation info\s*\([^)]*\):\s*\{[\s\S]*?\}\s*/i, '')
.replace(/^\[(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+[^\]]+\]\s*/i, '')
.trim();
const stripCwdExposedByCleanup = !textAfterInitialPrefix.startsWith('[Working directory: ')
&& cleaned.startsWith('[Working directory: ');
return (stripCwdExposedByCleanup ? stripAcpWorkingDirectoryPrefix(cleaned) : cleaned).trim();
}
function isInternalSummaryText(text: string): boolean {
if (!text) return true;
if (isOpenClawHeartbeatPollText(text)) return true;
if (/^\s*System\s*\(untrusted\)\s*:/i.test(text)) return true;
if (
/An async command you ran earlier has completed/i.test(text)
@@ -91,39 +110,188 @@ function normalizeTimestamp(value: unknown): number | null {
return value < 1e12 ? value * 1000 : value;
}
function parseMessageLine(line: string): TranscriptMessage | null {
try {
const entry = JSON.parse(line) as ParsedTranscriptLine;
if (entry.type !== 'message' || !entry.message || typeof entry.message !== 'object') {
return null;
function normalizeTranscriptTimestamp(value: unknown): number | null {
if (typeof value === 'number') return normalizeTimestamp(value);
if (typeof value !== 'string' || !value.trim()) return null;
const timestamp = Date.parse(value);
return Number.isFinite(timestamp) ? timestamp : null;
}
function transcriptRecordTimestamp(record: TranscriptMessageRecord): number | null {
return normalizeTranscriptTimestamp(record.timestamp)
?? normalizeTranscriptTimestamp(record.message.timestamp);
}
function normalizeTurnUserText(message: TranscriptMessage): string {
return stripAcpWorkingDirectoryPrefix(extractMessageText(message.content))
.replace(/\r\n/g, '\n')
.trim();
}
function isInternalInterSessionUser(message: TranscriptMessage): boolean {
const provenance = (message as TranscriptMessage & { provenance?: unknown }).provenance;
if (provenance && typeof provenance === 'object' && !Array.isArray(provenance)) {
const kind = (provenance as Record<string, unknown>).kind;
if (typeof kind === 'string' && kind.toLowerCase() === 'inter_session') return true;
}
return /^\[Inter-session message\]\s/.test(extractMessageText(message.content));
}
function extractTranscriptTurnTimings(records: TranscriptMessageRecord[]): SessionTurnTimingCandidate[] {
const turns: Array<{
normalizedUserText: string;
startedAt: number | null;
completedAt: number | null;
}> = [];
let current: (typeof turns)[number] | null = null;
for (const record of records) {
const role = typeof record.message.role === 'string' ? record.message.role.toLowerCase() : '';
if (role === 'user') {
if (isInternalInterSessionUser(record.message)) continue;
current = {
normalizedUserText: normalizeTurnUserText(record.message),
startedAt: transcriptRecordTimestamp(record),
completedAt: null,
};
turns.push(current);
continue;
}
return entry.message;
if (!current || (role !== 'assistant' && role !== 'toolresult' && role !== 'tool_result')) continue;
const timestamp = transcriptRecordTimestamp(record);
if (timestamp != null && (current.completedAt == null || timestamp > current.completedAt)) {
current.completedAt = timestamp;
}
}
const occurrences = new Map<string, number>();
const candidates = new Array<SessionTurnTimingCandidate | null>(turns.length).fill(null);
for (let index = turns.length - 1; index >= 0; index -= 1) {
const turn = turns[index]!;
const userOccurrenceFromTail = (occurrences.get(turn.normalizedUserText) ?? 0) + 1;
occurrences.set(turn.normalizedUserText, userOccurrenceFromTail);
if (turn.startedAt == null || turn.completedAt == null || turn.completedAt < turn.startedAt) continue;
candidates[index] = {
normalizedUserText: turn.normalizedUserText,
userOccurrenceFromTail,
durationMs: turn.completedAt - turn.startedAt,
};
}
return candidates.filter((candidate): candidate is SessionTurnTimingCandidate => candidate != null);
}
type SqliteDatabaseLike = {
prepare: (sql: string) => {
get: (...params: unknown[]) => unknown;
};
};
function normalizeCwdValue(value: unknown): string | null {
const cwd = typeof value === 'string' ? value.trim() : '';
return cwd || null;
}
function parseRuntimeOptionsCwd(value: unknown): string | null {
if (typeof value !== 'string' || !value.trim()) return null;
try {
const parsed = JSON.parse(value) as unknown;
if (!parsed || typeof parsed !== 'object') return null;
return normalizeCwdValue((parsed as Record<string, unknown>).cwd);
} catch {
return null;
}
}
function parseRecentMessagesFromTailChunk(chunk: string, readStart: number, limit: number): TranscriptMessage[] {
function readAcpReplayCwd(db: SqliteDatabaseLike, sessionKey: string): string | null {
try {
const row = db.prepare(
'SELECT cwd FROM acp_replay_sessions WHERE session_key = ? ORDER BY updated_at DESC, session_id ASC LIMIT 1',
).get(sessionKey) as { cwd?: unknown } | undefined;
return normalizeCwdValue(row?.cwd);
} catch {
return null;
}
}
function readAcpRuntimeMetaCwd(db: SqliteDatabaseLike, sessionKey: string): string | null {
try {
const row = db.prepare('SELECT * FROM acp_sessions WHERE session_key = ?').get(sessionKey) as {
runtime_options_json?: unknown;
cwd?: unknown;
} | undefined;
return parseRuntimeOptionsCwd(row?.runtime_options_json) ?? normalizeCwdValue(row?.cwd);
} catch {
return null;
}
}
async function readOpenClawAcpSessionCwds(sessionKeys: string[]): Promise<Map<string, string>> {
const normalizedKeys = Array.from(new Set(sessionKeys.map((sessionKey) => sessionKey.trim()).filter(Boolean)));
const workspaceByKey = new Map<string, string>();
if (normalizedKeys.length === 0) return workspaceByKey;
const databasePath = join(resolveOpenClawStateDir(), 'state', 'openclaw.sqlite');
try {
await access(databasePath);
const sqliteSpecifier = 'node:sqlite';
const { DatabaseSync } = await import(/* @vite-ignore */ sqliteSpecifier);
const db = new DatabaseSync(databasePath, { readOnly: true });
try {
for (const sessionKey of normalizedKeys) {
const cwd = readAcpReplayCwd(db, sessionKey) ?? readAcpRuntimeMetaCwd(db, sessionKey);
if (cwd) workspaceByKey.set(sessionKey, cwd);
}
return workspaceByKey;
} finally {
db.close();
}
} catch {
return new Map();
}
}
function parseMessageRecordLine(line: string): TranscriptMessageRecord | null {
try {
const entry = JSON.parse(line) as ParsedTranscriptLine;
if (entry.type !== 'message' || !entry.message || typeof entry.message !== 'object') {
return null;
}
return {
...(typeof entry.id === 'string' ? { id: entry.id } : {}),
timestamp: entry.timestamp,
message: entry.message,
};
} catch {
return null;
}
}
function parseMessageLine(line: string): TranscriptMessage | null {
return parseMessageRecordLine(line)?.message ?? null;
}
function parseRecentRecordsFromTailChunk(chunk: string, readStart: number, limit: number): TranscriptMessageRecord[] {
const lines = chunk.split(/\r?\n/);
if (readStart > 0) lines.shift();
const collected: TranscriptMessage[] = [];
const collected: TranscriptMessageRecord[] = [];
let scanned = 0;
for (let index = lines.length - 1; index >= 0; index -= 1) {
const line = lines[index];
if (!line?.trim()) continue;
scanned += 1;
if (scanned > RECENT_TRANSCRIPT_MAX_SCAN_LINES) break;
const message = parseMessageLine(line);
if (message) {
collected.push(message);
const record = parseMessageRecordLine(line);
if (record) {
collected.push(record);
if (collected.length >= limit) break;
}
}
return collected.reverse();
}
function readRecentTranscriptMessages(transcriptPath: string, limit: number): TranscriptMessage[] {
function readRecentTranscriptRecords(transcriptPath: string, limit: number): TranscriptMessageRecord[] {
const boundedLimit = Math.max(1, Math.min(Math.floor(limit), 1000));
let fd: number | null = null;
try {
@@ -137,13 +305,13 @@ function readRecentTranscriptMessages(transcriptPath: string, limit: number): Tr
const readLen = size - readStart;
const buffer = Buffer.allocUnsafe(readLen);
readSync(fd, buffer, 0, readLen, readStart);
const messages = parseRecentMessagesFromTailChunk(buffer.toString('utf8'), readStart, boundedLimit);
const records = parseRecentRecordsFromTailChunk(buffer.toString('utf8'), readStart, boundedLimit);
if (
messages.length >= boundedLimit
records.length >= boundedLimit
|| readStart === 0
|| readBytes >= RECENT_TRANSCRIPT_MAX_READ_BYTES
) {
return messages;
return records;
}
readBytes = Math.min(size, readBytes * 2);
}
@@ -153,6 +321,10 @@ function readRecentTranscriptMessages(transcriptPath: string, limit: number): Tr
}
}
function readRecentTranscriptMessages(transcriptPath: string, limit: number): TranscriptMessage[] {
return readRecentTranscriptRecords(transcriptPath, limit).map((record) => record.message);
}
async function readAllTranscriptMessages(transcriptPath: string): Promise<TranscriptMessage[]> {
const fsP = await import('node:fs/promises');
const raw = await fsP.readFile(transcriptPath, 'utf8');
@@ -162,9 +334,14 @@ async function readAllTranscriptMessages(transcriptPath: string): Promise<Transc
});
}
function summarizeTranscriptMessages(sessionKey: string, messages: TranscriptMessage[]): SessionSummary {
function summarizeTranscriptMessages(
sessionKey: string,
messages: TranscriptMessage[],
workspacePath: string | null,
): SessionSummary {
let firstUserText: string | null = null;
let lastTimestamp: number | null = null;
let sawHeartbeatPollText = false;
for (const message of messages) {
const normalizedTs = normalizeTimestamp(message.timestamp);
@@ -173,13 +350,24 @@ function summarizeTranscriptMessages(sessionKey: string, messages: TranscriptMes
}
if (firstUserText == null && message.role === 'user') {
const text = cleanSummaryUserText(extractMessageText(message.content));
if (text && !isInternalSummaryText(text)) {
if (text && isInternalSummaryText(text)) {
if (isOpenClawHeartbeatPollText(text)) {
sawHeartbeatPollText = true;
}
} else if (text) {
firstUserText = text;
}
}
}
return { sessionKey, firstUserText, lastTimestamp };
const heartbeatOnly = firstUserText == null && sawHeartbeatPollText;
return {
sessionKey,
firstUserText,
lastTimestamp,
workspacePath,
...(heartbeatOnly ? { heartbeatOnly: true } : {}),
};
}
function parseSessionKey(sessionKey: string): { agentId: string; suffix: string } | null {
@@ -209,7 +397,7 @@ function getLimit(payload: unknown, fallback = 200): number {
async function readSessionsJson(agentId: string): Promise<Record<string, unknown>> {
const fsP = await import('node:fs/promises');
const sessionsJsonPath = join(getOpenClawConfigDir(), 'agents', agentId, 'sessions', 'sessions.json');
const sessionsJsonPath = join(resolveOpenClawStateDir(), 'agents', agentId, 'sessions', 'sessions.json');
const raw = await fsP.readFile(sessionsJsonPath, 'utf8');
return JSON.parse(raw) as Record<string, unknown>;
}
@@ -264,33 +452,33 @@ function resolveSessionTranscriptPathByKey(
return resolvedSrcPath ?? null;
}
async function loadSessionSummary(sessionKey: string): Promise<SessionSummary> {
async function loadSessionSummary(sessionKey: string, workspacePath: string | null): Promise<SessionSummary> {
const parsed = parseSessionKey(sessionKey);
if (!parsed) {
return { sessionKey, firstUserText: null, lastTimestamp: null };
return { sessionKey, firstUserText: null, lastTimestamp: null, workspacePath };
}
try {
const sessionsDir = join(getOpenClawConfigDir(), 'agents', parsed.agentId, 'sessions');
const sessionsDir = join(resolveOpenClawStateDir(), 'agents', parsed.agentId, 'sessions');
const sessionsJson = await readSessionsJson(parsed.agentId);
const transcriptPath = resolveSessionTranscriptPathByKey(sessionKey, sessionsDir, sessionsJson);
if (!transcriptPath) {
return { sessionKey, firstUserText: null, lastTimestamp: null };
return { sessionKey, firstUserText: null, lastTimestamp: null, workspacePath };
}
const messages = await readAllTranscriptMessages(transcriptPath);
return summarizeTranscriptMessages(sessionKey, messages);
return summarizeTranscriptMessages(sessionKey, messages, workspacePath);
} catch {
return { sessionKey, firstUserText: null, lastTimestamp: null };
return { sessionKey, firstUserText: null, lastTimestamp: null, workspacePath };
}
}
async function loadSessionTranscriptByKey(sessionKey: string, limit: number): Promise<RawMessage[] | null> {
export async function loadSessionTranscriptByKey(sessionKey: string, limit: number): Promise<RawMessage[] | null> {
const parsed = parseSessionKey(sessionKey);
if (!parsed) return null;
try {
const sessionsDir = join(getOpenClawConfigDir(), 'agents', parsed.agentId, 'sessions');
const sessionsDir = join(resolveOpenClawStateDir(), 'agents', parsed.agentId, 'sessions');
const sessionsJson = await readSessionsJson(parsed.agentId);
const transcriptPath = resolveSessionTranscriptPathByKey(sessionKey, sessionsDir, sessionsJson);
if (!transcriptPath) return null;
@@ -301,6 +489,28 @@ async function loadSessionTranscriptByKey(sessionKey: string, limit: number): Pr
}
}
async function loadSessionTurnTimingsByKey(
sessionKey: string,
limit: number,
): Promise<SessionTurnTimingCandidate[] | null> {
const parsed = parseSessionKey(sessionKey);
if (!parsed) return null;
try {
const sessionsDir = join(resolveOpenClawStateDir(), 'agents', parsed.agentId, 'sessions');
const sessionsJson = await readSessionsJson(parsed.agentId);
const transcriptPath = resolveSessionTranscriptPathByKey(sessionKey, sessionsDir, sessionsJson);
if (!transcriptPath) return null;
// ACP session/load is authoritative for history content, but its updates omit the
// original timestamps needed to calculate a whole-turn duration. Read only bounded
// transcript timing metadata here; this must never become a second history source.
return extractTranscriptTurnTimings(readRecentTranscriptRecords(transcriptPath, limit));
} catch {
return null;
}
}
async function deleteSession(sessionKey: string): Promise<{ success: boolean; error?: string }> {
if (!sessionKey || !sessionKey.startsWith('agent:')) {
return { success: false, error: `Invalid sessionKey: ${sessionKey}` };
@@ -314,7 +524,7 @@ async function deleteSession(sessionKey: string): Promise<{ success: boolean; er
return { success: false, error: `Invalid agentId: ${agentId}` };
}
const sessionsDir = join(getOpenClawConfigDir(), 'agents', agentId, 'sessions');
const sessionsDir = join(resolveOpenClawStateDir(), 'agents', agentId, 'sessions');
const sessionsJsonPath = join(sessionsDir, 'sessions.json');
logger.info(`[session:delete] key=${sessionKey} agentId=${agentId}`);
logger.info(`[session:delete] sessionsJson=${sessionsJsonPath}`);
@@ -382,7 +592,7 @@ async function renameSession(sessionKey: string, label: string): Promise<{ succe
return { success: false, error: `Invalid agentId in sessionKey: ${agentId}` };
}
const sessionsJsonPath = join(getOpenClawConfigDir(), 'agents', agentId, 'sessions', 'sessions.json');
const sessionsJsonPath = join(resolveOpenClawStateDir(), 'agents', agentId, 'sessions', 'sessions.json');
const fsP = await import('node:fs/promises');
const raw = await fsP.readFile(sessionsJsonPath, 'utf8');
const json = JSON.parse(raw) as Record<string, unknown>;
@@ -429,9 +639,12 @@ export function createSessionsApi(): CompleteHostServiceRegistry['sessions'] {
? body.sessionKeys.filter((value): value is string => typeof value === 'string' && value.startsWith('agent:'))
: [];
if (sessionKeys.length === 0) return { success: true, summaries: [] };
const workspaceByKey = await readOpenClawAcpSessionCwds(sessionKeys);
return {
success: true,
summaries: await Promise.all(sessionKeys.map((sessionKey) => loadSessionSummary(sessionKey))),
summaries: await Promise.all(sessionKeys.map((sessionKey) => (
loadSessionSummary(sessionKey, workspaceByKey.get(sessionKey.trim()) ?? null)
))),
};
},
history: async (payload) => {
@@ -454,7 +667,7 @@ export function createSessionsApi(): CompleteHostServiceRegistry['sessions'] {
}
try {
const transcriptPath = join(getOpenClawConfigDir(), 'agents', agentId, 'sessions', `${sessionId}.jsonl`);
const transcriptPath = join(resolveOpenClawStateDir(), 'agents', agentId, 'sessions', `${sessionId}.jsonl`);
return { success: true, messages: readRecentTranscriptMessages(transcriptPath, limit) };
} catch (error) {
if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {
@@ -463,5 +676,13 @@ export function createSessionsApi(): CompleteHostServiceRegistry['sessions'] {
return { success: false, error: 'Failed to load transcript' };
}
},
turnTimings: async (payload) => {
const body = isRecord(payload) ? payload as SessionPayload : {};
const sessionKey = typeof body.sessionKey === 'string' ? body.sessionKey.trim() : '';
if (!sessionKey) return { success: false, error: 'sessionKey is required' };
const timings = await loadSessionTurnTimingsByKey(sessionKey, getLimit(payload, 1000));
if (!timings) return { success: false, error: 'Transcript not found' };
return { success: true, timings };
},
};
}
+55
View File
@@ -0,0 +1,55 @@
import { shell, type Session, type WebContents } from 'electron';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import type { WebBrowserGuestRegistry } from '../main/web-browser-policy';
import { normalizeWebBrowserHtmlFileUrl } from '../../shared/web-browser';
export interface WebBrowserApiDependencies {
browserSession: Session;
registry: WebBrowserGuestRegistry;
openExternal?: (url: string) => Promise<void>;
}
function requireLiveGuest(registry: WebBrowserGuestRegistry): WebContents {
const guest = registry.current();
if (!guest) {
throw new Error('Web browser guest is unavailable');
}
return guest;
}
function requireAllowedUrl(url: string): string {
const normalizedUrl = normalizeWebBrowserHtmlFileUrl(url);
if (!normalizedUrl) {
throw new Error('Only local HTML file URLs are allowed');
}
return normalizedUrl;
}
function isAbortedLoad(error: unknown): boolean {
if (typeof error !== 'object' || error === null) return false;
const loadError = error as { code?: unknown; errno?: unknown };
return loadError.code === 'ERR_ABORTED' && loadError.errno === -3;
}
export function createWebBrowserApi(
dependencies: WebBrowserApiDependencies,
): CompleteHostServiceRegistry['webBrowser'] {
const { registry } = dependencies;
const openExternal = dependencies.openExternal ?? ((url: string) => shell.openExternal(url));
return {
async navigate({ url }) {
const guest = requireLiveGuest(registry);
const allowedUrl = requireAllowedUrl(url);
try {
await guest.loadURL(allowedUrl);
} catch (error) {
if (!isAbortedLoad(error)) throw error;
}
},
async openExternal({ url }) {
await openExternal(requireAllowedUrl(url));
},
};
}
+181 -10
View File
@@ -1,19 +1,190 @@
export type ModelInputModality = 'text' | 'image';
type ContextWindowRule = {
/** Human-readable family label; kept so the table reads as documentation. */
label: string;
pattern: RegExp;
contextWindow: number;
};
/**
* Context-window defaults for well-known model families, applied to model rows
* that would otherwise carry no `contextWindow`.
*
* Why this matters: when a model row has neither `contextTokens` nor
* `contextWindow`, OpenClaw's embedded runner skips preemptive compaction and
* context-window guarding entirely, so long sessions only fail at the provider
* with "Context overflow: prompt too large" instead of being compacted early.
*
* Accuracy matters in both directions. Under-reporting is not the safe choice:
* it makes the runner start preflight compaction long before it is needed, and
* a compaction that times out aborts the whole turn. Over-reporting pushes the
* failure to the provider as a hard overflow. Prefer the vendor's published
* figure for the family rather than a defensive guess.
*
* Ordering contract: rules are evaluated top-down and the first match wins, so
* a specific variant MUST appear above its family fallback. Note that `\b`
* treats `.` and `-` as boundaries, so /\bgpt-5\b/ also matches `gpt-5.6-sol`;
* the generation-specific rules above it are what keep that correct.
*/
const CONTEXT_WINDOW_RULES: ContextWindowRule[] = [
// ── OpenAI ──────────────────────────────────────────────────────────────
{ label: 'GPT-5.6 Luna (low-latency tier)', pattern: /\bgpt-5\.6-luna\b/, contextWindow: 272_000 },
{ label: 'GPT-5.6 Sol / Terra', pattern: /\bgpt-5\.6\b/, contextWindow: 1_050_000 },
{ label: 'GPT-5.5', pattern: /\bgpt-5\.5\b/, contextWindow: 1_000_000 },
{ label: 'GPT-5 lightweight variants', pattern: /\bgpt-5[\w.]*-(?:mini|nano|turbo)\b/, contextWindow: 272_000 },
{ label: 'GPT-5 flagship', pattern: /\bgpt-5\b/, contextWindow: 400_000 },
{ label: 'GPT-4.x and o-series', pattern: /\b(?:gpt-4\.1|gpt-4o|o[134])\b/, contextWindow: 128_000 },
// ── Anthropic ───────────────────────────────────────────────────────────
{ label: 'Claude Fable 5 / Opus 5 / Sonnet 5', pattern: /\bclaude-(?:fable|opus|sonnet)-5\b/, contextWindow: 1_000_000 },
{ label: 'Claude Opus 4.8+', pattern: /\bclaude-opus-4[.-][89]\b/, contextWindow: 1_000_000 },
{ label: 'Claude Sonnet 4.6+', pattern: /\bclaude-sonnet-4[.-][6-9]\b/, contextWindow: 1_000_000 },
{ label: 'Claude Haiku and legacy Claude', pattern: /\bclaude\b|\bclaude-/, contextWindow: 200_000 },
// ── Google ──────────────────────────────────────────────────────────────
{ label: 'Gemini 1.0 (pre-million era)', pattern: /\bgemini-1\.0\b/, contextWindow: 32_768 },
{ label: 'Gemini 1.5 and newer', pattern: /\bgemini\b/, contextWindow: 1_048_576 },
// ── DeepSeek ────────────────────────────────────────────────────────────
// `deepseek-chat` / `deepseek-reasoner` are compatibility aliases that route
// to V4-Flash, so they inherit the V4 window rather than the V3 one.
{ label: 'DeepSeek V3 / R1', pattern: /\bdeepseek-(?:v3|r1)\b/, contextWindow: 128_000 },
{ label: 'DeepSeek V4 and aliases', pattern: /\bdeepseek\b/, contextWindow: 1_000_000 },
// ── Moonshot / Kimi ─────────────────────────────────────────────────────
// Only K3 reached a million tokens; K2.x tops out at 262,144.
{ label: 'Kimi K3', pattern: /\bkimi-k3\b/, contextWindow: 1_000_000 },
{ label: 'Kimi K2.x and other Moonshot', pattern: /\bkimi\b|moonshot/, contextWindow: 262_144 },
// ── Alibaba Qwen ────────────────────────────────────────────────────────
{ label: 'Qwen-Long (bulk document tier)', pattern: /\bqwen-long\b/, contextWindow: 10_000_000 },
{ label: 'Qwen 3.6+ hosted API', pattern: /\bqwen-?3\.[6-9]\b/, contextWindow: 1_000_000 },
{ label: 'Qwen 3.5 / Qwen3-Next', pattern: /\bqwen-?3\.5\b|\bqwen3-next\b/, contextWindow: 262_144 },
{ label: 'Qwen open-weight base', pattern: /\bqwen/, contextWindow: 131_072 },
// ── Z.AI GLM ────────────────────────────────────────────────────────────
{ label: 'GLM-5.2+', pattern: /\bglm-5\.[2-9]\b/, contextWindow: 1_000_000 },
{ label: 'GLM-5.0 / 5.1', pattern: /\bglm-5(?:\.[01])?\b/, contextWindow: 200_000 },
{ label: 'GLM-4.x', pattern: /\bglm-4/, contextWindow: 200_000 },
// ── MiniMax ─────────────────────────────────────────────────────────────
{ label: 'MiniMax M3+', pattern: /\bminimax-m[3-9]\b/, contextWindow: 524_288 },
{ label: 'MiniMax M2.x and earlier', pattern: /minimax/, contextWindow: 204_800 },
];
/**
* Fallback for hosted models we do not recognise. Set at the low end of the
* current frontier rather than at the old 128K floor: nearly every model a
* user can point a hosted provider at at this point clears 200K, and guessing
* too low triggers needless compaction on long sessions.
*/
export const DEFAULT_CUSTOM_MODEL_CONTEXT_WINDOW = 200_000;
/**
* Ceiling for locally hosted runtimes (Ollama and friends). A local `qwen3`
* tag is a quantised small model, not the hosted flagship of the same name, so
* family rules must not hand it a frontier-sized window. Kept at 128K because
* ClawX seeds `compaction.reserveTokensFloor = 50000` dropping the ceiling
* near or below that floor leaves the runner no usable budget.
*/
export const LOCAL_MODEL_CONTEXT_WINDOW = 131_072;
/**
* Ceiling for ChatGPT subscription transports (`openai-chatgpt-responses`).
*
* OAuth against a ChatGPT plan does not get the API-tier window: the backend
* enforces a far smaller per-session budget than `gpt-5.6-sol`'s published
* 1.05M. OpenClaw's own Codex catalog hard-codes 272,000 for every model on
* this transport, so we mirror that figure rather than inventing our own.
*
* This matters because ClawX writes OAuth rows into `models.providers.openai`
* while OpenClaw's cap lives on its separate `codex` provider nothing else
* would clamp the value we write.
*/
export const CHATGPT_OAUTH_CONTEXT_WINDOW = 272_000;
/** Runtime provider keys are suffixed per instance, e.g. `ollama-a1b2c3`. */
const LOCAL_PROVIDER_KEY_PATTERN = /^ollama(?:-|$)/;
/** Current and legacy spellings of the ChatGPT subscription transport. */
const SUBSCRIPTION_API_PROTOCOLS = new Set([
'openai-chatgpt-responses',
'openai-codex-responses',
]);
export type ModelCapabilityContext = {
/** OpenClaw runtime provider key, used to detect locally hosted models. */
providerKey?: string;
/** `models.providers.*.api` value, used to detect subscription transports. */
apiProtocol?: string;
};
/**
* Model ids reach us in several shapes: bare (`gpt-5.6-sol`), vendor-prefixed
* from aggregators (`openai/gpt-5.6-sol`, `deepseek-ai/DeepSeek-V3`), and
* Ollama-tagged (`qwen3:latest`). Patterns are written against the bare family
* name, so expose both forms and let callers test each.
*/
function normalizeModelId(modelId: string): { bare: string; full: string } {
const full = modelId.trim().toLowerCase();
const withoutVendor = full.slice(full.lastIndexOf('/') + 1);
const [bare] = withoutVendor.split(':');
return { bare: bare || full, full };
}
function matchesModelId(pattern: RegExp, modelId: string): boolean {
const { bare, full } = normalizeModelId(modelId);
return pattern.test(bare) || pattern.test(full);
}
function isLocalProviderKey(providerKey: string | undefined): boolean {
return providerKey != null && LOCAL_PROVIDER_KEY_PATTERN.test(providerKey.trim().toLowerCase());
}
function isSubscriptionApiProtocol(apiProtocol: string | undefined): boolean {
return apiProtocol != null && SUBSCRIPTION_API_PROTOCOLS.has(apiProtocol.trim().toLowerCase());
}
/**
* Family rules describe what the vendor's API tier offers. The transport a
* given account actually uses can be far more restrictive, so clamp rather
* than trusting the published figure.
*/
function resolveContextWindowCeiling(context: ModelCapabilityContext): number {
const ceilings: number[] = [];
if (isLocalProviderKey(context.providerKey)) ceilings.push(LOCAL_MODEL_CONTEXT_WINDOW);
if (isSubscriptionApiProtocol(context.apiProtocol)) ceilings.push(CHATGPT_OAUTH_CONTEXT_WINDOW);
return ceilings.length > 0 ? Math.min(...ceilings) : Number.POSITIVE_INFINITY;
}
export function inferCustomModelContextWindow(
modelId: string,
context: ModelCapabilityContext = {},
): number {
const ceiling = resolveContextWindowCeiling(context);
for (const rule of CONTEXT_WINDOW_RULES) {
if (matchesModelId(rule.pattern, modelId)) return Math.min(rule.contextWindow, ceiling);
}
return Math.min(DEFAULT_CUSTOM_MODEL_CONTEXT_WINDOW, ceiling);
}
const VISION_MODEL_PATTERNS: RegExp[] = [
/\b(?:gpt-4o|gpt-4\.1|gpt-[5-9]|o[134])\b/,
/\bclaude-(?:3|4|fable|sonnet|opus|haiku)\b/,
/\bgemini\b/,
/\b(?:qwen[\w.-]*-?vl|qwen-vl)\b/,
/\b(?:vision|llava|pixtral|internvl|mllama|minicpm-v|glm-4v)\b/,
/(?:^|[-_/])vl(?:[-_/]|$)/,
];
/**
* Mirrors OpenClaw 2026.5.20 custom-provider onboarding inference.
* Unknown models use the same conservative text-only fallback as non-interactive onboarding.
*/
export function inferCustomModelInputModalities(modelId: string): ModelInputModality[] {
const normalized = modelId.trim().toLowerCase();
const supportsImageInput = (
/\b(?:gpt-4o|gpt-4\.1|gpt-[5-9]|o[134])\b/.test(normalized)
|| /\bclaude-(?:3|4|sonnet|opus|haiku)\b/.test(normalized)
|| /\bgemini\b/.test(normalized)
|| /\b(?:qwen[\w.-]*-?vl|qwen-vl)\b/.test(normalized)
|| /\b(?:vision|llava|pixtral|internvl|mllama|minicpm-v|glm-4v)\b/.test(normalized)
|| /(?:^|[-_/])vl(?:[-_/]|$)/.test(normalized)
);
const supportsImageInput = VISION_MODEL_PATTERNS.some((pattern) => matchesModelId(pattern, modelId));
return supportsImageInput ? ['text', 'image'] : ['text'];
}
+123 -8
View File
@@ -15,9 +15,9 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [
requiresApiKey: true,
category: 'official',
envVar: 'ANTHROPIC_API_KEY',
defaultModelId: 'claude-opus-4-6',
defaultModelId: 'claude-opus-4-8',
showModelId: true,
modelIdPlaceholder: 'claude-opus-4-6',
modelIdPlaceholder: 'claude-opus-4-8',
supportedAuthModes: ['api_key'],
defaultAuthMode: 'api_key',
supportsMultipleAccounts: true,
@@ -31,11 +31,11 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [
requiresApiKey: true,
category: 'official',
envVar: 'OPENAI_API_KEY',
defaultModelId: 'gpt-5.5',
defaultModelId: 'gpt-5.6-sol',
isOAuth: true,
supportsApiKey: true,
showModelId: true,
modelIdPlaceholder: 'gpt-5.5',
modelIdPlaceholder: 'gpt-5.6-sol',
supportedAuthModes: ['api_key', 'oauth_browser'],
defaultAuthMode: 'api_key',
supportsMultipleAccounts: true,
@@ -69,8 +69,8 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [
model: 'Multi-Model',
requiresApiKey: true,
showModelId: true,
modelIdPlaceholder: 'anthropic/claude-opus-4.6',
defaultModelId: 'anthropic/claude-opus-4.6',
modelIdPlaceholder: 'openai/gpt-5.6-sol',
defaultModelId: 'openai/gpt-5.6-sol',
category: 'compatible',
envVar: 'OPENROUTER_API_KEY',
supportedAuthModes: ['api_key'],
@@ -138,7 +138,7 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [
reasoning: false,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 256000,
contextWindow: 262144,
maxTokens: 8192,
},
],
@@ -171,7 +171,7 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [
reasoning: false,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 256000,
contextWindow: 262144,
maxTokens: 8192,
},
],
@@ -310,6 +310,121 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [
],
},
},
{
// OpenClaw runtime key is always `zai` (CN + Global share one provider slot).
// Cross-checked with docs.openclaw.ai/providers/zai and docs.z.ai/devpack/tool/openclaw.
id: 'zai',
name: 'Z.AI (CN)',
icon: 'Z',
placeholder: 'your-z.ai-api-key',
model: 'GLM',
requiresApiKey: true,
defaultBaseUrl: 'https://open.bigmodel.cn/api/paas/v4',
showBaseUrl: true,
showModelId: true,
modelIdPlaceholder: 'glm-5.2',
defaultModelId: 'glm-5.2',
apiKeyUrl: 'https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys',
category: 'official',
envVar: 'ZAI_API_KEY',
codePlanPresetBaseUrl: 'https://open.bigmodel.cn/api/coding/paas/v4',
codePlanPresetModelId: 'glm-5.2',
codePlanDocsUrl: 'https://docs.bigmodel.cn/cn/coding-plan/quick-start',
supportedAuthModes: ['api_key'],
defaultAuthMode: 'api_key',
supportsMultipleAccounts: true,
providerConfig: {
baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
api: 'openai-completions',
apiKeyEnv: 'ZAI_API_KEY',
models: [
{
id: 'glm-5.2',
name: 'GLM-5.2',
reasoning: true,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1000000,
maxTokens: 131072,
},
{
id: 'glm-5.1',
name: 'GLM-5.1',
reasoning: true,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 200000,
maxTokens: 131072,
},
{
id: 'glm-4.7',
name: 'GLM-4.7',
reasoning: true,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 200000,
maxTokens: 131072,
},
],
},
},
{
// Aliases to OpenClaw runtime key `zai` — mutually exclusive with CN in the UI.
id: 'zai-global',
name: 'Z.AI (Global)',
icon: 'Z',
placeholder: 'your-z.ai-api-key',
model: 'GLM',
requiresApiKey: true,
defaultBaseUrl: 'https://api.z.ai/api/paas/v4',
showBaseUrl: true,
showModelId: true,
modelIdPlaceholder: 'glm-5.2',
defaultModelId: 'glm-5.2',
apiKeyUrl: 'https://z.ai/manage-apikey',
category: 'official',
envVar: 'ZAI_API_KEY',
codePlanPresetBaseUrl: 'https://api.z.ai/api/coding/paas/v4',
codePlanPresetModelId: 'glm-5.2',
codePlanDocsUrl: 'https://docs.z.ai/devpack/quick-start',
supportedAuthModes: ['api_key'],
defaultAuthMode: 'api_key',
supportsMultipleAccounts: true,
providerConfig: {
baseUrl: 'https://api.z.ai/api/paas/v4',
api: 'openai-completions',
apiKeyEnv: 'ZAI_API_KEY',
models: [
{
id: 'glm-5.2',
name: 'GLM-5.2',
reasoning: true,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1000000,
maxTokens: 131072,
},
{
id: 'glm-5.1',
name: 'GLM-5.1',
reasoning: true,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 200000,
maxTokens: 131072,
},
{
id: 'glm-4.7',
name: 'GLM-4.7',
reasoning: true,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 200000,
maxTokens: 131072,
},
],
},
},
{
id: 'modelstudio',
name: 'Model Studio',
+4
View File
@@ -10,6 +10,8 @@ export const PROVIDER_TYPES = [
'deepseek',
'minimax-portal',
'minimax-portal-cn',
'zai',
'zai-global',
'modelstudio',
'ollama',
'custom',
@@ -27,6 +29,8 @@ export const BUILTIN_PROVIDER_TYPES = [
'deepseek',
'minimax-portal',
'minimax-portal-cn',
'zai',
'zai-global',
'modelstudio',
'ollama',
] as const;
+246 -86
View File
@@ -1,9 +1,9 @@
import { access, copyFile, mkdir, readdir, rm } from 'fs/promises';
import { constants } from 'fs';
import { copyFile, lstat, mkdir, readdir, rm } from 'fs/promises';
import { join, normalize } from 'path';
import { deleteAgentChannelAccounts, listConfiguredChannels, readOpenClawConfig, writeOpenClawConfig } from './channel-config';
import { isDeepStrictEqual } from 'node:util';
import { mutateOpenClawConfig } from '../gateway/config-delivery';
import { deleteAgentChannelAccounts, listConfiguredChannelsFromConfig, readOpenClawConfig } from './channel-config';
import type { OpenClawConfig } from './channel-config';
import { withConfigLock } from './config-mutex';
import { expandPath, getOpenClawConfigDir } from './paths';
import * as logger from './logger';
import { toUiChannelType } from './channel-alias';
@@ -62,6 +62,11 @@ interface BindingConfig extends Record<string, unknown> {
match?: BindingMatch;
}
interface ChannelBindingConfig extends BindingConfig {
agentId: string;
match: BindingMatch & { channel: string };
}
interface ChannelSectionConfig extends Record<string, unknown> {
accounts?: Record<string, Record<string, unknown>>;
defaultAccount?: string;
@@ -147,7 +152,7 @@ function slugifyAgentId(name: string): string {
async function fileExists(path: string): Promise<boolean> {
try {
await access(path, constants.F_OK);
await lstat(path);
return true;
} catch {
return false;
@@ -217,7 +222,7 @@ function normalizeAgentsConfig(config: AgentConfigDocument): {
};
}
function isChannelBinding(binding: unknown): binding is BindingConfig {
function isChannelBinding(binding: unknown): binding is ChannelBindingConfig {
if (!binding || typeof binding !== 'object') return false;
const candidate = binding as BindingConfig;
if (typeof candidate.agentId !== 'string' || !candidate.agentId) return false;
@@ -460,7 +465,8 @@ function listConfiguredAccountIdsForChannel(config: AgentConfigDocument, channel
async function buildSnapshotFromConfig(config: AgentConfigDocument, preloadedChannels?: string[]): Promise<AgentsSnapshot> {
const { entries, defaultAgentId } = normalizeAgentsConfig(config);
const configuredChannels = preloadedChannels ?? await listConfiguredChannels();
const configuredChannels = preloadedChannels
?? await listConfiguredChannelsFromConfig(config as OpenClawConfig);
const { channelToAgent, accountToAgent } = getChannelBindingMap(config.bindings);
const defaultAgentIdNorm = normalizeAgentIdForBinding(defaultAgentId);
const channelOwners: Record<string, string> = {};
@@ -472,15 +478,11 @@ async function buildSnapshotFromConfig(config: AgentConfigDocument, preloadedCha
for (const channelType of configuredChannels) {
const accountIds = listConfiguredAccountIdsForChannel(config, channelType);
let primaryOwner: string | undefined;
const hasExplicitAccountBindingForChannel = accountIds.some((accountId) =>
accountToAgent.has(`${channelType}:${accountId}`),
);
for (const accountId of accountIds) {
const owner =
accountToAgent.get(`${channelType}:${accountId}`)
|| (
accountId === DEFAULT_ACCOUNT_ID && !hasExplicitAccountBindingForChannel
accountId === DEFAULT_ACCOUNT_ID
? channelToAgent.get(channelType)
: undefined
);
@@ -543,16 +545,25 @@ async function buildSnapshotFromConfig(config: AgentConfigDocument, preloadedCha
}
export async function listAgentsSnapshot(): Promise<AgentsSnapshot> {
return withConfigLock(async () => {
const config = await readOpenClawConfig() as AgentConfigDocument;
const { pruneStaleRuntimeAgentModelRefs } = await import('./openclaw-auth');
const modified = await pruneStaleRuntimeAgentModelRefs(config as unknown as Record<string, unknown>);
if (modified) {
await writeOpenClawConfig(config);
logger.info('Pruned stale runtime agent model refs from openclaw.json');
}
return buildSnapshotFromConfig(config);
let snapshot: AgentsSnapshot | undefined;
let prunedRuntimeModelRefs = false;
const {
getActiveAuthProfileProviders,
pruneStaleRuntimeAgentModelRefs,
} = await import('./openclaw-auth');
const authProfileProviders = await getActiveAuthProfileProviders();
await mutateOpenClawConfig(async (configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
prunedRuntimeModelRefs = await pruneStaleRuntimeAgentModelRefs(
config as unknown as Record<string, unknown>,
authProfileProviders,
);
snapshot = await buildSnapshotFromConfig(config);
});
if (prunedRuntimeModelRefs) {
logger.info('Pruned stale runtime agent model refs from openclaw.json');
}
return snapshot!;
}
export async function listAgentsSnapshotFromConfig(config: OpenClawConfig, configuredChannels?: string[]): Promise<AgentsSnapshot> {
@@ -589,8 +600,12 @@ export async function createAgent(
name: string,
options?: { inheritWorkspace?: boolean },
): Promise<AgentsSnapshot> {
return withConfigLock(async () => {
const config = await readOpenClawConfig() as AgentConfigDocument;
let snapshot: AgentsSnapshot | undefined;
let createdAgentId = '';
let agentToProvision: AgentListEntry | undefined;
let provisioningConfig: AgentConfigDocument | undefined;
await mutateOpenClawConfig(async (configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
const { agentsConfig, entries, syntheticMain } = normalizeAgentsConfig(config);
const normalizedName = normalizeAgentName(name);
const existingIds = new Set(entries.map((entry) => entry.id));
@@ -621,18 +636,61 @@ export async function createAgent(
list: nextEntries,
};
await provisionAgentFilesystem(config, newAgent, { inheritWorkspace: options?.inheritWorkspace });
await writeOpenClawConfig(config);
logger.info('Created agent config entry', { agentId: nextId, inheritWorkspace: !!options?.inheritWorkspace });
return buildSnapshotFromConfig(config);
createdAgentId = nextId;
agentToProvision = newAgent;
provisioningConfig = structuredClone(config);
snapshot = await buildSnapshotFromConfig(config);
});
const createdAgent = agentToProvision!;
const workspaceExisted = await fileExists(expandPath(createdAgent.workspace!));
const runtimeDirectory = join(getOpenClawConfigDir(), 'agents', createdAgent.id);
const runtimeDirectoryExisted = await fileExists(runtimeDirectory);
try {
await provisionAgentFilesystem(provisioningConfig!, createdAgent, { inheritWorkspace: options?.inheritWorkspace });
} catch (provisioningError) {
let rollbackError: unknown;
try {
await mutateOpenClawConfig((configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
const { agentsConfig, entries } = normalizeAgentsConfig(config);
const createdIndex = entries.findIndex((entry) => (
entry.id === createdAgent.id && isDeepStrictEqual(entry, createdAgent)
));
if (createdIndex === -1) return;
config.agents = {
...agentsConfig,
list: entries.filter((_, index) => index !== createdIndex),
};
});
} catch (error) {
rollbackError = error;
}
if (!workspaceExisted) {
await removeAgentWorkspaceDirectory(createdAgent);
}
if (!runtimeDirectoryExisted) {
await removeAgentRuntimeDirectory(createdAgent.id);
}
if (rollbackError) {
throw new AggregateError(
[provisioningError, rollbackError],
`Failed to provision agent "${createdAgent.id}" and roll back its config entry`,
{ cause: provisioningError },
);
}
throw provisioningError;
}
logger.info('Created agent config entry', { agentId: createdAgentId, inheritWorkspace: !!options?.inheritWorkspace });
return snapshot!;
}
export async function updateAgentName(agentId: string, name: string): Promise<AgentsSnapshot> {
return withConfigLock(async () => {
const config = await readOpenClawConfig() as AgentConfigDocument;
let snapshot: AgentsSnapshot | undefined;
const normalizedName = normalizeAgentName(name);
await mutateOpenClawConfig(async (configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
const { agentsConfig, entries } = normalizeAgentsConfig(config);
const normalizedName = normalizeAgentName(name);
const index = entries.findIndex((entry) => entry.id === agentId);
if (index === -1) {
throw new Error(`Agent "${agentId}" not found`);
@@ -648,10 +706,10 @@ export async function updateAgentName(agentId: string, name: string): Promise<Ag
list: entries,
};
await writeOpenClawConfig(config);
logger.info('Updated agent name', { agentId, name: normalizedName });
return buildSnapshotFromConfig(config);
snapshot = await buildSnapshotFromConfig(config);
});
logger.info('Updated agent name', { agentId, name: normalizedName });
return snapshot!;
}
function isValidModelRef(modelRef: string): boolean {
@@ -660,15 +718,16 @@ function isValidModelRef(modelRef: string): boolean {
}
export async function updateAgentModel(agentId: string, modelRef: string | null): Promise<AgentsSnapshot> {
return withConfigLock(async () => {
const config = await readOpenClawConfig() as AgentConfigDocument;
const normalizedModelRef = typeof modelRef === 'string' ? modelRef.trim() : '';
let snapshot: AgentsSnapshot | undefined;
await mutateOpenClawConfig(async (configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
const { agentsConfig, entries } = normalizeAgentsConfig(config);
const index = entries.findIndex((entry) => entry.id === agentId);
if (index === -1) {
throw new Error(`Agent "${agentId}" not found`);
}
const normalizedModelRef = typeof modelRef === 'string' ? modelRef.trim() : '';
const nextEntry: AgentListEntry = { ...entries[index] };
if (!normalizedModelRef) {
@@ -677,7 +736,29 @@ export async function updateAgentModel(agentId: string, modelRef: string | null)
if (!isValidModelRef(normalizedModelRef)) {
throw new Error('modelRef must be in "provider/model" format');
}
nextEntry.model = { primary: normalizedModelRef };
// Merge into the existing model block: replacing it wholesale discards
// hand-configured fields such as `fallbacks`.
const existingModel = entries[index].model;
const nextModel: AgentModelConfig = existingModel && typeof existingModel === 'object'
? { ...existingModel, primary: normalizedModelRef }
: { primary: normalizedModelRef };
// The OpenClaw runtime treats a per-agent model block without a
// `fallbacks` key as an EMPTY fallback override, which suppresses
// agents.defaults.model.fallbacks entirely. Inherit the defaults chain
// so switching models never silently disables failover.
if (!Array.isArray(nextModel.fallbacks)) {
const defaultsModel = agentsConfig.defaults?.model;
const defaultFallbacks = defaultsModel && typeof defaultsModel === 'object'
? (defaultsModel as AgentModelConfig).fallbacks
: undefined;
if (Array.isArray(defaultFallbacks)) {
const inherited = defaultFallbacks.filter((ref): ref is string => typeof ref === 'string' && ref.trim().length > 0);
if (inherited.length > 0) {
nextModel.fallbacks = inherited;
}
}
}
nextEntry.model = nextModel;
}
entries[index] = nextEntry;
@@ -686,21 +767,24 @@ export async function updateAgentModel(agentId: string, modelRef: string | null)
list: entries,
};
await writeOpenClawConfig(config);
logger.info('Updated agent model', { agentId, modelRef: normalizedModelRef || null });
return buildSnapshotFromConfig(config);
snapshot = await buildSnapshotFromConfig(config);
});
logger.info('Updated agent model', { agentId, modelRef: normalizedModelRef || null });
return snapshot!;
}
export async function deleteAgentConfig(agentId: string): Promise<{ snapshot: AgentsSnapshot; removedEntry: AgentListEntry }> {
return withConfigLock(async () => {
if (agentId === MAIN_AGENT_ID) {
throw new Error('The main agent cannot be deleted');
}
if (agentId === MAIN_AGENT_ID) {
throw new Error('The main agent cannot be deleted');
}
const config = await readOpenClawConfig() as AgentConfigDocument;
let result: { snapshot: AgentsSnapshot; removedEntry: AgentListEntry } | undefined;
await mutateOpenClawConfig(async (configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
const { agentsConfig, entries, defaultAgentId } = normalizeAgentsConfig(config);
const snapshotBeforeDeletion = await buildSnapshotFromConfig(config);
const bindingsBeforeDeletion = Array.isArray(config.bindings)
? config.bindings.filter(isChannelBinding)
: [];
const removedEntry = entries.find((entry) => entry.id === agentId);
const nextEntries = entries.filter((entry) => entry.id !== agentId);
if (!removedEntry || nextEntries.length === entries.length) {
@@ -724,81 +808,87 @@ export async function deleteAgentConfig(agentId: string): Promise<{ snapshot: Ag
const normalizedAgentId = normalizeAgentIdForBinding(agentId);
const legacyAccountId = resolveAccountIdForAgent(agentId);
const { channelToAgent, accountToAgent } = getChannelBindingMap(bindingsBeforeDeletion);
const boundChannelTypes = new Set(bindingsBeforeDeletion.map((binding) => binding.match.channel));
const ownedLegacyAccounts = new Set(
Object.entries(snapshotBeforeDeletion.channelAccountOwners)
.filter(([channelAccountKey, owner]) => {
if (owner !== normalizedAgentId) return false;
const accountId = channelAccountKey.slice(channelAccountKey.indexOf(':') + 1);
return accountId === legacyAccountId;
[...boundChannelTypes]
.filter((channelType) => {
const accountOwner = accountToAgent.get(`${channelType}:${legacyAccountId}`);
const effectiveOwner = accountOwner
?? (legacyAccountId === DEFAULT_ACCOUNT_ID ? channelToAgent.get(channelType) : undefined);
return effectiveOwner === normalizedAgentId;
})
.map(([channelAccountKey]) => channelAccountKey),
.map((channelType) => `${channelType}:${legacyAccountId}`),
);
await writeOpenClawConfig(config);
await deleteAgentChannelAccounts(agentId, ownedLegacyAccounts);
await removeAgentRuntimeDirectory(agentId);
// NOTE: workspace directory is NOT deleted here intentionally.
// The caller (route handler) defers workspace removal until after
// the Gateway process has fully restarted, so that any in-flight
// process.chdir(workspace) calls complete before the directory
// disappears (otherwise process.cwd() throws ENOENT for the rest
// of the Gateway's lifetime).
logger.info('Deleted agent config entry', { agentId });
return { snapshot: await buildSnapshotFromConfig(config), removedEntry };
result = { snapshot: await buildSnapshotFromConfig(config), removedEntry };
});
await removeAgentRuntimeDirectory(agentId);
// The caller removes the workspace only after the coordinator commit above.
logger.info('Deleted agent config entry', { agentId });
return result!;
}
export async function assignChannelToAgent(agentId: string, channelType: string): Promise<AgentsSnapshot> {
return withConfigLock(async () => {
const config = await readOpenClawConfig() as AgentConfigDocument;
let snapshot: AgentsSnapshot | undefined;
const accountId = resolveAccountIdForAgent(agentId);
await mutateOpenClawConfig(async (configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
const { entries } = normalizeAgentsConfig(config);
if (!entries.some((entry) => entry.id === agentId)) {
throw new Error(`Agent "${agentId}" not found`);
}
const accountId = resolveAccountIdForAgent(agentId);
config.bindings = upsertBindingsForChannel(config.bindings, channelType, agentId, accountId);
await writeOpenClawConfig(config);
logger.info('Assigned channel to agent', { agentId, channelType, accountId });
return buildSnapshotFromConfig(config);
snapshot = await buildSnapshotFromConfig(config);
});
logger.info('Assigned channel to agent', { agentId, channelType, accountId });
return snapshot!;
}
export async function assignChannelAccountToAgent(
agentId: string,
channelType: string,
accountId: string,
options?: { migrateLegacy?: boolean },
): Promise<AgentsSnapshot> {
return withConfigLock(async () => {
const config = await readOpenClawConfig() as AgentConfigDocument;
const trimmedAccountId = accountId.trim();
if (!trimmedAccountId) {
throw new Error('accountId is required');
}
let snapshot: AgentsSnapshot | undefined;
await mutateOpenClawConfig(async (configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
const { entries } = normalizeAgentsConfig(config);
if (!entries.some((entry) => entry.id === agentId)) {
throw new Error(`Agent "${agentId}" not found`);
}
if (!accountId.trim()) {
throw new Error('accountId is required');
if (options?.migrateLegacy) {
const validAgentIds = new Set(entries.map((entry) => normalizeAgentIdForBinding(entry.id)));
migrateLegacyChannelBindingInConfig(config, channelType, validAgentIds);
}
config.bindings = upsertBindingsForChannel(config.bindings, channelType, agentId, accountId.trim());
await writeOpenClawConfig(config);
logger.info('Assigned channel account to agent', { agentId, channelType, accountId: accountId.trim() });
return buildSnapshotFromConfig(config);
config.bindings = upsertBindingsForChannel(config.bindings, channelType, agentId, trimmedAccountId);
snapshot = await buildSnapshotFromConfig(config);
});
logger.info('Assigned channel account to agent', { agentId, channelType, accountId: trimmedAccountId });
return snapshot!;
}
export async function clearChannelBinding(channelType: string, accountId?: string): Promise<AgentsSnapshot> {
return withConfigLock(async () => {
const config = await readOpenClawConfig() as AgentConfigDocument;
let snapshot: AgentsSnapshot | undefined;
await mutateOpenClawConfig(async (configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
config.bindings = upsertBindingsForChannel(config.bindings, channelType, null, accountId);
await writeOpenClawConfig(config);
logger.info('Cleared channel binding', { channelType, accountId });
return buildSnapshotFromConfig(config);
snapshot = await buildSnapshotFromConfig(config);
});
logger.info('Cleared channel binding', { channelType, accountId });
return snapshot!;
}
export async function clearAllBindingsForChannel(channelType: string): Promise<void> {
return withConfigLock(async () => {
const config = await readOpenClawConfig() as AgentConfigDocument;
await mutateOpenClawConfig((configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
if (!Array.isArray(config.bindings)) return;
const nextBindings = config.bindings.filter((binding) => {
@@ -807,7 +897,77 @@ export async function clearAllBindingsForChannel(channelType: string): Promise<v
});
config.bindings = nextBindings.length > 0 ? nextBindings : undefined;
await writeOpenClawConfig(config);
logger.info('Cleared all bindings for channel', { channelType });
});
logger.info('Cleared all bindings for channel', { channelType });
}
function migrateLegacyChannelBindingInConfig(
config: AgentConfigDocument,
channelType: string,
validAgentIds: Set<string>,
): void {
const { channelToAgent, accountToAgent } = getChannelBindingMap(config.bindings);
const legacyOwner = channelToAgent.get(channelType);
if (!legacyOwner) return;
const explicitDefaultOwner = accountToAgent.get(`${channelType}:${DEFAULT_ACCOUNT_ID}`);
const defaultOwner = explicitDefaultOwner && validAgentIds.has(explicitDefaultOwner)
? explicitDefaultOwner
: (validAgentIds.has(legacyOwner) ? legacyOwner : null);
if (defaultOwner) {
config.bindings = upsertBindingsForChannel(
config.bindings,
channelType,
defaultOwner,
DEFAULT_ACCOUNT_ID,
);
}
config.bindings = upsertBindingsForChannel(config.bindings, channelType, null);
}
export async function migrateLegacyChannelWideBinding(channelType: string): Promise<void> {
await mutateOpenClawConfig((configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
const { entries } = normalizeAgentsConfig(config);
const validAgentIds = new Set(entries.map((entry) => normalizeAgentIdForBinding(entry.id)));
migrateLegacyChannelBindingInConfig(config, channelType, validAgentIds);
});
logger.info('Migrated legacy channel-wide binding', { channelType });
}
export async function ensureScopedChannelBinding(channelType: string, accountId?: string): Promise<void> {
const normalizedAccountId = accountId?.trim();
if (!normalizedAccountId) return;
await mutateOpenClawConfig((configSnapshot) => {
const config = configSnapshot as AgentConfigDocument;
const { entries } = normalizeAgentsConfig(config);
if (entries.length === 0) return;
const validAgentIds = new Set(entries.map((entry) => normalizeAgentIdForBinding(entry.id)));
if (normalizedAccountId === DEFAULT_ACCOUNT_ID) {
const mainAgent = entries.find((entry) => entry.id === MAIN_AGENT_ID);
if (mainAgent) {
config.bindings = upsertBindingsForChannel(
config.bindings,
channelType,
mainAgent.id,
DEFAULT_ACCOUNT_ID,
);
}
return;
}
migrateLegacyChannelBindingInConfig(config, channelType, validAgentIds);
const accountAgent = entries.find((entry) => entry.id === normalizedAccountId);
if (accountAgent) {
config.bindings = upsertBindingsForChannel(
config.bindings,
channelType,
accountAgent.id,
normalizedAccountId,
);
}
});
logger.info('Ensured scoped channel binding', { channelType, accountId: normalizedAccountId });
}
+1 -1
View File
@@ -19,7 +19,7 @@ import {
export type BrowserOAuthProviderType = 'openai';
const OPENAI_RUNTIME_PROVIDER_ID = 'openai';
const OPENAI_OAUTH_DEFAULT_MODEL = 'gpt-5.5';
const OPENAI_OAUTH_DEFAULT_MODEL = 'gpt-5.6-sol';
class BrowserOAuthManager extends EventEmitter {
private activeAccountId: string | null = null;
+213 -195
View File
@@ -8,10 +8,10 @@ import { access, mkdir, readFile, writeFile, readdir, stat, rm } from 'fs/promis
import { constants } from 'fs';
import { join } from 'path';
import { homedir } from 'os';
import { getOpenClawResolvedDir } from './paths';
import { mutateOpenClawConfig, readOpenClawConfigSnapshot } from '../gateway/config-delivery';
import { getOpenClawResolvedDir, resolveOpenClawConfigPath } from './paths';
import * as logger from './logger';
import { proxyAwareFetch } from './proxy-fetch';
import { withConfigLock } from './config-mutex';
import {
OPENCLAW_WECHAT_CHANNEL_TYPE,
isWechatChannelType,
@@ -20,9 +20,7 @@ import {
} from './channel-alias';
const OPENCLAW_DIR = join(homedir(), '.openclaw');
const CONFIG_FILE = join(OPENCLAW_DIR, 'openclaw.json');
const WECOM_PLUGIN_ID = 'wecom';
// Note: QQBot is a built-in channel since OpenClaw 3.31 — no plugin ID needed.
const WECHAT_PLUGIN_ID = OPENCLAW_WECHAT_CHANNEL_TYPE;
const FEISHU_PLUGIN_ID_CANDIDATES = ['openclaw-lark', 'feishu-openclaw-plugin'] as const;
const DEFAULT_ACCOUNT_ID = 'default';
@@ -61,23 +59,13 @@ const WECHAT_ACCOUNTS_DIR = join(WECHAT_STATE_DIR, 'accounts');
const LEGACY_WECHAT_CREDENTIALS_DIR = join(OPENCLAW_DIR, 'credentials', WECHAT_PLUGIN_ID);
const LEGACY_WECHAT_SYNC_DIR = join(OPENCLAW_DIR, 'agents', 'default', 'sessions', '.openclaw-weixin-sync');
// Channels that are managed as plugins (config goes under plugins.entries, not channels)
// External plugins whose activation lives in plugins.entries while account
// configuration remains exclusively under channels.<id>.
const PLUGIN_CHANNELS: string[] = ['discord', 'qqbot', 'whatsapp'];
const LEGACY_BUILTIN_CHANNEL_PLUGIN_IDS = new Set<string>();
const BUILTIN_CHANNEL_IDS = new Set([
'discord',
'telegram',
'whatsapp',
'slack',
'signal',
'imessage',
'matrix',
'line',
'msteams',
'googlechat',
'mattermost',
'qqbot',
]);
// OpenClaw 2026.7.1 bundles only these channel extensions. All other ClawX
// channels must retain their explicit external plugin allowlist entries.
const BUILTIN_CHANNEL_IDS = new Set(['telegram', 'imessage']);
// Unique credential key per channel type used for duplicate bot detection.
// Maps each channel type to the field that uniquely identifies a bot/account.
@@ -154,10 +142,16 @@ function sanitizeDiscordGuilds(config: unknown): void {
/**
* Strip `defaultAccount` from channel sections whose plugin schema
* declares additionalProperties:false without listing `defaultAccount`.
* Call right before every `writeOpenClawConfig` in channel-config
* mutation functions.
* Call before committing channel-config mutations.
*/
function sanitizeChannelSectionsBeforeWrite(config: OpenClawConfig): void {
for (const pluginId of PLUGIN_CHANNELS) {
const pluginEntry = config.plugins?.entries?.[pluginId];
if (!pluginEntry) continue;
delete pluginEntry.accounts;
delete pluginEntry.defaultAccount;
}
if (!config.channels) return;
for (const channelType of CHANNELS_OMIT_DEFAULT_ACCOUNT_KEY) {
const section = config.channels[channelType];
@@ -363,7 +357,24 @@ function ensurePluginRegistration(currentConfig: OpenClawConfig, pluginId: strin
if (!currentConfig.plugins.entries[pluginId]) {
currentConfig.plugins.entries[pluginId] = {};
}
currentConfig.plugins.entries[pluginId].enabled = true;
const pluginEntry = currentConfig.plugins.entries[pluginId];
// PluginEntryConfig contains plugin activation/config metadata, not channel
// accounts. Older ClawX versions mirrored credentials here, which OpenClaw
// 2026.7.1 rejects as an invalid plugins.entries.<id> shape.
delete pluginEntry.accounts;
delete pluginEntry.defaultAccount;
pluginEntry.enabled = true;
}
function syncPluginChannelRegistration(currentConfig: OpenClawConfig, channelType: string): void {
if (!PLUGIN_CHANNELS.includes(channelType)) return;
const channelSection = currentConfig.channels?.[channelType];
if (!channelSection) {
removePluginRegistration(currentConfig, channelType);
return;
}
ensurePluginRegistration(currentConfig, channelType);
currentConfig.plugins!.entries![channelType].enabled = channelSection.enabled !== false;
}
function cleanupLegacyBuiltInChannelPluginRegistration(
@@ -455,22 +466,10 @@ export interface OpenClawConfig {
// ── Config I/O ───────────────────────────────────────────────────
async function ensureConfigDir(): Promise<void> {
if (!(await fileExists(OPENCLAW_DIR))) {
await mkdir(OPENCLAW_DIR, { recursive: true });
}
}
export async function readOpenClawConfig(): Promise<OpenClawConfig> {
await ensureConfigDir();
if (!(await fileExists(CONFIG_FILE))) {
return {};
}
try {
const content = await readFile(CONFIG_FILE, 'utf-8');
return JSON.parse(content) as OpenClawConfig;
const snapshot = await readOpenClawConfigSnapshot();
return snapshot.config as OpenClawConfig;
} catch (error) {
logger.error('Failed to read OpenClaw config', error);
console.error('Failed to read OpenClaw config:', error);
@@ -478,26 +477,6 @@ export async function readOpenClawConfig(): Promise<OpenClawConfig> {
}
}
export async function writeOpenClawConfig(config: OpenClawConfig): Promise<void> {
await ensureConfigDir();
try {
// Enable graceful in-process reload authorization for SIGUSR1 flows.
const commands =
config.commands && typeof config.commands === 'object'
? { ...(config.commands as Record<string, unknown>) }
: {};
commands.restart = true;
config.commands = commands;
await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');
} catch (error) {
logger.error('Failed to write OpenClaw config', error);
console.error('Failed to write OpenClaw config:', error);
throw error;
}
}
// ── Channel operations ───────────────────────────────────────────
async function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType: string): Promise<void> {
@@ -505,10 +484,6 @@ async function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType:
ensurePluginRegistration(currentConfig, channelType);
}
if (channelType === 'discord' || channelType === 'qqbot' || channelType === 'whatsapp') {
ensurePluginRegistration(currentConfig, channelType);
}
if (channelType === 'feishu') {
const feishuPluginId = await resolveFeishuPluginId();
if (!currentConfig.plugins) {
@@ -599,8 +574,6 @@ async function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType:
}
}
// Note: QQBot is a built-in channel since OpenClaw 3.31 — no plugin registration needed.
if (channelType === WECHAT_PLUGIN_ID) {
if (!currentConfig.plugins) {
currentConfig.plugins = {
@@ -832,17 +805,19 @@ export async function saveChannelConfig(
config: ChannelConfigData,
accountId?: string,
): Promise<void> {
return withConfigLock(async () => {
const resolvedChannelType = resolveStoredChannelType(channelType);
const currentConfig = await readOpenClawConfig();
const resolvedAccountId = accountId || DEFAULT_ACCOUNT_ID;
const resolvedChannelType = resolveStoredChannelType(channelType);
const resolvedAccountId = accountId || DEFAULT_ACCOUNT_ID;
let transformedKeys: string[] = [];
await mutateOpenClawConfig(async (snapshot) => {
const currentConfig = snapshot as OpenClawConfig;
cleanupLegacyBuiltInChannelPluginRegistration(currentConfig, resolvedChannelType);
await ensurePluginAllowlist(currentConfig, resolvedChannelType);
syncBuiltinChannelsWithPluginAllowlist(currentConfig, [resolvedChannelType]);
// Plugin-based channels are mirrored into plugins.entries.<id> below,
// but ClawX still keeps channels.<id> as the local account-list source.
// Channel credentials always live under channels.<id>. External plugin
// entries carry activation metadata only.
if (!currentConfig.channels) {
currentConfig.channels = {};
@@ -859,6 +834,7 @@ export async function saveChannelConfig(
const existingAccountConfig = resolveAccountConfig(channelSection, resolvedAccountId);
const transformedConfig = transformChannelConfig(resolvedChannelType, config, existingAccountConfig);
transformedKeys = Object.keys(transformedConfig);
const uniqueKey = CHANNEL_UNIQUE_CREDENTIAL_KEY[resolvedChannelType];
if (uniqueKey && typeof transformedConfig[uniqueKey] === 'string') {
const rawCredentialValue = transformedConfig[uniqueKey] as string;
@@ -889,20 +865,7 @@ export async function saveChannelConfig(
// read channels.<type>.enabled still work.
channelSection.enabled = transformedConfig.enabled ?? channelSection.enabled ?? true;
// Plugin-backed channel packages read their activation/config from
// plugins.entries.<id>. Mirror the enabled flag and account map there
// while preserving channels.<id> for ClawX's account list UI.
if (PLUGIN_CHANNELS.includes(resolvedChannelType)) {
ensurePluginRegistration(currentConfig, resolvedChannelType);
const pluginEntry = currentConfig.plugins!.entries![resolvedChannelType];
const pluginAccounts = ensureChannelAccountsMap(pluginEntry);
pluginEntry.defaultAccount = channelSection.defaultAccount;
pluginEntry.enabled = channelSection.enabled;
pluginAccounts[resolvedAccountId] = {
...pluginAccounts[resolvedAccountId],
...accounts[resolvedAccountId],
};
}
syncPluginChannelRegistration(currentConfig, resolvedChannelType);
// Most OpenClaw channel plugins/built-ins also read the default
// account's credentials from the top level of `channels.<type>`
@@ -920,16 +883,15 @@ export async function saveChannelConfig(
}
sanitizeChannelSectionsBeforeWrite(currentConfig);
await writeOpenClawConfig(currentConfig);
logger.info('Channel config saved', {
channelType: resolvedChannelType,
accountId: resolvedAccountId,
configFile: CONFIG_FILE,
rawKeys: Object.keys(config),
transformedKeys: Object.keys(transformedConfig),
});
console.log(`Saved channel config for ${resolvedChannelType} account ${resolvedAccountId}`);
});
logger.info('Channel config saved', {
channelType: resolvedChannelType,
accountId: resolvedAccountId,
configFile: resolveOpenClawConfigPath(),
rawKeys: Object.keys(config),
transformedKeys,
});
console.log(`Saved channel config for ${resolvedChannelType} account ${resolvedAccountId}`);
}
export async function getChannelConfig(channelType: string, accountId?: string): Promise<ChannelConfigData | undefined> {
@@ -1003,40 +965,46 @@ export async function getChannelFormValues(channelType: string, accountId?: stri
}
export async function deleteChannelAccountConfig(channelType: string, accountId: string): Promise<void> {
return withConfigLock(async () => {
const resolvedChannelType = resolveStoredChannelType(channelType);
const currentConfig = await readOpenClawConfig();
const resolvedChannelType = resolveStoredChannelType(channelType);
let deleteWeChatAccount = false;
let deletedAccount = false;
await mutateOpenClawConfig((snapshot) => {
deleteWeChatAccount = false;
deletedAccount = false;
const currentConfig = snapshot as OpenClawConfig;
const channelSection = currentConfig.channels?.[resolvedChannelType];
if (!channelSection) {
if (isWechatChannelType(resolvedChannelType)) {
removePluginRegistration(currentConfig, WECHAT_PLUGIN_ID);
await writeOpenClawConfig(currentConfig);
await deleteWeChatAccountState(accountId);
deleteWeChatAccount = true;
} else if (PLUGIN_CHANNELS.includes(resolvedChannelType)) {
removePluginRegistration(currentConfig, resolvedChannelType);
}
return;
}
migrateLegacyChannelConfigToAccounts(channelSection, DEFAULT_ACCOUNT_ID);
const existingAccounts = getChannelAccountsMap(channelSection);
const targetsLegacyDefault = accountId === DEFAULT_ACCOUNT_ID
&& Object.keys(getLegacyChannelPayload(channelSection)).length > 0;
if (!existingAccounts?.[accountId] && !targetsLegacyDefault) return;
const currentDefaultAccountId = typeof channelSection.defaultAccount === 'string'
&& channelSection.defaultAccount.trim()
? channelSection.defaultAccount.trim()
: DEFAULT_ACCOUNT_ID;
migrateLegacyChannelConfigToAccounts(channelSection, currentDefaultAccountId);
const accounts = getChannelAccountsMap(channelSection);
if (!accounts?.[accountId]) {
// Account not found; just ensure top-level mirror is consistent
const mirroredAccountId = typeof channelSection.defaultAccount === 'string' && channelSection.defaultAccount.trim() ? channelSection.defaultAccount : DEFAULT_ACCOUNT_ID;
const defaultAccountData = accounts?.[mirroredAccountId] ?? accounts?.[DEFAULT_ACCOUNT_ID];
if (defaultAccountData) {
for (const [key, value] of Object.entries(defaultAccountData)) {
channelSection[key] = value;
}
}
return;
}
if (!accounts?.[accountId]) return;
delete accounts[accountId];
deletedAccount = true;
if (Object.keys(accounts).length === 0) {
delete currentConfig.channels![resolvedChannelType];
if (isWechatChannelType(resolvedChannelType)) {
removePluginRegistration(currentConfig, WECHAT_PLUGIN_ID);
} else if (PLUGIN_CHANNELS.includes(resolvedChannelType)) {
removePluginRegistration(currentConfig, resolvedChannelType);
}
} else {
if (channelSection.defaultAccount === accountId) {
@@ -1064,21 +1032,31 @@ export async function deleteChannelAccountConfig(channelType: string, accountId:
}
}
syncPluginChannelRegistration(currentConfig, resolvedChannelType);
syncBuiltinChannelsWithPluginAllowlist(currentConfig);
sanitizeChannelSectionsBeforeWrite(currentConfig);
await writeOpenClawConfig(currentConfig);
if (isWechatChannelType(resolvedChannelType)) {
await deleteWeChatAccountState(accountId);
deleteWeChatAccount = true;
}
});
if (deleteWeChatAccount) {
await deleteWeChatAccountState(accountId);
}
if (deletedAccount) {
logger.info('Deleted channel account config', { channelType: resolvedChannelType, accountId });
console.log(`Deleted channel account config for ${resolvedChannelType}/${accountId}`);
});
}
}
export async function deleteChannelConfig(channelType: string): Promise<void> {
return withConfigLock(async () => {
const resolvedChannelType = resolveStoredChannelType(channelType);
const currentConfig = await readOpenClawConfig();
const resolvedChannelType = resolveStoredChannelType(channelType);
let deleteWeChat = false;
let deletedConfig: 'channel' | 'plugin' | undefined;
await mutateOpenClawConfig((snapshot) => {
deleteWeChat = false;
deletedConfig = undefined;
const currentConfig = snapshot as OpenClawConfig;
cleanupLegacyBuiltInChannelPluginRegistration(currentConfig, resolvedChannelType);
if (currentConfig.channels?.[resolvedChannelType]) {
@@ -1102,38 +1080,47 @@ export async function deleteChannelConfig(channelType: string): Promise<void> {
if (resolvedChannelType === 'wecom') {
removePluginRegistration(currentConfig, WECOM_PLUGIN_ID);
}
syncBuiltinChannelsWithPluginAllowlist(currentConfig);
await writeOpenClawConfig(currentConfig);
if (isWechatChannelType(resolvedChannelType)) {
await deleteWeChatState();
if (PLUGIN_CHANNELS.includes(resolvedChannelType)) {
removePluginRegistration(currentConfig, resolvedChannelType);
}
console.log(`Deleted channel config for ${resolvedChannelType}`);
syncBuiltinChannelsWithPluginAllowlist(currentConfig);
if (isWechatChannelType(resolvedChannelType)) {
deleteWeChat = true;
}
deletedConfig = 'channel';
} else if (PLUGIN_CHANNELS.includes(resolvedChannelType)) {
if (currentConfig.plugins?.entries?.[resolvedChannelType] || currentConfig.plugins?.allow?.includes(resolvedChannelType)) {
removePluginRegistration(currentConfig, resolvedChannelType);
syncBuiltinChannelsWithPluginAllowlist(currentConfig);
await writeOpenClawConfig(currentConfig);
console.log(`Deleted plugin channel config for ${resolvedChannelType}`);
deletedConfig = 'plugin';
}
} else if (isWechatChannelType(resolvedChannelType)) {
removePluginRegistration(currentConfig, WECHAT_PLUGIN_ID);
syncBuiltinChannelsWithPluginAllowlist(currentConfig);
await writeOpenClawConfig(currentConfig);
await deleteWeChatState();
}
if (resolvedChannelType === 'whatsapp') {
try {
const whatsappDir = join(homedir(), '.openclaw', 'credentials', 'whatsapp');
if (await fileExists(whatsappDir)) {
await rm(whatsappDir, { recursive: true, force: true });
console.log('Deleted WhatsApp credentials directory');
}
} catch (error) {
console.error('Failed to delete WhatsApp credentials:', error);
}
deleteWeChat = true;
}
});
if (deleteWeChat) {
await deleteWeChatState();
}
if (deletedConfig === 'channel') {
console.log(`Deleted channel config for ${resolvedChannelType}`);
} else if (deletedConfig === 'plugin') {
console.log(`Deleted plugin channel config for ${resolvedChannelType}`);
}
if (resolvedChannelType === 'whatsapp') {
try {
const whatsappDir = join(homedir(), '.openclaw', 'credentials', 'whatsapp');
if (await fileExists(whatsappDir)) {
await rm(whatsappDir, { recursive: true, force: true });
console.log('Deleted WhatsApp credentials directory');
}
} catch (error) {
console.error('Failed to delete WhatsApp credentials:', error);
}
}
}
function channelHasAnyAccount(channelSection: ChannelConfigData): boolean {
@@ -1247,14 +1234,14 @@ export async function listConfiguredChannelAccounts(): Promise<Record<string, Co
}
export async function setChannelDefaultAccount(channelType: string, accountId: string): Promise<void> {
return withConfigLock(async () => {
const resolvedChannelType = resolveStoredChannelType(channelType);
const trimmedAccountId = accountId.trim();
if (!trimmedAccountId) {
throw new Error('accountId is required');
}
const resolvedChannelType = resolveStoredChannelType(channelType);
const trimmedAccountId = accountId.trim();
if (!trimmedAccountId) {
throw new Error('accountId is required');
}
const currentConfig = await readOpenClawConfig();
await mutateOpenClawConfig((snapshot) => {
const currentConfig = snapshot as OpenClawConfig;
const channelSection = currentConfig.channels?.[resolvedChannelType];
if (!channelSection) {
throw new Error(`Channel "${resolvedChannelType}" is not configured`);
@@ -1275,38 +1262,72 @@ export async function setChannelDefaultAccount(channelType: string, accountId: s
}
sanitizeChannelSectionsBeforeWrite(currentConfig);
await writeOpenClawConfig(currentConfig);
logger.info('Set channel default account', { channelType: resolvedChannelType, accountId: trimmedAccountId });
});
logger.info('Set channel default account', { channelType: resolvedChannelType, accountId: trimmedAccountId });
}
export async function deleteAgentChannelAccounts(agentId: string, ownedChannelAccounts?: Set<string>): Promise<void> {
return withConfigLock(async () => {
const currentConfig = await readOpenClawConfig();
if (!currentConfig.channels) return;
let modified = false;
const accountId = agentId === 'main' ? DEFAULT_ACCOUNT_ID : agentId;
const accountId = agentId === 'main' ? DEFAULT_ACCOUNT_ID : agentId;
let modified = false;
await mutateOpenClawConfig((snapshot) => {
modified = false;
const currentConfig = snapshot as OpenClawConfig;
const channels = currentConfig.channels ?? {};
for (const channelType of Object.keys(currentConfig.channels)) {
const section = currentConfig.channels[channelType];
migrateLegacyChannelConfigToAccounts(section, DEFAULT_ACCOUNT_ID);
const accounts = getChannelAccountsMap(section);
if (!accounts?.[accountId] || (ownedChannelAccounts && !ownedChannelAccounts.has(`${channelType}:${accountId}`))) {
// Ensure top-level mirror is consistent.
const mirroredAccountId = typeof section.defaultAccount === 'string' && section.defaultAccount.trim() ? section.defaultAccount : DEFAULT_ACCOUNT_ID;
const defaultAccountData = accounts?.[mirroredAccountId] ?? accounts?.[DEFAULT_ACCOUNT_ID];
if (defaultAccountData) {
for (const [key, value] of Object.entries(defaultAccountData)) {
section[key] = value;
}
// Older ClawX releases could leave the only copy of Discord, QQBot,
// or WhatsApp account credentials under plugins.entries.<id>. Migrate
// that invalid legacy shape into channels.<id> before deleting the
// owned account, so sibling accounts survive while PluginEntryConfig
// is normalized back to activation metadata only.
const legacyPluginChannelTypes = ownedChannelAccounts
? [...ownedChannelAccounts]
.filter((channelAccountKey) => channelAccountKey.endsWith(`:${accountId}`))
.map((channelAccountKey) => channelAccountKey.slice(0, -accountId.length - 1))
: PLUGIN_CHANNELS;
for (const channelType of legacyPluginChannelTypes) {
if (!PLUGIN_CHANNELS.includes(channelType)) continue;
const pluginEntry = currentConfig.plugins?.entries?.[channelType];
const pluginAccounts = pluginEntry ? getChannelAccountsMap(pluginEntry) : undefined;
if (!pluginEntry || !pluginAccounts?.[accountId]) continue;
const section = channels[channelType] ?? {
enabled: pluginEntry.enabled !== false,
};
const channelAccounts = ensureChannelAccountsMap(section);
for (const [legacyAccountId, legacyAccountConfig] of Object.entries(pluginAccounts)) {
if (!channelAccounts[legacyAccountId]) {
channelAccounts[legacyAccountId] = structuredClone(legacyAccountConfig);
}
continue;
}
if (typeof section.defaultAccount !== 'string' || !section.defaultAccount.trim()) {
section.defaultAccount = typeof pluginEntry.defaultAccount === 'string'
? pluginEntry.defaultAccount
: DEFAULT_ACCOUNT_ID;
}
channels[channelType] = section;
currentConfig.channels = channels;
}
for (const channelType of Object.keys(channels)) {
if (ownedChannelAccounts && !ownedChannelAccounts.has(`${channelType}:${accountId}`)) continue;
const section = channels[channelType];
const existingAccounts = getChannelAccountsMap(section);
const targetsLegacyDefault = accountId === DEFAULT_ACCOUNT_ID
&& Object.keys(getLegacyChannelPayload(section)).length > 0;
if (!existingAccounts?.[accountId] && !targetsLegacyDefault) continue;
const currentDefaultAccountId = typeof section.defaultAccount === 'string'
&& section.defaultAccount.trim()
? section.defaultAccount.trim()
: DEFAULT_ACCOUNT_ID;
migrateLegacyChannelConfigToAccounts(section, currentDefaultAccountId);
const accounts = getChannelAccountsMap(section);
if (!accounts?.[accountId]) continue;
delete accounts[accountId];
if (Object.keys(accounts).length === 0) {
delete currentConfig.channels[channelType];
delete channels[channelType];
} else {
if (section.defaultAccount === accountId) {
const nextDefaultAccountId = Object.keys(accounts).sort((a, b) => {
@@ -1331,21 +1352,26 @@ export async function deleteAgentChannelAccounts(agentId: string, ownedChannelAc
}
}
}
syncPluginChannelRegistration(currentConfig, channelType);
modified = true;
}
if (modified) {
sanitizeChannelSectionsBeforeWrite(currentConfig);
await writeOpenClawConfig(currentConfig);
logger.info('Deleted all channel accounts for agent', { agentId, accountId });
}
});
if (modified) {
logger.info('Deleted all channel accounts for agent', { agentId, accountId });
}
}
export async function setChannelEnabled(channelType: string, enabled: boolean): Promise<void> {
return withConfigLock(async () => {
const resolvedChannelType = resolveStoredChannelType(channelType);
const currentConfig = await readOpenClawConfig();
const resolvedChannelType = resolveStoredChannelType(channelType);
let pluginChannel = false;
await mutateOpenClawConfig(async (snapshot) => {
pluginChannel = false;
const currentConfig = snapshot as OpenClawConfig;
cleanupLegacyBuiltInChannelPluginRegistration(currentConfig, resolvedChannelType);
if (isWechatChannelType(resolvedChannelType)) {
@@ -1357,53 +1383,45 @@ export async function setChannelEnabled(channelType: string, enabled: boolean):
}
if (PLUGIN_CHANNELS.includes(resolvedChannelType)) {
if (enabled) {
ensurePluginRegistration(currentConfig, resolvedChannelType);
} else {
const plugins = currentConfig.plugins ?? (currentConfig.plugins = {});
const entries = plugins.entries ?? (plugins.entries = {});
entries[resolvedChannelType] ??= {};
}
const entries = currentConfig.plugins?.entries;
const pluginEntry = entries?.[resolvedChannelType];
if (!pluginEntry) throw new Error(`Plugin entry not initialized: ${resolvedChannelType}`);
pluginEntry.enabled = enabled;
syncBuiltinChannelsWithPluginAllowlist(currentConfig);
await writeOpenClawConfig(currentConfig);
console.log(`Set plugin channel ${resolvedChannelType} enabled: ${enabled}`);
return;
pluginChannel = true;
ensurePluginRegistration(currentConfig, resolvedChannelType);
currentConfig.plugins!.entries![resolvedChannelType].enabled = enabled;
}
if (!currentConfig.channels) currentConfig.channels = {};
if (!currentConfig.channels[resolvedChannelType]) currentConfig.channels[resolvedChannelType] = {};
currentConfig.channels[resolvedChannelType].enabled = enabled;
syncBuiltinChannelsWithPluginAllowlist(currentConfig, enabled ? [resolvedChannelType] : []);
await writeOpenClawConfig(currentConfig);
console.log(`Set channel ${resolvedChannelType} enabled: ${enabled}`);
});
console.log(`Set ${pluginChannel ? 'plugin channel' : 'channel'} ${resolvedChannelType} enabled: ${enabled}`);
}
export async function cleanupDanglingWeChatPluginState(): Promise<{ cleanedDanglingState: boolean }> {
return withConfigLock(async () => {
const currentConfig = await readOpenClawConfig();
let cleanedDanglingState = false;
let hasConfiguredWeChatAccounts = false;
await mutateOpenClawConfig((snapshot) => {
cleanedDanglingState = false;
hasConfiguredWeChatAccounts = false;
const currentConfig = snapshot as OpenClawConfig;
const channelSection = currentConfig.channels?.[WECHAT_PLUGIN_ID];
const hasConfiguredWeChatAccounts = channelHasConfiguredAccounts(channelSection);
hasConfiguredWeChatAccounts = channelHasConfiguredAccounts(channelSection);
const hadPluginRegistration = Boolean(
currentConfig.plugins?.entries?.[WECHAT_PLUGIN_ID]
|| currentConfig.plugins?.allow?.includes(WECHAT_PLUGIN_ID),
);
if (hasConfiguredWeChatAccounts) {
return { cleanedDanglingState: false };
return;
}
const modified = removePluginRegistration(currentConfig, WECHAT_PLUGIN_ID);
if (modified) {
await writeOpenClawConfig(currentConfig);
}
await deleteWeChatState();
return { cleanedDanglingState: hadPluginRegistration || modified };
cleanedDanglingState = hadPluginRegistration || modified;
});
if (!hasConfiguredWeChatAccounts) {
await deleteWeChatState();
}
return { cleanedDanglingState };
}
// ── Validation ───────────────────────────────────────────────────
+85 -31
View File
@@ -12,6 +12,19 @@ import { getUvMirrorEnv } from './uv-env';
/** Browser Control UI client id used in OpenClaw 2026.5.x connect frames. */
export const CONTROL_UI_BROWSER_CLIENT_ID = 'openclaw-control-ui';
/** ClawX Gateway WebSocket client id used in connect frames. */
export const GATEWAY_UI_CLIENT_ID = 'gateway-client';
/** OpenClaw embedded CLI client id (ACP bridge, doctor, etc.). */
export const OPENCLAW_CLI_CLIENT_ID = 'cli';
/** Loopback-only clients that ClawX auto-approves without user interaction. */
export const LOCAL_AUTO_APPROVE_CLIENT_IDS = new Set([
CONTROL_UI_BROWSER_CLIENT_ID,
GATEWAY_UI_CLIENT_ID,
OPENCLAW_CLI_CLIENT_ID,
]);
export type PendingDevicePairingRequest = {
requestId?: string;
clientId?: string;
@@ -46,6 +59,11 @@ export function isControlUiBrowserPairingRequest(request: PendingDevicePairingRe
return clientId === CONTROL_UI_BROWSER_CLIENT_ID;
}
export function isLocalLoopbackDeviceAutoApprovalRequest(request: PendingDevicePairingRequest): boolean {
const clientId = typeof request.clientId === 'string' ? request.clientId.trim() : '';
return LOCAL_AUTO_APPROVE_CLIENT_IDS.has(clientId);
}
function parseDevicePairingList(value: unknown): DevicePairingList {
const record = typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {};
return {
@@ -206,10 +224,10 @@ function sleep(ms: number, signal: { cancelled: boolean }): Promise<void> {
}
/**
* Approve pending Control UI browser pairing requests.
* Approve pending loopback device pairing / scope-upgrade requests for trusted local clients.
* Uses Gateway RPC when available; falls back to local pending.json + embedded CLI on Windows packaged builds.
*/
export async function approvePendingControlUiPairingRequests(
export async function approvePendingLocalDeviceRequests(
gateway: GatewayPairingRpcClient,
options?: { approvedRequestIds?: Set<string> },
): Promise<string[]> {
@@ -219,7 +237,7 @@ export async function approvePendingControlUiPairingRequests(
const approved: string[] = [];
for (const request of pending) {
if (!isControlUiBrowserPairingRequest(request)) continue;
if (!isLocalLoopbackDeviceAutoApprovalRequest(request)) continue;
const requestId = typeof request.requestId === 'string' ? request.requestId.trim() : '';
if (!requestId || approvedRequestIds.has(requestId)) continue;
@@ -230,11 +248,11 @@ export async function approvePendingControlUiPairingRequests(
approvedRequestIds.add(requestId);
approved.push(requestId);
logger.info(
`[control-ui] Auto-approved browser device pairing (requestId=${requestId}, mode=${request.clientMode ?? 'unknown'})`,
`[device-auto-approve] Auto-approved local device request (requestId=${requestId}, clientId=${request.clientId ?? 'unknown'}, mode=${request.clientMode ?? 'unknown'})`,
);
} catch (error) {
logger.warn(
`[control-ui] Failed to auto-approve pairing request ${requestId}: ${String(error)}`,
`[device-auto-approve] Failed to auto-approve request ${requestId}: ${String(error)}`,
);
}
}
@@ -242,26 +260,78 @@ export async function approvePendingControlUiPairingRequests(
return approved;
}
async function watchControlUiPairingApprovals(
/**
* Approve pending Control UI browser pairing requests.
* @deprecated Prefer approvePendingLocalDeviceRequests.
*/
export async function approvePendingControlUiPairingRequests(
gateway: GatewayPairingRpcClient,
options?: { approvedRequestIds?: Set<string> },
): Promise<string[]> {
return approvePendingLocalDeviceRequests(gateway, options);
}
async function watchLocalDeviceApprovals(
gateway: GatewayPairingRpcClient,
signal: { cancelled: boolean },
timeoutMs: number,
timeoutMs: number | null,
pollIntervalMs: number,
): Promise<void> {
const approvedRequestIds = new Set<string>();
const deadline = Date.now() + timeoutMs;
const deadline = timeoutMs == null ? null : Date.now() + timeoutMs;
while (!signal.cancelled && Date.now() < deadline) {
while (!signal.cancelled && (deadline == null || Date.now() < deadline)) {
try {
await approvePendingControlUiPairingRequests(gateway, { approvedRequestIds });
await approvePendingLocalDeviceRequests(gateway, { approvedRequestIds });
} catch (error) {
logger.debug(`[control-ui] Pairing poll error: ${String(error)}`);
logger.debug(`[device-auto-approve] Poll error: ${String(error)}`);
}
await sleep(pollIntervalMs, signal);
}
}
export function cancelLocalDeviceAutoApproval(): void {
activeWatcher?.cancel();
activeWatcher = null;
}
/**
* Poll for loopback device pairing / scope-upgrade requests and approve them locally.
* Safe to call repeatedly; only one watcher runs at a time.
*/
export function scheduleLocalDeviceAutoApproval(
gateway: GatewayPairingRpcClient,
options?: {
/** Omit or pass null to poll until cancelLocalDeviceAutoApproval() is called. */
timeoutMs?: number | null;
pollIntervalMs?: number;
},
): void {
activeWatcher?.cancel();
const signal = { cancelled: false };
const cancel = () => {
signal.cancelled = true;
};
activeWatcher = { cancel };
const timeoutMs = options?.timeoutMs === undefined
? null
: options.timeoutMs;
const pollIntervalMs = options?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
void watchLocalDeviceApprovals(gateway, signal, timeoutMs, pollIntervalMs)
.catch((error) => {
logger.warn(`[device-auto-approve] Auto-approval watcher failed: ${String(error)}`);
})
.finally(() => {
if (activeWatcher?.cancel === cancel) {
activeWatcher = null;
}
});
}
/**
* Poll for Control UI browser pairing requests and approve them locally.
* Safe to call repeatedly; only one watcher runs at a time.
@@ -273,24 +343,8 @@ export function scheduleControlUiDeviceAutoApproval(
pollIntervalMs?: number;
},
): void {
activeWatcher?.cancel();
const signal = { cancelled: false };
const cancel = () => {
signal.cancelled = true;
};
activeWatcher = { cancel };
const timeoutMs = resolveWatchTimeoutMs(options?.timeoutMs);
const pollIntervalMs = options?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
void watchControlUiPairingApprovals(gateway, signal, timeoutMs, pollIntervalMs)
.catch((error) => {
logger.warn(`[control-ui] Auto-approval watcher failed: ${String(error)}`);
})
.finally(() => {
if (activeWatcher?.cancel === cancel) {
activeWatcher = null;
}
});
scheduleLocalDeviceAutoApproval(gateway, {
timeoutMs: resolveWatchTimeoutMs(options?.timeoutMs),
pollIntervalMs: options?.pollIntervalMs,
});
}
File diff suppressed because it is too large Load Diff
+170 -14
View File
@@ -11,9 +11,9 @@ import {
symlinkSync,
unlinkSync,
} from 'node:fs';
import { spawn } from 'node:child_process';
import { spawn, type ForkOptions } from 'node:child_process';
import { homedir } from 'node:os';
import { join, dirname } from 'node:path';
import { delimiter, join, dirname } from 'node:path';
import { getOpenClawDir, getOpenClawEntryPath } from './paths';
import { logger } from './logger';
@@ -98,6 +98,158 @@ export function getOpenClawCliCommand(): string {
return `node ${quoteForPosix(entryPath)}`;
}
export type OpenClawCliSpawnSpec = {
command: string;
args: string[];
env?: NodeJS.ProcessEnv;
shell?: boolean;
};
type OpenClawEmbeddedForkOptions = ForkOptions & { windowsHide?: boolean };
export type OpenClawEmbeddedForkSpec = {
modulePath: string;
args: string[];
options: OpenClawEmbeddedForkOptions;
};
function fileExists(path: string): boolean {
return existsSync(path);
}
function getWindowsCmdWrapperSpawnSpec(cmdPath: string): OpenClawCliSpawnSpec {
return {
command: process.env.ComSpec || 'cmd.exe',
args: ['/d', '/s', '/c', `"${cmdPath}"`],
};
}
function getExecutableFromPath(command: string): string | null {
const pathEnv = process.env.PATH || '';
for (const dir of pathEnv.split(delimiter)) {
if (!dir) continue;
const candidate = join(dir, command);
if (fileExists(candidate)) return candidate;
}
return null;
}
function getDevNodeExecPath(): string | null {
const nodeCommand = process.platform === 'win32' ? 'node.exe' : 'node';
return getExecutableFromPath(nodeCommand);
}
export function getOpenClawCliSpawnSpec(): OpenClawCliSpawnSpec {
const entryPath = getOpenClawEntryPath();
const platform = process.platform;
if (platform === 'darwin' || platform === 'linux') {
const localBinPath = join(homedir(), '.local', 'bin', 'openclaw');
if (fileExists(localBinPath)) {
return { command: localBinPath, args: [] };
}
}
if (platform === 'linux' && fileExists('/usr/local/bin/openclaw')) {
return { command: '/usr/local/bin/openclaw', args: [] };
}
if (!app.isPackaged) {
const openclawDir = getOpenClawDir();
const nodeModulesDir = dirname(openclawDir);
const binName = platform === 'win32' ? 'openclaw.cmd' : 'openclaw';
const binPath = join(nodeModulesDir, '.bin', binName);
if (fileExists(binPath)) {
if (platform === 'win32') {
return getWindowsCmdWrapperSpawnSpec(binPath);
}
return { command: binPath, args: [], shell: false };
}
}
const packagedWrapper = getPackagedCliWrapperPath();
if (packagedWrapper) {
if (platform === 'win32') {
return getWindowsCmdWrapperSpawnSpec(packagedWrapper);
}
return { command: packagedWrapper, args: [], shell: false };
}
if (app.isPackaged) {
if (platform === 'win32') {
const bundledNode = getPackagedWindowsNodePath();
if (bundledNode) {
return { command: bundledNode, args: [entryPath] };
}
}
return {
command: process.execPath,
args: [entryPath],
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
};
}
return { command: 'node', args: [entryPath] };
}
function getOpenClawEmbeddedExecPath(): { execPath: string; electronRunAsNode: boolean } {
if (!app.isPackaged) {
const nodeExecPath = getDevNodeExecPath();
if (nodeExecPath) return { execPath: nodeExecPath, electronRunAsNode: false };
if (process.versions?.electron) {
throw new Error('Node executable not found on PATH for embedded OpenClaw launch');
}
}
if (app.isPackaged && process.platform === 'win32') {
const bundledNode = getPackagedWindowsNodePath();
if (bundledNode) return { execPath: bundledNode, electronRunAsNode: false };
}
if (app.isPackaged && process.platform === 'darwin') {
const helperPath = getPackagedMacOSHelperPath();
if (!helperPath) {
throw new Error('ClawX Helper executable not found for embedded OpenClaw launch');
}
return { execPath: helperPath, electronRunAsNode: true };
}
return { execPath: process.execPath, electronRunAsNode: Boolean(process.versions?.electron) };
}
export function getOpenClawEmbeddedForkSpec(args: string[] = []): OpenClawEmbeddedForkSpec {
const { execPath, electronRunAsNode } = getOpenClawEmbeddedExecPath();
const env: NodeJS.ProcessEnv = {
...process.env,
OPENCLAW_NO_RESPAWN: '1',
OPENCLAW_EMBEDDED_IN: 'ClawX',
OPENCLAW_EXEC_SHELL_SNAPSHOT: '0',
};
if (electronRunAsNode) {
env.ELECTRON_RUN_AS_NODE = '1';
} else {
delete env.ELECTRON_RUN_AS_NODE;
}
return {
modulePath: getOpenClawEntryPath(),
args,
options: {
cwd: getOpenClawDir(),
env,
execPath,
execArgv: [],
stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
windowsHide: true,
},
};
}
// ── Packaged CLI wrapper path ────────────────────────────────────────────────
function getPackagedCliWrapperPath(): string | null {
@@ -120,6 +272,20 @@ function getWindowsPowerShellPath(): string {
return join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
}
function getPackagedMacOSHelperPath(): string | null {
if (process.platform !== 'darwin' || !app.isPackaged) return null;
const appName = app.getName();
const helperName = `${appName} Helper`;
const helperPath = join(
dirname(process.execPath),
'../Frameworks',
`${helperName}.app`,
'Contents/MacOS',
helperName,
);
return existsSync(helperPath) ? helperPath : null;
}
// ── macOS / Linux install ────────────────────────────────────────────────────
function getCliTargetPath(): string {
@@ -328,18 +494,8 @@ export async function autoInstallCliIfNeeded(
// ── Completion helpers ───────────────────────────────────────────────────────
function getNodeExecForCli(): string {
if (process.platform === 'darwin' && app.isPackaged) {
const appName = app.getName();
const helperName = `${appName} Helper`;
const helperPath = join(
dirname(process.execPath),
'../Frameworks',
`${helperName}.app`,
'Contents/MacOS',
helperName,
);
if (existsSync(helperPath)) return helperPath;
}
const helperPath = getPackagedMacOSHelperPath();
if (helperPath) return helperPath;
return process.execPath;
}
+1 -13
View File
@@ -5,23 +5,11 @@
* (`#token=...`) and strips them after load. Query-string tokens are removed
* by the UI bootstrap but are not imported for auth.
*/
export type OpenClawControlUiView = 'dreams';
type OpenClawControlUiUrlOptions = {
view?: OpenClawControlUiView;
};
const CONTROL_UI_VIEW_PATHS: Record<OpenClawControlUiView, string> = {
dreams: '/dreaming',
};
export function buildOpenClawControlUiUrl(
port: number,
token: string,
options: OpenClawControlUiUrlOptions = {},
): string {
const path = options.view ? CONTROL_UI_VIEW_PATHS[options.view] : '/';
const url = new URL(path, `http://127.0.0.1:${port}`);
const url = new URL('/', `http://127.0.0.1:${port}`);
const trimmedToken = token.trim();
if (trimmedToken) {
+28 -21
View File
@@ -1,8 +1,8 @@
/**
* Read/write agents.defaults.imageGenerationModel and per-agent auth readiness.
*/
import { readOpenClawConfig, writeOpenClawConfig } from './channel-config';
import { withConfigLock } from './config-mutex';
import { mutateOpenClawConfig } from '../gateway/config-delivery';
import { readOpenClawConfig } from './channel-config';
import {
getOAuthTokenFromOpenClaw,
getProviderApiKeyFromOpenClaw,
@@ -10,7 +10,11 @@ import {
syncOpenAiCompatibleImageRelay,
} from './openclaw-auth';
import { ensureClawXOpenAiImagePluginInstalled } from './plugin-install';
import { listAgentsSnapshot, type AgentsSnapshot } from './agent-config';
import {
listAgentsSnapshot,
listAgentsSnapshotFromConfig,
type AgentsSnapshot,
} from './agent-config';
import { expandPath } from './paths';
import {
generateImageInProcess,
@@ -84,6 +88,7 @@ type AgentModelConfigShape = {
primary?: string;
fallbacks?: string[];
timeoutMs?: number;
[key: string]: unknown;
};
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -130,12 +135,12 @@ function parseImageGenerationModelConfig(raw: unknown): ImageGenerationModelConf
function buildImageGenerationModelConfigWrite(
config: ImageGenerationModelConfig,
existing: unknown,
): AgentModelConfigShape | undefined {
if (!config.primary && config.fallbacks.length === 0 && config.timeoutMs === null) {
return undefined;
}
const next: AgentModelConfigShape = {};
const next: AgentModelConfigShape = isRecord(existing) ? { ...existing } : {};
delete next.primary;
delete next.fallbacks;
delete next.timeoutMs;
if (config.primary) {
next.primary = config.primary;
}
@@ -145,7 +150,7 @@ function buildImageGenerationModelConfigWrite(
if (config.timeoutMs !== null) {
next.timeoutMs = config.timeoutMs;
}
return next;
return Object.keys(next).length > 0 ? next : undefined;
}
export function parseProviderFromModelRef(modelRef: string): string | null {
@@ -207,8 +212,8 @@ export async function setImageGenerationConfig(
}
}
return withConfigLock(async () => {
const config = await readOpenClawConfig();
let savedConfig: ImageGenerationModelConfig | undefined;
await mutateOpenClawConfig((config) => {
const agents = (config.agents && typeof config.agents === 'object'
? { ...(config.agents as Record<string, unknown>) }
: {}) as Record<string, unknown>;
@@ -220,7 +225,7 @@ export async function setImageGenerationConfig(
primary: next.primary,
fallbacks: [...new Set(next.fallbacks.map((ref) => ref.trim()).filter(Boolean))],
timeoutMs: next.timeoutMs,
});
}, defaults.imageGenerationModel);
if (writeValue) {
defaults.imageGenerationModel = writeValue;
@@ -234,10 +239,9 @@ export async function setImageGenerationConfig(
agents.defaults = defaults;
config.agents = agents;
await writeOpenClawConfig(config);
return readImageGenerationConfig();
savedConfig = parseImageGenerationModelConfig(defaults.imageGenerationModel);
});
return savedConfig!;
}
async function buildAgentAuthRows(
@@ -316,10 +320,10 @@ function resolveOpenAiImageRelayModelId(
}
export async function getImageGenerationSettingsSnapshot(): Promise<ImageGenerationSettingsSnapshot> {
const config = await readImageGenerationConfig();
const snapshot = await listAgentsSnapshot();
const openclawConfig = await readOpenClawConfig();
const defaults = getAgentsDefaults(openclawConfig);
const config = parseImageGenerationModelConfig(defaults?.imageGenerationModel);
const snapshot = await listAgentsSnapshotFromConfig(openclawConfig);
const autoProviderFallback = defaults?.mediaGenerationAutoProviderFallback !== false;
const providerKey = config.primary ? parseProviderFromModelRef(config.primary) : null;
@@ -348,6 +352,12 @@ export async function applyOpenAiImageRelaySettings(params: {
apiKey?: string;
model?: string | null;
}): Promise<void> {
if (params.enabled) {
const plugin = await ensureClawXOpenAiImagePluginInstalled();
if (!plugin.installed) {
throw new Error(plugin.warning || 'Failed to install ClawX OpenAI Image plugin');
}
}
const imageModelIds: string[] = [];
const explicitModel = params.model?.trim();
if (explicitModel) {
@@ -364,14 +374,11 @@ export async function applyOpenAiImageRelaySettings(params: {
apiKey: params.apiKey,
imageModelIds,
});
if (params.enabled) {
ensureClawXOpenAiImagePluginInstalled();
}
}
export async function listImageGenerationProvidersFromRuntime(): Promise<ImageGenerationProviderRow[]> {
const cfg = await readOpenClawConfig();
const snapshot = await listAgentsSnapshot();
const snapshot = await listAgentsSnapshotFromConfig(cfg);
const rows = await listImageGenerationProvidersInProcess({
config: cfg,
isProviderConfigured: (providerId) => isImageProviderAuthenticated(providerId, snapshot.defaultAgentId),
+64
View File
@@ -0,0 +1,64 @@
/**
* Memory search default seeding for openclaw.json.
*
* OpenClaw defaults to the `openai` embedding provider. When no OpenAI key is
* available, ClawX explicitly selects OpenClaw's keyword-only FTS provider so
* memory_search remains useful without making an embedding request.
*/
export const MEMORY_SEARCH_FTS_MIGRATION_VERSION = 1;
export type MemorySearchDefaultResult = 'unchanged' | 'seeded' | 'migrated';
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
/**
* True when the user manages memorySearch themselves: either
* `agents.defaults.memorySearch` or any `agents.list[].memorySearch` exists.
*/
export function hasUserMemorySearchConfig(config: Record<string, unknown>): boolean {
const agents = isRecord(config.agents) ? config.agents : undefined;
if (!agents) return false;
const defaults = isRecord(agents.defaults) ? agents.defaults : undefined;
if (defaults && defaults.memorySearch !== undefined) return true;
const list = Array.isArray(agents.list) ? agents.list : [];
return list.some((entry) => isRecord(entry) && entry.memorySearch !== undefined);
}
/**
* Seed OpenClaw's explicit FTS-only mode when no memorySearch config exists.
* When requested, also migrate the exact legacy ClawX-managed disabled
* default. Objects with any additional fields and per-agent overrides remain
* user-owned.
*/
export function ensureMemorySearchFtsDefault(
config: Record<string, unknown>,
migrateLegacyDisabledDefault = false,
): MemorySearchDefaultResult {
const agents = (isRecord(config.agents) ? config.agents : {}) as Record<string, unknown>;
const list = Array.isArray(agents.list) ? agents.list : [];
if (list.some((entry) => isRecord(entry) && entry.memorySearch !== undefined)) {
return 'unchanged';
}
const defaults = (isRecord(agents.defaults) ? agents.defaults : {}) as Record<string, unknown>;
const memorySearch = defaults.memorySearch;
if (memorySearch !== undefined) {
const isLegacyDisabledDefault = isRecord(memorySearch)
&& Object.keys(memorySearch).length === 1
&& memorySearch.enabled === false;
if (!migrateLegacyDisabledDefault || !isLegacyDisabledDefault) {
return 'unchanged';
}
}
defaults.memorySearch = { enabled: true, provider: 'none' };
agents.defaults = defaults;
config.agents = agents;
return memorySearch === undefined ? 'seeded' : 'migrated';
}
+20 -12
View File
@@ -1,7 +1,7 @@
import { readOpenClawConfig, writeOpenClawConfig } from './channel-config';
import { mutateOpenClawConfig } from '../gateway/config-delivery';
import type { OpenClawConfig } from './channel-config';
import { resolveProxySettings, type ProxySettings } from './proxy';
import { logger } from './logger';
import { withConfigLock } from './config-mutex';
interface SyncProxyOptions {
/**
@@ -19,23 +19,26 @@ export async function syncProxyConfigToOpenClaw(
settings: ProxySettings,
options: SyncProxyOptions = {},
): Promise<void> {
return withConfigLock(async () => {
const config = await readOpenClawConfig();
const resolved = resolveProxySettings(settings);
const preserveExistingWhenDisabled = options.preserveExistingWhenDisabled !== false;
const nextProxy = settings.proxyEnabled
? (resolved.allProxy || resolved.httpsProxy || resolved.httpProxy)
: '';
const syncState: { result: 'unchanged' | 'preserved' | 'updated' } = { result: 'unchanged' };
await mutateOpenClawConfig((snapshot) => {
syncState.result = 'unchanged';
const config = snapshot as OpenClawConfig;
const telegramConfig = config.channels?.telegram;
if (!telegramConfig) {
return;
}
const resolved = resolveProxySettings(settings);
const preserveExistingWhenDisabled = options.preserveExistingWhenDisabled !== false;
const nextProxy = settings.proxyEnabled
? (resolved.allProxy || resolved.httpsProxy || resolved.httpProxy)
: '';
const currentProxy = typeof telegramConfig.proxy === 'string' ? telegramConfig.proxy : '';
if (!settings.proxyEnabled && preserveExistingWhenDisabled && currentProxy) {
logger.info('Skipped Telegram proxy sync because ClawX proxy is disabled and preserve mode is enabled');
syncState.result = 'preserved';
return;
}
@@ -57,7 +60,12 @@ export async function syncProxyConfigToOpenClaw(
delete config.channels.telegram.proxy;
}
await writeOpenClawConfig(config);
logger.info(`Synced Telegram proxy to OpenClaw config (${nextProxy || 'disabled'})`);
syncState.result = 'updated';
});
if (syncState.result === 'preserved') {
logger.info('Skipped Telegram proxy sync because ClawX proxy is disabled and preserve mode is enabled');
} else if (syncState.result === 'updated') {
logger.info(`Synced Telegram proxy to OpenClaw config (${nextProxy || 'disabled'})`);
}
}
+265
View File
@@ -0,0 +1,265 @@
import { chmod, copyFile, lstat, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
import { basename, dirname, join, relative, resolve } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { resolveOpenClawConfigPath, resolveOpenClawStateDir } from './paths';
const UPGRADE_ID = 'openclaw-2026.7.1';
const SNAPSHOT_DIR_MODE = 0o700;
const SNAPSHOT_FILE_MODE = 0o600;
const AGENT_AUTH_BASENAMES = new Set([
'auth-profiles.json',
'openclaw-agent.sqlite',
'openclaw-agent.sqlite-wal',
'openclaw-agent.sqlite-shm',
]);
export type OpenClawUpgradeSnapshotResult = {
status: 'created' | 'exists';
snapshotDir: string;
files: string[];
};
export type OpenClawUpgradeSnapshotCleanupResult = {
status: 'removed' | 'missing';
snapshotDir: string;
};
export type LegacyUpdateCheckCleanupResult = {
status: 'quarantined' | 'missing' | 'deferred';
sourcePath: string;
backupPath?: string;
};
type SnapshotOptions = {
stateDir?: string;
configPath?: string;
};
function resolveSnapshotDir(stateDir: string): string {
return join(stateDir, 'backups', `clawx-${UPGRADE_ID}-pre-migration`);
}
async function isCopyableRegularFile(path: string): Promise<boolean> {
try {
const info = await lstat(path);
return info.isFile();
} catch {
return false;
}
}
async function snapshotMarkerExists(markerPath: string): Promise<boolean> {
try {
return (await stat(markerPath)).isFile();
} catch {
return false;
}
}
async function copyFileIfPresent(source: string, destination: string, copied: string[]): Promise<void> {
if (!await isCopyableRegularFile(source)) return;
await mkdir(dirname(destination), { recursive: true, mode: SNAPSHOT_DIR_MODE });
await copyFile(source, destination);
await chmod(destination, SNAPSHOT_FILE_MODE);
copied.push(destination);
}
async function pathExists(path: string): Promise<boolean> {
try {
await lstat(path);
return true;
} catch {
return false;
}
}
async function resolveAvailableBackupPath(basePath: string): Promise<string> {
if (!await pathExists(basePath)) return basePath;
const timestamp = Date.now();
for (let suffix = 0; suffix < 100; suffix += 1) {
const candidate = `${basePath}.${timestamp}${suffix === 0 ? '' : `-${suffix}`}`;
if (!await pathExists(candidate)) return candidate;
}
throw new Error(`Could not allocate backup path for ${basePath}`);
}
function hasCanonicalUpdateCheckState(sqlitePath: string): boolean {
let db: DatabaseSync | undefined;
try {
db = new DatabaseSync(sqlitePath, { readOnly: true });
const row = db.prepare(`
SELECT 1 AS present
FROM update_check_state
WHERE state_key = ?
LIMIT 1
`).get('default') as { present?: number } | undefined;
return row?.present === 1;
} catch {
return false;
} finally {
db?.close();
}
}
async function copyTree(
sourceRoot: string,
destinationRoot: string,
copied: string[],
includeFile: (name: string) => boolean,
): Promise<void> {
let entries;
try {
entries = await readdir(sourceRoot, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (entry.isSymbolicLink()) continue;
const source = join(sourceRoot, entry.name);
const destination = join(destinationRoot, entry.name);
if (entry.isDirectory()) {
await mkdir(destination, { recursive: true, mode: SNAPSHOT_DIR_MODE });
await copyTree(source, destination, copied, includeFile);
} else if (entry.isFile() && includeFile(entry.name)) {
await copyFileIfPresent(source, destination, copied);
}
}
}
/**
* Creates a one-time pre-migration snapshot before ClawX first starts the
* OpenClaw 2026.7.1 Gateway. SQLite databases are copied together with their
* WAL/SHM sidecars; channel credentials under `credentials/` are intentionally
* excluded because this migration does not rewrite them.
*/
export async function ensureOpenClaw2026_7_1UpgradeSnapshot(
options: SnapshotOptions = {},
): Promise<OpenClawUpgradeSnapshotResult> {
const stateDir = resolve(options.stateDir ?? resolveOpenClawStateDir());
const configPath = resolve(options.configPath ?? resolveOpenClawConfigPath());
const snapshotDir = resolveSnapshotDir(stateDir);
const markerPath = join(snapshotDir, 'snapshot.json');
if (await snapshotMarkerExists(markerPath)) {
try {
const marker = JSON.parse(await readFile(markerPath, 'utf8')) as { files?: unknown };
return {
status: 'exists',
snapshotDir,
files: Array.isArray(marker.files)
? marker.files.filter((value): value is string => typeof value === 'string')
: [],
};
} catch {
// Replace malformed/incomplete snapshots below.
}
}
const tempDir = `${snapshotDir}.tmp-${process.pid}-${Date.now()}`;
const copiedDestinations: string[] = [];
await rm(tempDir, { recursive: true, force: true });
await mkdir(tempDir, { recursive: true, mode: SNAPSHOT_DIR_MODE });
try {
await copyFileIfPresent(configPath, join(tempDir, 'config', basename(configPath)), copiedDestinations);
for (const databasePath of [
join(stateDir, 'openclaw.sqlite'),
join(stateDir, 'state', 'openclaw.sqlite'),
]) {
const relativeDatabase = relative(stateDir, databasePath);
for (const suffix of ['', '-wal', '-shm']) {
await copyFileIfPresent(
`${databasePath}${suffix}`,
join(tempDir, 'state-files', `${relativeDatabase}${suffix}`),
copiedDestinations,
);
}
}
await copyTree(
join(stateDir, 'agents'),
join(tempDir, 'agents'),
copiedDestinations,
(name) => AGENT_AUTH_BASENAMES.has(name),
);
const files = copiedDestinations.map((path) => relative(tempDir, path)).sort();
await writeFile(join(tempDir, 'snapshot.json'), `${JSON.stringify({
upgrade: UPGRADE_ID,
createdAt: new Date().toISOString(),
configPath,
stateDir,
files,
}, null, 2)}\n`, { encoding: 'utf8', mode: SNAPSHOT_FILE_MODE });
await rm(snapshotDir, { recursive: true, force: true });
await mkdir(dirname(snapshotDir), { recursive: true, mode: SNAPSHOT_DIR_MODE });
await rename(tempDir, snapshotDir);
return { status: 'created', snapshotDir, files };
} catch (error) {
await rm(tempDir, { recursive: true, force: true });
throw error;
}
}
/**
* OpenClaw 2026.7.1 refuses Gateway readiness when the legacy update-check JSON
* differs from an existing canonical SQLite row. The JSON contains updater
* bookkeeping only, and upstream would archive it when both copies match. Once
* SQLite has the canonical row, move the legacy file out of the active state
* root so a harmless mismatch cannot trap startup or an ineffective doctor
* retry loop. If SQLite has no row yet, leave the JSON for upstream to import.
*/
export async function quarantineLegacyUpdateCheckState(
options: Pick<SnapshotOptions, 'stateDir'> = {},
): Promise<LegacyUpdateCheckCleanupResult> {
const stateDir = resolve(options.stateDir ?? resolveOpenClawStateDir());
const sourcePath = join(stateDir, 'update-check.json');
let sourceInfo;
try {
sourceInfo = await lstat(sourcePath);
} catch {
return { status: 'missing', sourcePath };
}
if (!sourceInfo.isFile() && !sourceInfo.isSymbolicLink()) {
return { status: 'deferred', sourcePath };
}
const sqlitePath = join(stateDir, 'state', 'openclaw.sqlite');
if (!hasCanonicalUpdateCheckState(sqlitePath)) {
return { status: 'deferred', sourcePath };
}
const backupDir = join(stateDir, 'backups');
await mkdir(backupDir, { recursive: true, mode: SNAPSHOT_DIR_MODE });
const backupPath = await resolveAvailableBackupPath(
join(backupDir, `clawx-${UPGRADE_ID}-legacy-update-check.json`),
);
await rename(sourcePath, backupPath);
if (sourceInfo.isFile()) {
await chmod(backupPath, SNAPSHOT_FILE_MODE);
}
return { status: 'quarantined', sourcePath, backupPath };
}
/**
* Removes the one-time OpenClaw 2026.7.1 pre-migration snapshot after Gateway
* startup succeeds so duplicated config/auth/SQLite secrets do not linger.
*/
export async function removeOpenClaw2026_7_1UpgradeSnapshot(
options: SnapshotOptions = {},
): Promise<OpenClawUpgradeSnapshotCleanupResult> {
const stateDir = resolve(options.stateDir ?? resolveOpenClawStateDir());
const snapshotDir = resolveSnapshotDir(stateDir);
const markerPath = join(snapshotDir, 'snapshot.json');
if (!await snapshotMarkerExists(markerPath)) {
return { status: 'missing', snapshotDir };
}
await rm(snapshotDir, { recursive: true, force: true });
return { status: 'removed', snapshotDir };
}
+15 -1
View File
@@ -3,7 +3,7 @@
* Cross-platform path resolution helpers
*/
import { createRequire } from 'node:module';
import { join } from 'path';
import { dirname, join, resolve } from 'path';
import { homedir } from 'os';
import { existsSync, mkdirSync, readFileSync, realpathSync } from 'fs';
@@ -54,6 +54,20 @@ export function getOpenClawConfigDir(): string {
return join(homedir(), '.openclaw');
}
export function resolveOpenClawStateDir(env: NodeJS.ProcessEnv = process.env): string {
const configured = env.OPENCLAW_STATE_DIR?.trim();
return resolve(expandPath(configured || join(homedir(), '.openclaw')));
}
export function resolveOpenClawConfigPath(env: NodeJS.ProcessEnv = process.env): string {
const configured = env.OPENCLAW_CONFIG_PATH?.trim();
return resolve(expandPath(configured || join(resolveOpenClawStateDir(env), 'openclaw.json')));
}
export function resolveOpenClawConfigDir(env: NodeJS.ProcessEnv = process.env): string {
return dirname(resolveOpenClawConfigPath(env));
}
/**
* Get OpenClaw skills directory
*/
+230
View File
@@ -0,0 +1,230 @@
/**
* Persist ClawX-managed plugin install records into OpenClaw's SQLite
* installed_plugin_index store (openclaw.sqlite).
*
* OpenClaw 2026.6+ reads trusted install metadata from SQLite at runtime,
* not from transient plugins.installs in openclaw.json.
*/
import { existsSync, mkdirSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { logger } from './logger';
const INSTALLED_PLUGIN_INDEX_KEY = 'installed-plugin-index';
const INSTALLED_PLUGIN_INDEX_WARNING = 'DO NOT EDIT. This file is generated by OpenClaw from plugin manifests, install records, and config policy. Use `openclaw plugins registry --refresh`, `openclaw plugins install/update/uninstall`, or `openclaw plugins enable/disable` instead.';
const INSTALLED_PLUGIN_INDEX_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS installed_plugin_index (
index_key TEXT NOT NULL PRIMARY KEY,
version INTEGER NOT NULL,
host_contract_version TEXT NOT NULL,
compat_registry_version TEXT NOT NULL,
migration_version INTEGER NOT NULL,
policy_hash TEXT NOT NULL,
generated_at_ms INTEGER NOT NULL,
refresh_reason TEXT,
install_records_json TEXT NOT NULL,
plugins_json TEXT NOT NULL,
diagnostics_json TEXT NOT NULL,
warning TEXT,
updated_at_ms INTEGER NOT NULL
);
`;
function resolveOpenClawStateDir(): string {
return process.env.OPENCLAW_STATE_DIR?.trim() || join(homedir(), '.openclaw');
}
function resolveOpenClawStateSqlitePath(): string {
// OpenClaw 2026.7.1 moved the shared state database under state/.
// Writing the legacy root-level database leaves Gateway migrations reading
// stale plugin records from the canonical database.
return join(resolveOpenClawStateDir(), 'state', 'openclaw.sqlite');
}
function parseInstallRecordsJson(raw: unknown): Record<string, Record<string, unknown>> {
if (!raw || typeof raw !== 'string') {
return {};
}
try {
const parsed = JSON.parse(raw) as unknown;
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return {};
}
const records: Record<string, Record<string, unknown>> = {};
for (const [pluginId, record] of Object.entries(parsed as Record<string, unknown>)) {
if (record && typeof record === 'object' && !Array.isArray(record)) {
records[pluginId] = record as Record<string, unknown>;
}
}
return records;
} catch {
return {};
}
}
function installRecordsMatch(
left: Record<string, unknown>,
right: Record<string, unknown>,
): boolean {
const keys = ['source', 'spec', 'installPath', 'version', 'resolvedName', 'resolvedVersion', 'resolvedSpec'] as const;
return keys.every((key) => left[key] === right[key]);
}
function openStateDatabase(sqlitePath: string): DatabaseSync {
const db = new DatabaseSync(sqlitePath);
db.exec(INSTALLED_PLUGIN_INDEX_TABLE_SQL);
return db;
}
/**
* Upsert trusted install records into openclaw.sqlite.
* ClawX-authored records win over stale SQLite entries for the same plugin id.
*/
export function upsertPluginInstallRecordsIntoSqlite(
records: Record<string, Record<string, unknown>>,
): boolean {
if (Object.keys(records).length === 0) {
return false;
}
ensureOpenClawStateDirExists();
const sqlitePath = resolveOpenClawStateSqlitePath();
mkdirSync(join(resolveOpenClawStateDir(), 'state'), { recursive: true });
let db: DatabaseSync | null = null;
try {
db = openStateDatabase(sqlitePath);
const row = db.prepare(`
SELECT install_records_json
FROM installed_plugin_index
WHERE index_key = ?
`).get(INSTALLED_PLUGIN_INDEX_KEY) as { install_records_json?: string } | undefined;
const now = Date.now();
let merged: Record<string, Record<string, unknown>>;
let changed = false;
if (row) {
const existing = parseInstallRecordsJson(row.install_records_json);
merged = { ...existing };
for (const [pluginId, record] of Object.entries(records)) {
const current = merged[pluginId];
if (current && installRecordsMatch(current, record)) {
continue;
}
merged[pluginId] = record;
changed = true;
}
if (!changed) {
return false;
}
db.prepare(`
UPDATE installed_plugin_index
SET install_records_json = ?,
updated_at_ms = ?,
generated_at_ms = ?
WHERE index_key = ?
`).run(JSON.stringify(merged), now, now, INSTALLED_PLUGIN_INDEX_KEY);
} else {
merged = { ...records };
changed = true;
db.prepare(`
INSERT INTO installed_plugin_index (
index_key, version, host_contract_version, compat_registry_version,
migration_version, policy_hash, generated_at_ms, refresh_reason,
install_records_json, plugins_json, diagnostics_json, warning, updated_at_ms
) VALUES (
?, 1, 'clawx-managed', 'clawx-managed',
1, 'clawx-managed', ?, 'source-changed',
?, '[]', '[]', ?, ?
)
`).run(
INSTALLED_PLUGIN_INDEX_KEY,
now,
JSON.stringify(merged),
INSTALLED_PLUGIN_INDEX_WARNING,
now,
);
}
if (changed) {
logger.info(`[plugin] Persisted trusted install metadata to SQLite for: ${Object.keys(records).join(', ')}`);
}
return changed;
} catch (error) {
logger.warn('[plugin] Failed to persist trusted install metadata to SQLite:', error);
return false;
} finally {
db?.close();
}
}
/**
* Remove install records that must remain ClawX-managed rather than updated
* from their raw upstream npm package. Also clean the legacy root-level DB
* previously written by ClawX before OpenClaw 2026.7.1 moved state to state/.
*/
export function removePluginInstallRecordsFromSqlite(pluginIds: string[]): boolean {
if (pluginIds.length === 0) return false;
const stateDir = resolveOpenClawStateDir();
const sqlitePaths = [
resolveOpenClawStateSqlitePath(),
join(stateDir, 'openclaw.sqlite'),
];
let changed = false;
for (const sqlitePath of sqlitePaths) {
if (!existsSync(sqlitePath)) continue;
let db: DatabaseSync | null = null;
try {
db = openStateDatabase(sqlitePath);
const row = db.prepare(`
SELECT install_records_json
FROM installed_plugin_index
WHERE index_key = ?
`).get(INSTALLED_PLUGIN_INDEX_KEY) as { install_records_json?: string } | undefined;
if (!row) continue;
const records = parseInstallRecordsJson(row.install_records_json);
let databaseChanged = false;
for (const pluginId of pluginIds) {
if (Object.hasOwn(records, pluginId)) {
delete records[pluginId];
databaseChanged = true;
}
}
if (!databaseChanged) continue;
const now = Date.now();
db.prepare(`
UPDATE installed_plugin_index
SET install_records_json = ?,
updated_at_ms = ?,
generated_at_ms = ?
WHERE index_key = ?
`).run(JSON.stringify(records), now, now, INSTALLED_PLUGIN_INDEX_KEY);
changed = true;
} catch (error) {
logger.warn(`[plugin] Failed to remove install metadata from ${sqlitePath}:`, error);
} finally {
db?.close();
}
}
if (changed) {
logger.info(`[plugin] Removed managed install metadata from SQLite for: ${pluginIds.join(', ')}`);
}
return changed;
}
/** Ensure ~/.openclaw exists before first config write in fresh installs. */
export function ensureOpenClawStateDirExists(): void {
const stateDir = resolveOpenClawStateDir();
if (!existsSync(stateDir)) {
mkdirSync(stateDir, { recursive: true });
}
}
+447 -46
View File
@@ -7,11 +7,19 @@
*/
import { app } from 'electron';
import path from 'node:path';
import { existsSync, cpSync, copyFileSync, statSync, mkdirSync, rmSync, readFileSync, writeFileSync, readdirSync, realpathSync } from 'node:fs';
import { existsSync, cpSync, copyFileSync, statSync, lstatSync, mkdirSync, readFileSync, readlinkSync, writeFileSync, readdirSync, realpathSync, symlinkSync, unlinkSync } from 'node:fs';
import { readdir, stat, copyFile, mkdir } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { logger } from './logger';
import { getOpenClawResolvedDir } from './paths';
import { safeRmSync } from './safe-fs';
import {
upsertPluginInstallRecordsIntoSqlite,
removePluginInstallRecordsFromSqlite,
ensureOpenClawStateDirExists,
} from './plugin-install-index';
import { mutateOpenClawConfig } from '../gateway/config-delivery';
function normalizeFsPathForWindows(filePath: string): string {
if (process.platform !== 'win32') return filePath;
@@ -121,7 +129,7 @@ const MANIFEST_ID_FIXES: Record<string, string> = {
/**
* After a plugin has been copied to ~/.openclaw/extensions/<dir>, fix any
* known manifest-ID mismatches so the Gateway can load the plugin.
* Also patches package.json fields that the Gateway uses as "entry hints".
* Also keeps package.json npm metadata usable by OpenClaw's repair planner.
*/
export function fixupPluginManifest(targetDir: string): void {
// 1. Fix openclaw.plugin.json id
@@ -130,45 +138,64 @@ export function fixupPluginManifest(targetDir: string): void {
const raw = readFileSync(fsPath(manifestPath), 'utf-8');
const manifest = JSON.parse(raw);
const oldId = manifest.id as string | undefined;
let modified = false;
if (oldId && MANIFEST_ID_FIXES[oldId]) {
const newId = MANIFEST_ID_FIXES[oldId];
manifest.id = newId;
writeFileSync(fsPath(manifestPath), JSON.stringify(manifest, null, 2) + '\n', 'utf-8');
modified = true;
logger.info(`[plugin] Fixed manifest ID: ${oldId}${newId}`);
}
// OpenClaw 2026.7.1 treats configured channel plugins without a static
// channelConfigs descriptor as stale/missing and invokes its npm repair
// flow. The WeCom package has no descriptor upstream, so provide a
// permissive schema that preserves ClawX's existing channel config fields.
if (manifest.id === 'wecom' && !manifest.channelConfigs?.wecom) {
manifest.channelConfigs = {
...(manifest.channelConfigs ?? {}),
wecom: {
schema: {
type: 'object',
additionalProperties: true,
},
},
};
modified = true;
logger.info('[plugin] Added WeCom channelConfigs compatibility descriptor');
}
if (modified) {
writeFileSync(fsPath(manifestPath), JSON.stringify(manifest, null, 2) + '\n', 'utf-8');
}
} catch {
// manifest may not exist yet — ignore
}
// 2. Fix package.json fields that Gateway uses as "entry hints"
// 2. Keep package.json package-manager metadata valid
const pkgPath = join(targetDir, 'package.json');
try {
const raw = readFileSync(fsPath(pkgPath), 'utf-8');
const pkg = JSON.parse(raw);
let modified = false;
// Check if the package name contains a legacy ID that needs fixing
for (const [oldId, newId] of Object.entries(MANIFEST_ID_FIXES)) {
if (typeof pkg.name === 'string' && pkg.name.includes(oldId)) {
pkg.name = pkg.name.replace(oldId, newId);
modified = true;
}
const install = pkg.openclaw?.install;
if (install) {
if (typeof install.npmSpec === 'string' && install.npmSpec.includes(oldId)) {
install.npmSpec = install.npmSpec.replace(oldId, newId);
modified = true;
}
if (typeof install.localPath === 'string' && install.localPath.includes(oldId)) {
install.localPath = install.localPath.replace(oldId, newId);
modified = true;
}
}
// Keep the real upstream npm package name/spec even though ClawX patches
// the effective plugin id. Rewriting these to the non-existent
// `@wecom/wecom` package makes OpenClaw's repair planner fail before the
// Gateway starts. Restore metadata previously rewritten by older ClawX
// compatibility code.
if (pkg.name === '@wecom/wecom') {
pkg.name = '@wecom/wecom-openclaw-plugin';
modified = true;
}
const install = pkg.openclaw?.install;
if (install?.npmSpec === '@wecom/wecom') {
install.npmSpec = '@wecom/wecom-openclaw-plugin';
modified = true;
}
if (modified) {
writeFileSync(fsPath(pkgPath), JSON.stringify(pkg, null, 2) + '\n', 'utf-8');
logger.info(`[plugin] Fixed package.json entry hints in ${targetDir}`);
logger.info(`[plugin] Restored package.json npm metadata in ${targetDir}`);
}
} catch {
// ignore
@@ -238,7 +265,368 @@ const PLUGIN_NPM_NAMES: Record<string, string> = {
'openclaw-weixin': '@tencent-weixin/openclaw-weixin',
};
// ── Version helper ───────────────────────────────────────────────────────────
/**
* Channel plugins whose ClawX-managed mirrors need synchronized install
* metadata. OpenClaw 2026.6+ reads these records from SQLite for trust checks;
* OpenClaw 2026.7.1 also uses them to decide whether startup migrations should
* update an installed plugin.
*/
type TrustedOfficialExtensionPlugin = {
npmName: string;
/** Effective manifest/config id when it differs from the mirror directory. */
pluginId?: string;
/** Path records keep OpenClaw from replacing a ClawX-patched mirror. */
recordSource?: 'npm' | 'path';
legacyPluginIds?: string[];
};
const TRUSTED_OFFICIAL_EXTENSION_PLUGINS: Record<string, TrustedOfficialExtensionPlugin> = {
dingtalk: { npmName: '@soimy/dingtalk' },
// WeCom intentionally runs under ClawX's legacy-compatible `wecom` id even
// though the upstream package manifest still declares
// `wecom-openclaw-plugin`. Keep it path-owned so startup migration does not
// replace the compatibility-patched mirror with the raw npm package.
wecom: {
npmName: '@wecom/wecom-openclaw-plugin',
recordSource: 'path',
legacyPluginIds: ['wecom-openclaw-plugin'],
},
// @larksuite/openclaw-lark 2026.7.9 declares ./dist/index.js as `main`, but
// publishes its runtime entry as ./index.js. OpenClaw 2026.7.1 rejects old
// managed npm records during its post-core smoke check. Make ClawX's complete
// mirror the canonical path-owned payload instead.
'feishu-openclaw-plugin': {
npmName: '@larksuite/openclaw-lark',
pluginId: 'openclaw-lark',
recordSource: 'path',
legacyPluginIds: ['feishu-openclaw-plugin', 'feishu'],
},
whatsapp: { npmName: '@openclaw/whatsapp' },
discord: { npmName: '@openclaw/discord' },
qqbot: { npmName: '@openclaw/qqbot' },
'openclaw-weixin': { npmName: '@tencent-weixin/openclaw-weixin' },
'clawx-openai-image': {
npmName: 'clawx-openai-image-plugin',
recordSource: 'path',
},
};
type TrustedOfficialPluginInstallRecord = Record<string, unknown> & {
source: 'npm' | 'path';
spec: string;
installPath: string;
version: string;
installedAt: string;
};
/** Store plain paths for OpenClaw install-record matching (no Windows \\?\ prefix). */
function normalizePluginInstallPathForRecord(targetDir: string): string | null {
try {
const resolved = realpathSync(targetDir);
return path.normalize(resolved);
} catch {
return path.normalize(targetDir);
}
}
function buildTrustedOfficialPluginInstallRecord(
pluginDirName: string,
targetDir: string,
): { pluginId: string; record: TrustedOfficialPluginInstallRecord } | null {
const definition = TRUSTED_OFFICIAL_EXTENSION_PLUGINS[pluginDirName];
if (!definition) return null;
const version = readPluginVersion(join(targetDir, 'package.json'));
const installPath = normalizePluginInstallPathForRecord(targetDir);
if (!version || !installPath) return null;
const pluginId = definition.pluginId ?? pluginDirName;
const installedAt = new Date().toISOString();
if (definition.recordSource === 'path') {
return {
pluginId,
record: {
source: 'path',
spec: targetDir,
sourcePath: targetDir,
installPath,
version,
installedAt,
},
};
}
return {
pluginId,
record: {
source: 'npm',
spec: definition.npmName,
installPath,
version,
resolvedName: definition.npmName,
resolvedVersion: version,
resolvedSpec: `${definition.npmName}@${version}`,
installedAt,
},
};
}
function pluginInstallRecordIds(pluginDirName: string): string[] {
const definition = TRUSTED_OFFICIAL_EXTENSION_PLUGINS[pluginDirName];
return [...new Set([
pluginDirName,
definition?.pluginId,
...(definition?.legacyPluginIds ?? []),
].filter((value): value is string => Boolean(value)))];
}
async function removeLegacyPluginInstallMetadataFromConfig(pluginIds: string[]): Promise<boolean> {
const removedIds = new Set<string>();
const changed = await mutateOpenClawConfig((config) => {
removedIds.clear();
const plugins = config.plugins;
if (!plugins || typeof plugins !== 'object' || Array.isArray(plugins)) return;
const pluginsRecord = plugins as Record<string, unknown>;
const installs = pluginsRecord.installs;
if (!installs || typeof installs !== 'object' || Array.isArray(installs)) return;
const installsRecord = installs as Record<string, unknown>;
for (const pluginId of pluginIds) {
if (!Object.hasOwn(installsRecord, pluginId)) continue;
delete installsRecord[pluginId];
removedIds.add(pluginId);
}
if (removedIds.size > 0 && Object.keys(installsRecord).length === 0) {
delete pluginsRecord.installs;
}
});
if (removedIds.size > 0) {
logger.info(`[plugin] Removed legacy config install metadata for: ${[...removedIds].join(', ')}`);
}
return changed;
}
function canonicalComparablePath(filePath: string): string {
let resolved: string;
try {
resolved = realpathSync(fsPath(filePath));
} catch {
resolved = path.resolve(filePath);
}
const withoutLongPathPrefix = resolved.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/i, '');
return process.platform === 'win32' ? withoutLongPathPrefix.toLowerCase() : withoutLongPathPrefix;
}
function resolveSymlinkTarget(linkPath: string, target: string): string {
return path.isAbsolute(target) ? target : path.resolve(path.dirname(linkPath), target);
}
function openClawPeerLinkPointsTo(linkPath: string, openclawDir: string): boolean {
try {
const stat = lstatSync(fsPath(linkPath));
if (stat.isSymbolicLink()) {
const target = readlinkSync(fsPath(linkPath));
const resolvedTarget = resolveSymlinkTarget(linkPath, target);
return canonicalComparablePath(resolvedTarget) === canonicalComparablePath(openclawDir);
}
if (stat.isDirectory()) {
try {
const packageJson = JSON.parse(readFileSync(fsPath(join(linkPath, 'package.json')), 'utf-8')) as { name?: unknown };
if (packageJson.name === 'openclaw') {
return canonicalComparablePath(linkPath) === canonicalComparablePath(openclawDir);
}
} catch {
return false;
}
}
} catch {
return false;
}
return false;
}
/**
* Materialized mirrors live outside the bundled OpenClaw package tree, so
* Node's normal package lookup cannot resolve their declared `openclaw` peer.
* OpenClaw 2026.7.1 also audits this exact link before reporting Gateway ready.
*/
export function repairPluginOpenClawPeerLink(
targetDir: string,
openclawDir = getOpenClawResolvedDir(),
): boolean {
let packageJson: Record<string, unknown>;
try {
packageJson = JSON.parse(readFileSync(fsPath(join(targetDir, 'package.json')), 'utf-8')) as Record<string, unknown>;
} catch {
return false;
}
const peerDependencies = packageJson.peerDependencies;
if (
!peerDependencies
|| typeof peerDependencies !== 'object'
|| Array.isArray(peerDependencies)
|| typeof (peerDependencies as Record<string, unknown>).openclaw !== 'string'
) {
return true;
}
if (!existsSync(fsPath(join(openclawDir, 'package.json')))) {
logger.warn(`[plugin] Cannot link OpenClaw peer for ${targetDir}: runtime package missing at ${openclawDir}`);
return false;
}
const nodeModulesDir = join(targetDir, 'node_modules');
const linkPath = join(nodeModulesDir, 'openclaw');
try {
mkdirSync(fsPath(nodeModulesDir), { recursive: true });
const nodeModulesStat = lstatSync(fsPath(nodeModulesDir));
if (!nodeModulesStat.isDirectory() || nodeModulesStat.isSymbolicLink()) {
logger.warn(`[plugin] Cannot link OpenClaw peer because ${nodeModulesDir} is not a real directory`);
return false;
}
if (openClawPeerLinkPointsTo(linkPath, openclawDir)) {
return true;
}
let existing: ReturnType<typeof lstatSync> | null = null;
try {
existing = lstatSync(fsPath(linkPath));
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
if (existing) {
if (existing.isSymbolicLink()) {
unlinkSync(fsPath(linkPath));
} else if (existing.isDirectory()) {
let existingPackageName: unknown;
try {
existingPackageName = JSON.parse(
readFileSync(fsPath(join(linkPath, 'package.json')), 'utf-8'),
).name;
} catch {
existingPackageName = null;
}
if (existingPackageName !== 'openclaw') {
logger.warn(`[plugin] Cannot replace non-OpenClaw peer directory at ${linkPath}`);
return false;
}
safeRmSync(fsPath(linkPath));
} else {
logger.warn(`[plugin] Cannot replace non-directory OpenClaw peer at ${linkPath}`);
return false;
}
}
const junctionTarget = path.resolve(openclawDir);
symlinkSync(fsPath(junctionTarget), fsPath(linkPath), 'junction');
if (!openClawPeerLinkPointsTo(linkPath, openclawDir)) {
logger.warn(`[plugin] OpenClaw peer link audit failed after creating ${linkPath}`);
return false;
}
logger.info(`[plugin] Linked OpenClaw peer: ${linkPath}${openclawDir}`);
return true;
} catch (error) {
logger.warn(`[plugin] Failed to link OpenClaw peer for ${targetDir}:`, error);
return false;
}
}
function persistTrustedOfficialPluginInstallRecordsToSqlite(
records: Record<string, Record<string, unknown>>,
): boolean {
return upsertPluginInstallRecordsIntoSqlite(records);
}
/**
* Persist a ClawX-mirrored plugin install record in OpenClaw's canonical SQLite
* index. OpenClaw 2026.7.1 treats config-level plugins.installs as legacy
* migration input, so remove that transient copy instead of recreating it.
* Safe to call repeatedly; no-ops when metadata is already current.
*/
export async function syncTrustedOfficialPluginInstallRecord(
pluginDirName: string,
targetDir: string,
): Promise<boolean> {
const expected = buildTrustedOfficialPluginInstallRecord(pluginDirName, targetDir);
if (!expected) return false;
if (!existsSync(fsPath(join(targetDir, 'openclaw.plugin.json')))) {
return false;
}
// Repair this even when install metadata already matches. A copied plugin's
// node_modules intentionally excludes host peers, and OpenClaw's migration
// smoke check runs before the Gateway can supply any runtime fallback.
repairPluginOpenClawPeerLink(targetDir);
const recordIds = pluginInstallRecordIds(pluginDirName);
let jsonChanged = false;
try {
ensureOpenClawStateDirExists();
jsonChanged = await removeLegacyPluginInstallMetadataFromConfig(recordIds);
} catch (error) {
// Keep the canonical SQLite repair available even if legacy config cleanup
// cannot be completed in this pass.
logger.warn(`[plugin] Failed to remove legacy install metadata for ${pluginDirName}:`, error);
}
// Remove aliases left by older ClawX/OpenClaw ownership conventions, but do
// not delete the canonical id first: upsert can replace npm/path ownership
// atomically without creating a missing-record window.
const staleRecordIds = recordIds.filter((pluginId) => pluginId !== expected.pluginId);
const removedLegacyRecord = removePluginInstallRecordsFromSqlite(staleRecordIds);
const sqliteChanged = persistTrustedOfficialPluginInstallRecordsToSqlite({
[expected.pluginId]: expected.record,
});
return jsonChanged || removedLegacyRecord || sqliteChanged;
}
/**
* Remove metadata for a ClawX mirror that is no longer configured. This must
* run even when its extension directory is already missing: stale records are
* themselves enough to fail OpenClaw's post-core payload smoke check.
*/
export async function removeTrustedOfficialPluginInstallRecord(pluginDirName: string): Promise<boolean> {
const recordIds = pluginInstallRecordIds(pluginDirName);
if (recordIds.length === 0) return false;
let jsonChanged = false;
try {
jsonChanged = await removeLegacyPluginInstallMetadataFromConfig(recordIds);
} catch (error) {
logger.warn(`[plugin] Failed to remove stale config install metadata for ${pluginDirName}:`, error);
}
const sqliteChanged = removePluginInstallRecordsFromSqlite(recordIds);
return jsonChanged || sqliteChanged;
}
/** Repair managed install metadata and host peer links for all mirrors on disk. */
export async function repairTrustedOfficialPluginInstallRecords(): Promise<void> {
for (const pluginDirName of Object.keys(TRUSTED_OFFICIAL_EXTENSION_PLUGINS)) {
const targetDir = join(homedir(), '.openclaw', 'extensions', pluginDirName);
if (!existsSync(fsPath(join(targetDir, 'openclaw.plugin.json')))) {
continue;
}
await syncTrustedOfficialPluginInstallRecord(pluginDirName, targetDir);
}
}
export function resolvePluginNpmPackagePath(npmName: string): string | null {
const candidateRoots = app.isPackaged
? [app.getAppPath(), process.resourcesPath]
: [app.getAppPath(), process.cwd(), join(app.getAppPath(), '..')];
for (const root of candidateRoots) {
const npmPkgPath = join(root, 'node_modules', ...npmName.split('/'));
if (existsSync(fsPath(join(npmPkgPath, 'openclaw.plugin.json')))) {
return npmPkgPath;
}
}
return null;
}
function readPluginVersion(pkgJsonPath: string): string | null {
try {
@@ -298,7 +686,7 @@ export function copyPluginFromNodeModules(npmPkgPath: string, targetDir: string,
}
// 1. Copy plugin package itself
rmSync(fsPath(targetDir), { recursive: true, force: true });
safeRmSync(fsPath(targetDir));
mkdirSync(fsPath(targetDir), { recursive: true });
cpSyncSafe(realPath, targetDir);
@@ -360,24 +748,37 @@ export function copyPluginFromNodeModules(npmPkgPath: string, targetDir: string,
// ── Core install / upgrade logic ─────────────────────────────────────────────
export function ensurePluginInstalled(
export type PluginInstallResult = {
installed: boolean;
warning?: string;
peerLinkOk?: boolean;
};
export async function ensurePluginInstalled(
pluginDirName: string,
candidateSources: string[],
pluginLabel: string,
): { installed: boolean; warning?: string } {
): Promise<PluginInstallResult> {
const targetDir = join(homedir(), '.openclaw', 'extensions', pluginDirName);
const targetManifest = join(targetDir, 'openclaw.plugin.json');
const targetPkgJson = join(targetDir, 'package.json');
const sourceDir = candidateSources.find((dir) => existsSync(fsPath(join(dir, 'openclaw.plugin.json'))));
async function finalizeInstalledMirror(): Promise<{ installed: true; peerLinkOk: boolean }> {
await syncTrustedOfficialPluginInstallRecord(pluginDirName, targetDir);
return { installed: true, peerLinkOk: repairPluginOpenClawPeerLink(targetDir) };
}
// If already installed, check whether an upgrade is available
if (existsSync(fsPath(targetManifest))) {
if (!sourceDir) return { installed: true }; // no bundled source to compare, keep existing
if (!sourceDir) {
return await finalizeInstalledMirror(); // no bundled source to compare, keep existing
}
const installedVersion = readPluginVersion(targetPkgJson);
const sourceVersion = readPluginVersion(join(sourceDir, 'package.json'));
if (!sourceVersion || !installedVersion || sourceVersion === installedVersion) {
return { installed: true }; // same version or unable to compare
return await finalizeInstalledMirror(); // same version or unable to compare
}
// Version differs — fall through to overwrite install
logger.info(
@@ -394,20 +795,21 @@ export function ensurePluginInstalled(
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
mkdirSync(fsPath(extensionsRoot), { recursive: true });
rmSync(fsPath(targetDir), { recursive: true, force: true });
safeRmSync(fsPath(targetDir));
cpSyncSafe(sourceDir, targetDir);
if (!existsSync(fsPath(join(targetDir, 'openclaw.plugin.json')))) {
return { installed: false, warning: `Failed to install ${pluginLabel} plugin mirror (manifest missing).` };
}
fixupPluginManifest(targetDir);
const installed = await finalizeInstalledMirror();
logger.info(`Installed ${pluginLabel} plugin from bundled mirror: ${sourceDir}`);
return { installed: true };
return installed;
} catch (error) {
const diagnostic = toErrorDiagnostic(error);
attempts.push({ attempt, ...diagnostic });
if (attempt < maxAttempts) {
try {
rmSync(fsPath(targetDir), { recursive: true, force: true });
safeRmSync(fsPath(targetDir));
} catch {
// Ignore cleanup failures before retry.
}
@@ -434,8 +836,8 @@ export function ensurePluginInstalled(
if (!app.isPackaged) {
const npmName = PLUGIN_NPM_NAMES[pluginDirName];
if (npmName) {
const npmPkgPath = join(process.cwd(), 'node_modules', ...npmName.split('/'));
if (existsSync(fsPath(join(npmPkgPath, 'openclaw.plugin.json')))) {
const npmPkgPath = resolvePluginNpmPackagePath(npmName);
if (npmPkgPath && existsSync(fsPath(join(npmPkgPath, 'openclaw.plugin.json')))) {
const installedVersion = existsSync(fsPath(targetPkgJson)) ? readPluginVersion(targetPkgJson) : null;
const sourceVersion = readPluginVersion(join(npmPkgPath, 'package.json'));
if (sourceVersion && (!installedVersion || sourceVersion !== installedVersion)) {
@@ -448,7 +850,7 @@ export function ensurePluginInstalled(
copyPluginFromNodeModules(npmPkgPath, targetDir, npmName);
fixupPluginManifest(targetDir);
if (existsSync(fsPath(join(targetDir, 'openclaw.plugin.json')))) {
return { installed: true };
return await finalizeInstalledMirror();
}
} catch (err) {
logger.warn(
@@ -465,7 +867,7 @@ export function ensurePluginInstalled(
);
}
} else if (existsSync(fsPath(targetManifest))) {
return { installed: true }; // same version, already installed
return await finalizeInstalledMirror(); // same version, already installed
}
}
}
@@ -500,15 +902,15 @@ export function buildCandidateSources(pluginDirName: string): string[] {
// ── Per-channel plugin helpers ───────────────────────────────────────────────
export function ensureDingTalkPluginInstalled(): { installed: boolean; warning?: string } {
export function ensureDingTalkPluginInstalled(): Promise<PluginInstallResult> {
return ensurePluginInstalled('dingtalk', buildCandidateSources('dingtalk'), 'DingTalk');
}
export function ensureWeComPluginInstalled(): { installed: boolean; warning?: string } {
export function ensureWeComPluginInstalled(): Promise<PluginInstallResult> {
return ensurePluginInstalled('wecom', buildCandidateSources('wecom'), 'WeCom');
}
export function ensureFeishuPluginInstalled(): { installed: boolean; warning?: string } {
export function ensureFeishuPluginInstalled(): Promise<PluginInstallResult> {
return ensurePluginInstalled(
'feishu-openclaw-plugin',
buildCandidateSources('feishu-openclaw-plugin'),
@@ -516,25 +918,23 @@ export function ensureFeishuPluginInstalled(): { installed: boolean; warning?: s
);
}
export function ensureWeChatPluginInstalled(): { installed: boolean; warning?: string } {
export function ensureWeChatPluginInstalled(): Promise<PluginInstallResult> {
return ensurePluginInstalled('openclaw-weixin', buildCandidateSources('openclaw-weixin'), 'WeChat');
}
export function ensureDiscordPluginInstalled(): { installed: boolean; warning?: string } {
export function ensureDiscordPluginInstalled(): Promise<PluginInstallResult> {
return ensurePluginInstalled('discord', buildCandidateSources('discord'), 'Discord');
}
export function ensureQQBotPluginInstalled(): { installed: boolean; warning?: string } {
export function ensureQQBotPluginInstalled(): Promise<PluginInstallResult> {
return ensurePluginInstalled('qqbot', buildCandidateSources('qqbot'), 'QQBot');
}
export function ensureWhatsAppPluginInstalled(): { installed: boolean; warning?: string } {
export function ensureWhatsAppPluginInstalled(): Promise<PluginInstallResult> {
return ensurePluginInstalled('whatsapp', buildCandidateSources('whatsapp'), 'WhatsApp');
}
export function ensureClawXOpenAiImagePluginInstalled(): { installed: boolean; warning?: string } {
export function ensureClawXOpenAiImagePluginInstalled(): Promise<PluginInstallResult> {
return ensurePluginInstalled(
'clawx-openai-image',
buildCandidateSources('clawx-openai-image'),
@@ -567,7 +967,7 @@ const ALL_BUNDLED_PLUGINS = [
export async function ensureAllBundledPluginsInstalled(): Promise<void> {
for (const { fn, label } of ALL_BUNDLED_PLUGINS) {
try {
const result = fn();
const result = await fn();
if (result.warning) {
logger.warn(`[plugin] ${label}: ${result.warning}`);
}
@@ -575,4 +975,5 @@ export async function ensureAllBundledPluginsInstalled(): Promise<void> {
logger.warn(`[plugin] Failed to install/upgrade ${label} plugin:`, error);
}
}
await repairTrustedOfficialPluginInstallRecords();
}
+8
View File
@@ -3,6 +3,8 @@ const MULTI_INSTANCE_PROVIDER_TYPES = new Set(['custom', 'ollama']);
export const OPENCLAW_PROVIDER_KEY_MINIMAX = 'minimax-portal';
export const OPENCLAW_PROVIDER_KEY_MOONSHOT = 'moonshot';
export const OPENCLAW_PROVIDER_KEY_MOONSHOT_GLOBAL = 'moonshot-global';
/** OpenClaw Z.AI runtime provider id (CN + Global share this key). */
export const OPENCLAW_PROVIDER_KEY_ZAI = 'zai';
/** OpenClaw Codex OAuth runtime provider id (canonical `openai`, not legacy `openai-codex`). */
export const OPENAI_CODEX_RUNTIME_PROVIDER_KEY = 'openai';
export const CLAWX_OPENAI_IMAGE_PROVIDER_KEY = 'clawx-openai-image';
@@ -19,6 +21,8 @@ const HIDDEN_PROVIDER_KEYS_FOR_UI = new Set<string>([
const PROVIDER_KEY_ALIASES: Record<string, string> = {
'minimax-portal-cn': OPENCLAW_PROVIDER_KEY_MINIMAX,
// OpenClaw's built-in Z.AI provider is always `zai` (see docs.openclaw.ai/providers/zai).
'zai-global': OPENCLAW_PROVIDER_KEY_ZAI,
};
export function getOpenClawProviderKeyForType(type: string, providerId: string): string {
@@ -87,6 +91,10 @@ export function isMiniMaxProviderType(type: string): boolean {
return type === OPENCLAW_PROVIDER_KEY_MINIMAX || type === 'minimax-portal-cn';
}
export function isZaiProviderType(type: string): boolean {
return type === OPENCLAW_PROVIDER_KEY_ZAI || type === 'zai-global';
}
export function getOAuthProviderTargetKey(type: string): string | undefined {
if (!isOAuthProviderType(type)) return undefined;
return OPENCLAW_PROVIDER_KEY_MINIMAX;
+128
View File
@@ -0,0 +1,128 @@
import { dirname, join } from 'node:path';
import { lstatSync, readdirSync, realpathSync, rmdirSync, unlinkSync } from 'node:fs';
function normalizeComparablePath(input: string): string {
if (process.platform === 'win32') {
return input.replace(/\\/g, '/').toLowerCase();
}
return input;
}
function isPathInside(root: string, candidate: string): boolean {
const normalizedRoot = normalizeComparablePath(root);
const normalizedCandidate = normalizeComparablePath(candidate);
const rootWithSep = normalizedRoot.endsWith('/') ? normalizedRoot : `${normalizedRoot}/`;
return normalizedCandidate === normalizedRoot || normalizedCandidate.startsWith(rootWithSep);
}
function errnoCode(error: unknown): string | undefined {
return error && typeof error === 'object'
? (error as NodeJS.ErrnoException).code
: undefined;
}
function resolveRealPath(input: string): string {
// Node's JavaScript realpath implementation can split a Windows namespaced
// path (\\?\C:\...) at the drive colon and try to lstat "C:". The native
// implementation accepts the same long-path form without reparsing it.
return realpathSync.native(input);
}
function removeLinkEntry(entryPath: string): void {
// Never recursively remove a link. In particular, an NTFS junction may point
// at the bundled OpenClaw runtime outside the plugin tree.
try {
unlinkSync(entryPath);
} catch (error) {
const code = errnoCode(error);
if (code === 'ENOENT') return;
// libuv normally unlinks Windows junctions directly. Some Windows filesystems
// report directory links as EPERM/EISDIR, where a non-recursive rmdir removes
// the junction node without traversing its target.
if (process.platform === 'win32' && (code === 'EPERM' || code === 'EISDIR')) {
rmdirSync(entryPath);
return;
}
throw error;
}
}
function removeFileEntry(entryPath: string): void {
try {
unlinkSync(entryPath);
} catch (error) {
if (errnoCode(error) !== 'ENOENT') throw error;
}
}
function removeDirectoryEntry(entryPath: string, deletionRootRealPath: string): void {
let stat;
try {
stat = lstatSync(entryPath);
} catch (error) {
if (errnoCode(error) === 'ENOENT') return;
throw error;
}
if (stat.isSymbolicLink()) {
removeLinkEntry(entryPath);
return;
}
if (stat.isDirectory()) {
// Resolve before descending. If resolution fails, propagate the error rather
// than falling back to fs.rmSync(), which could follow an outbound junction.
const entryRealPath = resolveRealPath(entryPath);
if (!isPathInside(deletionRootRealPath, entryRealPath)) {
throw new Error(`Refusing to recursively delete directory outside root: ${entryPath} -> ${entryRealPath}`);
}
for (const child of readdirSync(entryPath)) {
removeDirectoryEntry(join(entryPath, child), deletionRootRealPath);
}
rmdirSync(entryPath);
return;
}
removeFileEntry(entryPath);
}
/**
* Remove a file or directory tree without following outbound directory
* junctions/symlinks on Windows. Plain fs.rmSync({ recursive: true }) can
* traverse NTFS junctions (for example plugin node_modules/openclaw peers)
* and delete link targets outside the requested tree.
*/
export function safeRmSync(targetPath: string): void {
let stat;
try {
stat = lstatSync(targetPath);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
throw error;
}
if (stat.isSymbolicLink()) {
removeLinkEntry(targetPath);
return;
}
if (!stat.isDirectory()) {
removeFileEntry(targetPath);
return;
}
// Fail closed when either path cannot be resolved. Falling back to recursive
// rm here would reintroduce the junction traversal this helper prevents.
const parentRealPath = resolveRealPath(dirname(targetPath));
const deletionRootRealPath = resolveRealPath(targetPath);
if (!isPathInside(parentRealPath, deletionRootRealPath)) {
throw new Error(`Refusing to recursively delete directory outside parent: ${targetPath} -> ${deletionRootRealPath}`);
}
for (const child of readdirSync(targetPath)) {
removeDirectoryEntry(join(targetPath, child), deletionRootRealPath);
}
rmdirSync(targetPath);
}
+26 -50
View File
@@ -1,21 +1,16 @@
/**
* Skill Config Utilities
* Direct read/write access to skill configuration in ~/.openclaw/openclaw.json
* This bypasses the Gateway RPC for faster and more reliable config updates.
*
* All file I/O uses async fs/promises to avoid blocking the main thread.
* Skill configuration reads and coordinated mutations for openclaw.json.
*/
import { readFile, writeFile, access, mkdir, readdir, rm } from 'fs/promises';
import { readFile, writeFile, mkdir, readdir, rm } from 'fs/promises';
import { existsSync } from 'fs';
import { constants } from 'fs';
import { join } from 'path';
import { homedir } from 'os';
import { getOpenClawDir, getOpenClawResolvedDir, getResourcesDir } from './paths';
import { logger } from './logger';
import { cpAsyncSafe } from './plugin-install';
import { withConfigLock } from './config-mutex';
import { mutateOpenClawConfig, readOpenClawConfigSnapshot } from '../gateway/config-delivery';
const OPENCLAW_CONFIG_PATH = join(homedir(), '.openclaw', 'openclaw.json');
const BUNDLED_OPENCLAW_SKILL_ALLOWLIST = new Set(['skill-creator']);
export interface SkillConfigUpdates {
@@ -60,52 +55,35 @@ interface PreinstalledMarker {
installedAt: string;
}
async function fileExists(p: string): Promise<boolean> {
try { await access(p, constants.F_OK); return true; } catch { return false; }
}
/**
* Read the current OpenClaw config
*/
async function readConfig(): Promise<OpenClawConfig> {
if (!(await fileExists(OPENCLAW_CONFIG_PATH))) {
return {};
}
try {
const raw = await readFile(OPENCLAW_CONFIG_PATH, 'utf-8');
return JSON.parse(raw);
return (await readOpenClawConfigSnapshot()).config as OpenClawConfig;
} catch (err) {
console.error('Failed to read openclaw config:', err);
return {};
}
}
/**
* Write the OpenClaw config
*/
async function writeConfig(config: OpenClawConfig): Promise<void> {
const json = JSON.stringify(config, null, 2);
await writeFile(OPENCLAW_CONFIG_PATH, json, 'utf-8');
}
async function setSkillsEnabled(skillKeys: string[], enabled: boolean): Promise<void> {
if (skillKeys.length === 0) {
return;
}
return withConfigLock(async () => {
const config = await readConfig();
if (!config.skills) {
config.skills = {};
await mutateOpenClawConfig((config) => {
const skillConfig = config as OpenClawConfig;
if (!skillConfig.skills) {
skillConfig.skills = {};
}
if (!config.skills.entries) {
config.skills.entries = {};
if (!skillConfig.skills.entries) {
skillConfig.skills.entries = {};
}
for (const skillKey of skillKeys) {
const entry = config.skills.entries[skillKey] || {};
const entry = skillConfig.skills.entries[skillKey] || {};
entry.enabled = enabled;
config.skills.entries[skillKey] = entry;
skillConfig.skills.entries[skillKey] = entry;
}
await writeConfig(config);
});
}
@@ -209,12 +187,10 @@ export async function updateSkillConfigs(
updates: Array<{ skillKey: string } & SkillConfigUpdates>,
): Promise<{ success: boolean; error?: string }> {
try {
return await withConfigLock(async () => {
const config = await readConfig();
await applySkillConfigUpdates(config, updates);
await writeConfig(config);
return { success: true };
await mutateOpenClawConfig(async (config) => {
await applySkillConfigUpdates(config as OpenClawConfig, updates);
});
return { success: true };
} catch (err) {
console.error('Failed to update skill config:', err);
return { success: false, error: String(err) };
@@ -227,25 +203,25 @@ export async function removeSkillConfig(skillKey: string): Promise<{ success: bo
export async function removeSkillConfigs(skillKeys: string[]): Promise<{ success: boolean; removed: number; error?: string }> {
try {
return await withConfigLock(async () => {
const config = await readConfig();
const existingEntries = config.skills?.entries || {};
const normalizedSkillKeys = skillKeys
.map((skillKey) => skillKey.trim())
.filter(Boolean);
const removed = normalizedSkillKeys.filter((skillKey) => Object.prototype.hasOwnProperty.call(existingEntries, skillKey)).length;
const normalizedSkillKeys = skillKeys
.map((skillKey) => skillKey.trim())
.filter(Boolean);
let removed = 0;
await mutateOpenClawConfig(async (config) => {
const skillConfig = config as OpenClawConfig;
const existingEntries = skillConfig.skills?.entries || {};
removed = normalizedSkillKeys.filter((skillKey) => Object.prototype.hasOwnProperty.call(existingEntries, skillKey)).length;
if (removed === 0) {
return { success: true, removed: 0 };
return;
}
await applySkillConfigUpdates(
config,
skillConfig,
normalizedSkillKeys.map((skillKey) => ({ skillKey, remove: true })),
);
await writeConfig(config);
return { success: true, removed };
});
return { success: true, removed };
} catch (err) {
console.error('Failed to remove skill configs:', err);
return { success: false, removed: 0, error: String(err) };
+9
View File
@@ -6,6 +6,7 @@
import { randomBytes } from 'crypto';
import { app } from 'electron';
import { resolveSupportedLanguage } from '@shared/language';
import { DEFAULT_WORKSPACE_CWD } from '@shared/workspace';
// Lazy-load electron-store (ESM module)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -41,6 +42,7 @@ export interface AppSettings {
proxyHttpsServer: string;
proxyAllServer: string;
proxyBypassRules: string;
memorySearchFtsMigrationVersion: number;
// Update
updateChannel: 'stable' | 'beta' | 'dev';
@@ -51,6 +53,9 @@ export interface AppSettings {
// UI State
sidebarCollapsed: boolean;
devModeUnlocked: boolean;
chatWorkspacePath: string;
recentWorkspacePaths: string[];
workspaceLabels: Record<string, string>;
// Presets
selectedBundles: string[];
@@ -92,6 +97,7 @@ function createDefaultSettings(): AppSettings {
proxyHttpsServer: '',
proxyAllServer: '',
proxyBypassRules: '<local>;localhost;127.0.0.1;::1',
memorySearchFtsMigrationVersion: 0,
// Update
updateChannel: 'stable',
@@ -102,6 +108,9 @@ function createDefaultSettings(): AppSettings {
// UI State
sidebarCollapsed: false,
devModeUnlocked: false,
chatWorkspacePath: DEFAULT_WORKSPACE_CWD,
recentWorkspacePaths: [DEFAULT_WORKSPACE_CWD],
workspaceLabels: {},
// Presets
selectedBundles: ['productivity', 'developer'],
+5 -14
View File
@@ -1,10 +1,10 @@
import { createRequire } from 'node:module';
import { randomUUID } from 'node:crypto';
import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { deflateSync } from 'node:zlib';
import { readOpenClawConfigSnapshot } from '../gateway/config-delivery';
import { normalizeOpenClawAccountId } from './channel-alias';
import { resolveOpenClawRuntimeModulePath } from './runtime-package-resolution';
@@ -209,18 +209,9 @@ function isLoginFresh(login: ActiveLogin): boolean {
return Date.now() - login.startedAt < ACTIVE_LOGIN_TTL_MS;
}
function resolveConfigPath(): string {
const envPath = process.env.OPENCLAW_CONFIG?.trim();
if (envPath) return envPath;
return join(OPENCLAW_DIR, 'openclaw.json');
}
function loadWeChatRouteTag(accountId?: string): string | undefined {
async function loadWeChatRouteTag(accountId?: string): Promise<string | undefined> {
try {
const configPath = resolveConfigPath();
if (!existsSync(configPath)) return undefined;
const raw = readFileSync(configPath, 'utf-8');
const parsed = JSON.parse(raw) as {
const parsed = (await readOpenClawConfigSnapshot()).config as {
channels?: Record<string, {
routeTag?: string | number;
accounts?: Record<string, { routeTag?: string | number }>;
@@ -246,7 +237,7 @@ async function fetchWeChatQrCode(apiBaseUrl: string, accountId?: string, botType
const base = apiBaseUrl.endsWith('/') ? apiBaseUrl : `${apiBaseUrl}/`;
const url = new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(botType)}`, base);
const headers: Record<string, string> = {};
const routeTag = loadWeChatRouteTag(accountId);
const routeTag = await loadWeChatRouteTag(accountId);
if (routeTag) {
headers.SKRouteTag = routeTag;
}
@@ -265,7 +256,7 @@ async function pollWeChatQrStatus(apiBaseUrl: string, qrcode: string, accountId?
const headers: Record<string, string> = {
'iLink-App-ClientVersion': '1',
};
const routeTag = loadWeChatRouteTag(accountId);
const routeTag = await loadWeChatRouteTag(accountId);
if (routeTag) {
headers.SKRouteTag = routeTag;
}
@@ -0,0 +1,172 @@
# ACP Attachment Access Control And Open With
Status: authoritative durable architecture and security reference, reviewed 2026-07-23.
Related scenarios: `acp-chat-experience`, `acp-file-activity`, `gateway-backend-communication`
Related rules: `attachment-access-safety`, `session-workspace-authority`, `tool-derived-file-safety`, `renderer-main-boundary`, `backend-communication-boundary`
Related tasks: `acp-media-attachments`, `acp-attachment-open-with`, `fix-acp-directory-attachments`, `unify-acp-file-cards`
## Trust Boundaries And Ownership
Renderer owns attachment parsing, timeline projection, presentation, and click routing. Electron Main owns ACP session and relative-path context, filesystem and URI validation, scoped reads, operating-system handler discovery, and native open/reveal actions. Renderer-provided URIs, metadata, staging ids, transcript message ids, attachment references, and selected handler ids are untrusted inputs.
An attachment source reference conceptually identifies the active ACP session key, generation, original URI, and optional Main-issued staging or transcript evidence. A resolved local or remote reference repeats that routing identity. These references, Renderer-visible attachment ids, opaque file identities, and handler ids are not bearer capabilities. This Harness reference is authoritative for the durable architecture and security invariants; `shared/host-api/contract.ts` and `src/lib/acp/timeline-types.ts` define the exact current serializable fields, result unions, error values, and operation signatures.
Renderer reaches attachment operations only through `src/lib/host-api.ts` and the typed Host API. The Main-owned `files` service exposes resolution, bounded text and binary reads, click-initiated open, compatible-handler listing, selected-handler open, and reveal. A successful resolution supplies display metadata, a non-sensitive opaque identity, and an attachment-scoped target, but it does not authorize a later read, list, open, or reveal.
The attachment Open With contract consists of `listAttachmentOpenHandlers(ref)`, `openAttachmentWith({ ref, handlerId })`, and `revealAttachment(ref)`. Renderer receives only platform, stable public handler identity, bounded display name, optional bounded PNG icon data URL, and default status. Main accepts no Renderer-provided canonical file path, executable or application path, association input, bundle path, icon-source path, command line, command template, helper source, or child-process environment addition.
## Grant Lifecycle
ACP session load or creation is the only operation that establishes attachment session and relative-path context. Main canonicalizes the selected workspace root and execution cwd, verifies that both are directories and cwd is contained by the workspace, and commits the context only after the ACP operation succeeds. A failed load restores the prior ACP state and prior context. Switching the active session or advancing generation replaces that context.
Every attachment operation looks up the one active Main-owned context by exact session key and generation. Attachment, preview, list, selected-handler open, and reveal payloads cannot provide or replace the execution cwd. Each operation independently resolves the original ref and checks the active session and generation. Generation is a revocation and race token used together with session identity; it is not a globally monotonic credential.
Listing never grants a durable capability. Application-specific open freshly enumerates current handlers without icons, verifies exact membership of the submitted public handler id, then calls an attachment-owned revalidation callback. That callback resolves the original ref again, requires an existing regular local file, and rechecks generation immediately before native invocation. The action is rejected if the association key changed. Reveal likewise re-resolves and revalidates immediately before `shell.showItemInFolder()`.
## Local Resolution And Special Scopes
An accepted absolute, home-relative, `file:`, or execution-cwd-relative reference may resolve to any existing regular local file or directory, including a target outside the active workspace or managed OpenClaw directories. The target is canonicalized before use, and Main returns an explicit `entryKind`. Directories are a narrow system-open-only case: Main overrides untrusted MIME and size hints with `application/x-directory` and zero, and does not permit scoped reads, Preview, Open With, reveal-as-file, outgoing-media resolution, or directory-content enumeration. The local `scope` returned to Renderer is classification metadata for existing UI behavior, not an authorization root:
- `workspace`: the canonical target is inside the active ACP workspace root. Relative references resolve from the registered execution cwd.
- `openclaw-media`: the canonical target is outside the workspace. This legacy scope name does not imply containment under an OpenClaw media root.
- `staging`: when a staging id is supplied, it must match the exact canonical file or selected directory in the Main-owned staging record. The same target may also resolve from an explicit path without claiming staging identity.
- `remote`: a normalized HTTP or HTTPS URL without embedded credentials. Remote references remain session/generation scoped and are revalidated immediately before external open.
Gateway outgoing media remains a record-bound special case, not a general local URL alias. Main validates the outgoing attachment id, requires the URL session key and managed record `sessionKey` to equal the active ACP session key, requires the record attachment id to match, and resolves the record's original file through a managed media root. If both transcript evidence and the record carry a message id, they must agree. The literal `global` session key follows exact equality and is never a wildcard.
## Path And URI Hardening
Main applies syntax checks before ownership checks and authorization again before each side effect. Current defenses include:
- Reject empty, NUL-containing, traversal-bearing, unknown-scheme, UNC, network-share, and overlong source references. The source-reference bound is 4096 characters.
- Decode percent-encoded input once through platform URL handling, then reject encoded traversal or NUL content as well.
- Accept `file:` URLs only with an empty authority or local `localhost` authority; reject remote authorities and credentials.
- Accept only HTTP and HTTPS remote URLs, require a host, reject credentials, and use platform URL normalization for identity and open.
- Resolve home-relative, absolute, Windows-drive, and execution-cwd-relative local references without treating a Renderer-provided path as an authorization root.
- Require an existing regular file or directory and canonicalize the target. Symlink targets and targets outside the workspace are allowed after canonical resolution; all file-content and application-handler operations still require a regular file.
Scoped reads reject directories, open the canonical file without following a final symlink where the platform supports it, verify that the handle is a regular file, recheck the active generation, and read through that handle. Local system open re-resolves the file or directory immediately before `shell.openPath`; remote open revalidates the normalized URL and active generation before `shell.openExternal`. A prior resolve, handler list, cache entry, or stable identity alone never authorizes a later side effect.
## Opaque Identity And Safe Labels
After authorization, Main returns an opaque hash derived from the canonical local target or normalized remote URL. Renderer uses that value for turn-scoped deduplication and diagnostics, but it must not expose a sensitive host path or be treated as access authority.
Display labels come from approved metadata or a decoded basename. Main reduces labels to a basename, removes control and bidirectional-formatting characters, collapses whitespace to one line, applies the current length bound, and falls back to a generic attachment label. Available attachment cards separately show the decoded local path or normalized remote URL represented by the explicit source reference; unavailable cards remain basename-only. Main-owned staging metadata may provide the original user-selected display path.
## Preview And Shared File Card
The shared Renderer classifier in `src/lib/file-preview-capabilities.ts` decides whether a session-valid local attachment fits an existing inline viewer and its size cap. Supported text/code, HTML, CSV, image, PDF, spreadsheet, and supported Office files use the right-side Preview panel. Unsupported, known binary, audio/video, archive, other office-document, over-limit file, and explicit directory targets use the system application only after a user click. HTTP and HTTPS targets open externally only after a user click.
Every attachment preview carries an attachment-scoped file reference. Preview components and rich viewers use the attachment text or binary read operations and must not fall back to a naked path or general workspace read. Attachment previews omit trusted workspace-browser reveal or folder actions.
The later shared-card implementation supersedes the original attachment-local card/menu ownership. `src/pages/Chat/AcpFileCard.tsx` now owns the common `AcpFileCard` shell and target-aware `AcpFileOpenWith` menu for distinct `attachment` and `workspace` references. This sharing is presentation only: attachment authorization remains session/generation scoped, while tool-derived file activity uses independently validated workspace-scoped operations. The two reference types must never be converted into each other. Eligible local HTML menus put an action first that opens the already-authorized target in the existing right-side Preview tab; this file-only preview path is separate from native attachment operations.
For attachments, Open With is eligible only when tone is `assistant`, access is `available`, the target is `local`, and `attachmentOpenMode(...)` is `preview`. User, pending, unavailable, remote, and system-open-only attachments do not show it. The primary sibling button retains the translated `Preview <filename>` accessible name and preview behavior. The compact secondary sibling is never nested inside the primary button and must not activate preview.
Created and modified ACP file-activity rows may use the same shared menu with `WorkspaceFileRef`; deleted rows never do. Their Preview and Changes actions remain separate from Open With. Workspace operations follow the authority in `harness/reference/openclaw-file-activity.md`, not attachment grants.
## Lazy Menu Lifecycle
Discovery is user-initiated and starts only when an eligible menu opens. On every closed-to-open transition, the shared component clears old rows and starts a new request on macOS or Windows. A disabled localized loading row occupies only the application section; reveal is immediately available. Linux skips the discovery call. Closing, unmounting, changing target, or starting a newer request invalidates prior asynchronous results so a stale response cannot populate another file's menu.
Valid rows put enumerated defaults first and locale-sort the remainder with `Intl.Collator(i18n.language)`. Rows use the Main-provided 20-pixel PNG icon only after Renderer validates the expected bounded data URL shape; missing, malformed, oversized, or image-load-failed icons use the generic application icon. The application section is not truncated; the bounded-height Radix menu scrolls and retains keyboard navigation, Enter activation, Escape/outside-click dismissal, and trigger focus restoration. Reveal is the final item and is labeled for Finder on macOS, File Explorer on Windows, or the file manager on Linux.
Discovery is requested again on a later open. Main's cache may satisfy that request, but Renderer owns no authorization or native metadata cache. Only a failed user-selected application open or reveal may show a localized non-blocking toast.
## Native Helper Bounds
Native helper output is untrusted and every record is independently schema-validated. The following limits are security invariants in both the Main adapter and static Windows helper where applicable:
- Handler display name: at most 256 UTF-16 code units.
- Private native handler identity/public input: at most 512 UTF-16 code units before platform-specific public-id validation.
- Native file, bundle, executable, and icon-source path: at most 4096 UTF-16 code units.
- Icon PNG data URL: at most 64 KiB, with macOS base64 syntax and PNG signature validation before IPC.
- Process lifetime: five seconds for non-interactive discovery and the interactive Windows protocol.
- Aggregate or `execFile` output: at most 1 MiB.
- Windows stdin protocol: exactly one JSON line no longer than 8192 characters after ready.
- Presentation cache: five minutes and at most 128 association entries.
Control characters invalidate bounded names, ids, and paths. Helpers run through explicit executables and positional argument arrays with `shell: false`, hidden Windows process UI, and a minimal allowlisted Main-owned environment. Payloads, dependencies, Renderer inputs, and inherited arbitrary variables cannot add environment entries. Process failures are reduced to bounded reason codes; command arguments, private output, and native errors are not logged.
## macOS Static JXA Adapter
macOS uses `/usr/bin/osascript -l JavaScript` with a static JXA program owned in `electron/services/attachment-open-with.ts`. File paths and the icon mode are positional arguments after `--`; no Renderer or file value is interpolated into source. The program imports Foundation and AppKit and uses `NSWorkspace`/Launch Services to convert the Main-owned canonical path to a file URL, enumerate registered application URLs, and identify the default application URL.
Each valid enumerated row carries a private bundle identifier, localized display name, and bundle path. The public `handlerId` is the bundle identifier, but bundle and icon-source paths remain private to Main. Listing renders each bundle's `NSWorkspace.iconForFile()` image as a 32-point PNG in JXA; one icon failure omits only that icon, and macOS does not use Electron bundle-icon fallback.
Opening performs a fresh icon-free JXA enumeration, matches the submitted bundle identifier, calls attachment revalidation, rejects an association-key change, then invokes `/usr/bin/open` with `['-a', freshBundlePath, revalidatedPath]`. No caller can select an arbitrary application path.
## Windows Static PowerShell/C#/COM Adapter
Windows uses the checked-in static bundled `resources/scripts/attachment-open-with.ps1` helper. Development resolves it from the app resources tree and packaged builds resolve the copied resource under `process.resourcesPath`; Windows CI/native smoke and release packaging checks protect source validity and packaged-resource identity. Main starts `powershell.exe` with `-NoLogo`, `-NoProfile`, `-NonInteractive`, `-ExecutionPolicy Bypass`, `-File`, helper path, mode, and data as separate arguments. It never builds or executes PowerShell/registry command templates.
The helper's static embedded C# uses documented Shell APIs: `SHAssocEnumHandlers`, `AssocQueryString`, `IAssocHandler`, `IEnumAssocHandlers`, `IShellItem`, and Shell data-object binding. Listing derives the association from the Main-owned path, enumerates desktop and packaged handlers, reads localized UI names and icon/executable metadata when available, and marks an enumerated row default only when strict normalized executable identity matches `AssocQueryString`. Main requests Windows icons from validated private icon/executable paths through `app.getFileIcon()`; icon absence or failure does not invalidate a handler.
Windows never exposes native handler identity. Both Node and the helper derive the public opaque id as lower-case hex `SHA-256(UTF8("win32\0" + nativeIdentity))`; action input must be exactly 64 lower-case hexadecimal characters. Private identity-to-public-id relationships stay inside Main/helper memory and list cache records.
For action-time validation, Main spawns `prepare-open` with the initial pre-authorized canonical path and opaque id as separate arguments. The helper derives that path's association, enumerates exactly once, recomputes ids, retains only the matching `IAssocHandler` COM object, emits exactly one `{"ready":true}` line, and waits. Only after ready does Main re-resolve the original attachment ref and generation. If revalidation succeeds and the association key is unchanged, Main sends exactly one bounded line containing only `{ "command": "invoke", "path": <post-ready canonical path> }`. The helper rechecks the association, creates a Shell data object for that path, invokes the retained handler, and releases COM objects. Timeout, output overflow, EOF, malformed/repeated protocol, cancellation, revalidation failure, stdin failure, association change, or non-zero helper exit prevents invocation.
## Successful Empty Result On Linux
Linux intentionally has no application discovery or application-specific open in this scope. `listAttachmentOpenHandlers` still authorizes and resolves the attachment, then returns `{ ok: true, platform: 'linux', handlers: [] }` without starting a helper. The shared menu therefore contains only attachment-scoped reveal. Application-specific open is unsupported rather than falling back to a default application.
## Normalization And Presentation Cache
Main validates rows independently, removes duplicate public identities, carries a default flag across duplicates, and keeps valid enumerated default rows before other operating-system rows. Renderer locale-sorts non-default rows. Current code normalizes only rows returned by enumeration; it does not synthesize a handler that a separate default-association query names but enumeration omitted.
The durable guarded requirement is that any future default-handler insertion must use complete validated metadata from a platform API, preserve exact fresh-membership and invocation checks, and remain representable without exposing private identity or paths. It is a follow-up, not implemented behavior. Tests and documentation must not claim insertion until the adapter actually supplies and validates that row.
Main caches normalized list metadata, converted icons, and private list records for five minutes by platform plus lower-case file-association key; extensionless files use the lower-case basename. Expired entries are pruned, growth is bounded to 128 entries, and oldest entries are evicted. This discovery cache is presentation-only. Attachment authorization is never cached, failures grant nothing, and action-time validation always uses a fresh icon-free enumeration rather than the cache.
## Failure And Privacy Semantics
An invalid, stale, missing, unsafe, remote-for-local-operation, unsupported filesystem entry, or directory submitted to a file-only operation becomes an unavailable/error result. It cannot use that operation, but it does not suppress assistant prose or independently valid attachments. A valid existing file or system-open directory does not become unavailable merely because it is outside the workspace. Read failures remain inside Preview; local or remote open failures use the localized non-blocking Chat error path.
Helper startup, timeout, output, parsing, schema, association, application metadata, and icon failures must not reject attachment-card rendering. Whole discovery failure becomes an empty application section with no toast, banner, or failure row. One invalid handler is omitted; one invalid icon affects only that row. Reveal remains available and primary preview remains unchanged. Only a failed action explicitly requested by selecting an application or reveal may surface a concise localized toast.
Logs and traces must not contain transcript bodies, file content, credentials, canonical file paths, application or bundle paths, icon-source paths, native handler identities, helper source/output, command lines, or icon data. Optional open-with tracing may use only the existing opaque attachment identity and bounded allowlisted fields such as source kind or reason code.
## Non-Goals
- Application discovery or application-specific open on Linux.
- Open With on user, remote, unavailable, pending, system-open-only, or non-preview attachment cards.
- Changing preview format classification or file-size limits.
- Persisting associations or changing an operating-system default.
- Download, export, copy, or system chooser actions in this menu.
- Renderer access to canonical/native paths, private identities, helper source, or command templates.
- Converting workspace file-activity evidence into attachment authority.
- Generalizing the card/menu beyond ACP attachment and file-activity surfaces.
## Rejected Alternatives
### Native N-API Addon
A native addon could call AppKit, Launch Services, and Windows Shell APIs directly. It was rejected because architecture-specific compilation, signing, packaging, and release maintenance are disproportionate to this feature.
### Registry Or Application-Directory Parsing
Scanning macOS application directories or parsing Windows Registry command strings was rejected because it misses packaged applications, can report handlers that cannot open the file, and introduces unsafe command-template parsing. Windows must use Shell association COM APIs.
### System Open-With Dialog Only
Delegating entirely to the operating-system chooser was rejected because it does not provide the required in-card application list, icons, and independently available reveal action.
### Renderer-Owned Discovery Or Paths
Renderer-side helper execution, raw executable selection, and generic-shell reveal were rejected because they bypass attachment-scoped authorization, expose private host paths, and make stale-session revocation unenforceable.
## Validation Anchors
- `tests/unit/attachment-open-with.test.ts`: schema normalization, 256/512/4096 bounds, control rejection, SHA-256 opacity, stable deduplication/default-first ordering, five-minute/128-entry cache, 64 KiB icons, static JXA arguments, shell-free sanitized process options, five seconds/1 MiB bounds, Linux no-process behavior, fresh macOS membership, and Windows ready/revalidate/invoke protocol.
- `tests/unit/attachment-open-with-native.test.ts`: real platform-gated static JXA and PowerShell/C#/COM smoke coverage plus packaged helper resolution.
- `tests/unit/attachment-access.test.ts`: typed per-operation attachment authorization, stale generation and remote rejection, action-time re-resolution, forged handler rejection, association-race prevention, scoped reveal, and sensitive diagnostic exclusion.
- `tests/unit/files-api-workspace.test.ts`: the distinct workspace-scoped operations consumed by the later shared `AcpFileCard` implementation.
- `tests/unit/host-api-facade.test.ts` and `tests/unit/host-services.test.ts`: typed `files` facade/service routes and absence of a legacy direct IPC path.
- `tests/unit/acp-chat-components.test.tsx`: exact attachment and file-activity eligibility, sibling controls, lazy loading, stale-request invalidation, locale ordering, icon fallback, silent discovery failure, platform reveal labels, explicit-action errors, and keyboard menu behavior.
- `tests/unit/artifact-panel.test.tsx`, `tests/unit/file-preview-body.test.tsx`, and `tests/unit/rich-file-viewers.test.tsx`: unchanged attachment-scoped preview behavior.
- `tests/e2e/chat-acp-attachments.spec.ts`: attachment card click routing, typed list/open/reveal requests, platform branches, Linux reveal-only behavior, and failure isolation.
- `tests/e2e/chat-file-changes.spec.ts`: later `AcpFileCard` workspace-target reuse and deleted-row exclusion without conflating workspace and attachment grants.
- `.github/workflows/check.yml` and `.github/workflows/release.yml`: Windows native bridge execution and packaged helper presence/hash checks.
+109
View File
@@ -0,0 +1,109 @@
# ACP Chat Architecture And Timeline
Status: current architecture reference, reviewed 2026-07-27.
Related scenario: `acp-chat-experience`
Related rules: `acp-chat-state-and-history`, `attachment-access-safety`, `renderer-main-boundary`
Related tasks: `acp-native-chat`, `acp-media-attachments`, `filter-openclaw-heartbeat-session`, `recover-acp-session-after-gateway-restart`
## Ownership
Electron Main owns the reusable `openclaw acp` child process, ACP SDK connection, stdio lifecycle, typed host operations, permission responses, and routing envelopes. Renderer owns ACP semantic reduction and presentation. Main must not translate ordinary text, thought, tool, permission, plan, or media updates into a second ClawX Chat protocol.
The normal flow is:
```text
Chat UI -> host-api -> Main ACP service -> openclaw acp
session/update -> Main routing envelope -> Renderer reducer -> timeline -> React
```
Gateway remains responsible for non-Chat capabilities. Renderer Chat does not call ordinary Gateway `chat.history` or `chat.send`, and Main has no Chat-history polling, coalescing, or backpressure specialization. Generic Gateway RPC requests retain Main-owned validation and timeout handling before direct `GatewayManager.rpc` dispatch. Restricted Gateway host-event evidence may supplement asynchronous image-generation completion, but it is not a source for ordinary Chat messages or tool history.
## ACP Semantic Authority
For every Chat semantic and context exposed by ACP, ACP is the preferred authority, not only for `session/load` history. This includes session identity and routing where applicable, workspace and execution `cwd`, prompt and timeline state, and standard resource or attachment semantics. When ACP provides the value or event, Main and Renderer must use it rather than substitute Gateway snapshots, transcript inference, local configuration, or a parallel projection.
An ACP bypass is allowed only when upstream has no equivalent capability. The exception must be narrow, bounded, session- and generation-scoped, and documented with its rationale, source of truth, limits, reconciliation behavior, and removal condition in a Harness reference or rule. It must never become a second semantic authority.
## Identity And Race Protection
Renderer-visible session identity is the OpenClaw Gateway session key. Main may hold a different ACP session id returned by `newSession`; it rewrites downstream routing to the matching Gateway session key. Loads on the shared ACP connection are serialized. A routing envelope carries the session key and the Main-owned generation token for the matching load or live prompt. Renderer uses a separate local request sequence to reject stale load completions; preparing a local-only session must not advance the ACP generation. Renderer ignores updates, permission requests, and asynchronous hydration results whose session or generation matches neither the selected session nor a retained live prompt. Generation is an in-memory race token rather than a durable sequence; Main may restore the previous value when a load fails, so code must compare it together with session and current-operation state rather than assume global monotonicity.
While `session/prompt` is pending, Main retains a bounded session-id routing context and Renderer retains that prompt's reduced timeline and original client-observed turn start in memory. This lets another page or conversation be viewed without dropping the original stream or resetting elapsed time. Returning to the live conversation reactivates its existing ACP context and restores the memory snapshot without calling `session/load`; updates received during the handoff are still generation-filtered. Prompt settlement releases both live contexts, after which returning uses ordinary ACP replay plus bounded timing metadata. This is live operation state, not a second history ledger, and it is never persisted.
When guarded Gateway recovery interrupts an accepted main-session run, patched OpenClaw starts a distinct recovery run and marks its Chat and agent events with the interrupted run id as `resumedFromRunId`. The reconnecting ACP bridge keeps the original prompt pending for a bounded 60-second total recovery window, adopts only that explicitly linked recovery run, resets per-run text and tool state, and rebinds cancellation to the new run id. The initial disconnect check still occurs after 5 seconds: prompts whose send was never acknowledged reject then, while acknowledged prompts receive the remaining 55 seconds for Gateway startup backoff and recovery dispatch. ACP also subscribes to session tool events after reconnect, and Gateway mirrors visible recovery tools to that exact session subscription with lineage intact, so recovered tool cards preserve the surrounding text boundaries. Renderer does not reload the session or use Gateway runtime identity for this flow; normal ACP generation, session, and workspace guards remain authoritative.
`messageId` and `toolCallId` are opaque identities within one loaded timeline. They are not durable UI identities across loads. Timeline sequence values and DOM anchors are also local to the active snapshot.
## History Authority
ACP `session/load` replay is the primary source of Chat history. ClawX does not persist an ACP ledger, reduced timeline, replay cache, or reconstructed tool history. Full structured replay restores recorded tools and file activity. When that ledger is unavailable, OpenClaw's ACP adapter maps persisted transcript `toolCall` and `toolResult` records to native ACP tool updates in transcript order, preserving assistant text segments on either side; this is upstream ACP replay, not a ClawX transcript supplement or inference path.
OpenClaw emits replay through ordinary `session/update` notifications and completes the replay before `session/load` returns. Main collects those raw notifications for the active load generation and returns them with the load result instead of forwarding them incrementally. Renderer temporarily groups generation-matching host events that arrive during the IPC result handoff, then runs the normal reducer over the combined batch and publishes the resulting timeline in one state update. This is an in-flight transaction buffer only, not a history cache; after load, each live update continues through the normal host-event route and is applied immediately without a Renderer batching timer. Permission requests are accepted only after the current loaded session starts a prompt, preventing load-time or handoff requests from creating invisible waiters.
There are exactly two approved transcript-derived content supplements. ClawX may recover asynchronous image-generation completions with proven `image_generate` context, and it may recover explicit line-leading assistant `MEDIA:` attachment directives omitted by OpenClaw ACP. Both are bounded, marked, memory-only projections. Separately, Main may extract metadata-only whole-turn timing because ACP replay omits original timestamps. Renderer can attach that timing only to an unambiguously matched ACP turn; it cannot reconstruct ordinary assistant text, thoughts, tool cards, plans, permissions, file activity, or missing turns. See `harness/reference/acp-generated-media-and-diagnostics.md#bounded-transcript-exceptions` for the content compatibility grammar and timing boundary.
## Timeline Model
The Renderer keeps an in-memory `AcpTimelineSnapshot` with ordered item ids, item records, open message segments, tool and permission state, and ACP metadata. The exact TypeScript types in `src/lib/acp/` are authoritative; the stable conceptual item kinds are:
```ts
type TimelineItem =
| MessageSegmentItem
| ThoughtItem
| ToolCallItem
| PermissionItem
| PlanItem;
type MessageSegmentItem = {
kind: 'message-segment';
id: string;
role: 'user' | 'assistant';
messageId: string;
segmentIndex: number;
parts: RenderPart[];
};
```
The reducer preserves first-seen ACP order and patches existing items in place. Interleaving a process block with assistant text closes the current segment; later text for that message creates another segment. Replay and live updates use the same reducer path. Optimistic user segments are allowed and are coalesced with the ACP user echo.
UI-only state such as card expansion, scroll position, selected artifact, composer draft, copy feedback, and lightbox state stays outside the reducer.
## Display Grouping
The protocol timeline remains flat. `src/lib/acp/timeline-groups.ts` derives display groups at render time:
- A user item starts or extends a user group.
- All non-user items between user boundaries form one assistant turn.
- Assistant-side items before the first user item still form a visible assistant turn.
- Grouping never infers ownership from `messageId`, `toolCallId`, `_meta`, or synthetic persisted turn ids.
An assistant turn has one identity column and one copy action. Copy includes textual assistant segments and excludes tool output. Its footer may show localized whole-turn metadata: live duration runs from optimistic send until prompt settlement, while historical duration runs from the matched transcript user record to the latest assistant or tool-result record before the next real user. Missing or ambiguous timing stays hidden. Tool cards render inline in original order, preserve preformatted whitespace, auto-collapse one second after live completion, respect manual override, and start collapsed when historical and completed.
## Attachments
Standard ACP `resource_link` and URI-backed `resource` content is the preferred attachment path. OpenClaw ACP currently projects assistant text and thought content but can omit assistant media while removing `MEDIA:` directives from the visible live reply. Until upstream emits standard resource content, the bounded explicit-`MEDIA:` supplement may add a marked compatibility attachment to the matching turn without manufacturing an ACP event.
Standard `resource_link` mapping preserves its URI, name, title fallback, MIME type, and size when supplied. A URI-backed embedded `resource` uses the same model and metadata precedence; embedded content without a usable URI becomes unavailable rather than entering an unrelated unsupported-content path. Exact TypeScript models remain authoritative.
Renderer keeps attachment references and compatibility projections in the active in-memory timeline. Main owns ACP session and relative-path context and resolves, reads, and opens every attachment against the exact session and generation. Existing regular files may resolve outside the active workspace, but a prior resolution is not reusable authorization and Renderer cannot supply a replacement execution cwd. Native ACP evidence wins when it resolves to the same identity as compatibility evidence. The complete authorization and URI boundary is documented in `harness/reference/acp-attachment-access-control.md`.
Assistant grouping lifts attachments from message, thought, and tool-output segments into one ordered turn list after all prose and process items and before file activity. This prevents an early resource block from appearing above later assistant prose. User grouping similarly renders all prose before ordered attachments. User-selected images render as Main-generated thumbnails whose hover overlay identifies the file. Other available attachment cards show the filename followed by the muted, truncating path represented by their explicit source reference; unavailable attachments remain basename-only.
Available attachment cards contain a primary semantic action with keyboard activation, an accessible action and safe filename, standard focus visibility, and the established hover state. Eligible local assistant Preview cards may also contain a compact secondary Open With sibling button; controls are never nested and secondary interaction cannot activate Preview. Pending and unavailable rows remain announced but disabled. Supported session-valid local files use the Preview panel, other local files use the system application only after a click, and HTTP or HTTPS attachments open externally only after a click. One malformed or unavailable attachment cannot suppress prose or sibling attachments. Image-generation completion remains an inline-image experience. It shares transcript coordination and opaque resolved identities with attachment recovery but is not converted into an attachment card.
## Chat Behaviors
- The primary Chat view renders process activity directly in the ordered ACP timeline.
- A recoverable initial `reply was never sent` load failure may leave an empty new-chat page usable; prompt failures remain visible.
- The working indicator follows the same sending state as the Stop action and supports reduced motion.
- The question directory is derived only from active user message segments. Duplicate text remains separate, titles use the first non-empty Markdown part, and textless entries use a localized fallback. Fewer than two questions disables navigation. When open, the directory floats above the conversation without changing the chat column width. Selection scrolls smoothly to the current-snapshot anchor; a missing anchor is a safe no-op. The UI caps the directory at 300 recent entries and reports the hidden count when older entries are omitted.
- Heartbeat-only desktop sessions are hidden only when the exact OpenClaw heartbeat sentinel is present and there is no real user content. A title such as `ClawX` or `main` is never sufficient. The guard applies to list, startup selection, refresh, and cached summary hydration without deleting OpenClaw history.
## Validation Anchors
Key tests live in `tests/unit/acp-*.test.*`, `tests/unit/acp-timeline-groups.test.ts`, `tests/unit/attachment-access.test.ts`, `tests/unit/chat-question-directory.test.tsx`, `tests/e2e/chat-acp-inline-timeline.spec.ts`, and `tests/e2e/chat-acp-attachments.spec.ts`.
This reference consolidates the former ACP native Chat, Chat polish, turn grouping, and question-directory design documents. Later implementation decisions supersede the original no-optimistic-message rule, the assumption that ACP id always equals Gateway session key, and segment-level assistant copy controls.
@@ -0,0 +1,89 @@
# ACP Generated Media And Diagnostics
Status: current compatibility reference, reviewed 2026-07-15.
Related scenario: `acp-chat-experience`
Related rules: `acp-chat-state-and-history`, `acp-compatibility-content-safety`, `attachment-access-safety`, `diagnostics-trace-safety`
Related tasks: `acp-image-generation-compatibility`, `acp-historical-transcript-supplement`, `acp-media-attachments`, `acp-debug-trace-channel`, `acp-whole-turn-duration`
## Preferred And Compatibility Paths
Standard ACP image, `resource_link`, and URI-backed `resource` content blocks are preferred and render directly. OpenClaw ACP currently projects assistant text and thought content but can omit assistant media, while Gateway processing removes `MEDIA:` directives from the visible live reply. ClawX handles those gaps through two bounded in-memory compatibility exceptions. Neither revives the legacy Chat renderer nor represents synthetic data as a native ACP event.
## Bounded Transcript Exceptions
This section is the durable rationale referenced by the transcript supplement entry point. The two content exceptions are:
1. Image-generation completion with proven `image_generate` context. Trusted structured runtime evidence or approved transcript evidence may restore the completion caption, failure explanation, and media as the existing inline-image experience.
2. General attachment recovery from a canonical persisted assistant `__openclaw.media` fact or an explicit line-leading assistant `MEDIA:` directive outside fenced code blocks. This exception does not require image-generation context, but it recovers only attachment references and declared media metadata, never the surrounding assistant message.
Both content exceptions use one bounded transcript fetch coordinator, keep projected state in memory, require exact active session and generation identity, and reject stale or ambiguous evidence. Existing-session load reads at most 1000 recent transcript messages. An ordinary successful live prompt performs one immediate read and one retry 1500 milliseconds later. Only an `image_generate` task recorded for that same live prompt extends the coordinator through bounded backoff while waiting for its completion artifact; accepted completion, invalidation, or retry-window exhaustion stops it. These exceptions must be removed when the distributed OpenClaw ACP adapter emits the equivalent standard content.
The same historical coordinator may request metadata-only whole-turn timing from Main. This is necessary because ACP `session/load` supplies replay content and status but not the original timestamps needed to calculate duration. Main derives candidates from bounded transcript JSONL envelopes, and Renderer aligns them with the same normalized user text and duplicate occurrence-from-tail rule. Timing can annotate only an ACP-created turn and never recovers transcript content.
Transcript supplementation must not recover or reconstruct ordinary assistant messages, thoughts, tools, plans, permissions, file activity, or a parallel Chat history. Bare paths and inline prose paths without canonical media facts, unknown URI schemes, incidental tool paths, and directives inside fenced code blocks are not general attachments.
### Image-Generation Completion
The projector:
1. Detects a recent image-generation task start from ACP tool evidence.
2. Accepts completion text and media only from bounded, trusted fields or approved historical context.
3. Requires the active session and generation to remain unchanged.
4. Resolves local paths or Gateway media through `hostApi.media.thumbnails` in Main.
5. Inserts a marked synthetic assistant segment after the associated tool when possible.
6. Deduplicates repeated evidence and keeps all state in memory.
Accepted live evidence includes structured media fields such as `mediaUrl`, `mediaUrls`, nested `sourceReply` media, assistant media attachments, OpenClaw ACP tool output explicitly associated with the internal UI sink, and final Gateway assistant replies whose `image_generate:<task-id>:ok|error` run matches the recorded task. For a correlated `message` tool delivery, `sourceReply.text` is the authoritative visible caption or failure explanation. A task-correlated final assistant reply may also provide the authoritative caption or text-only failure explanation. Arbitrary prose, unrelated runs or tools, failed delivery attempts, and unscoped local paths are rejected.
When trusted source-reply text exists, it is preserved whether or not media is present. If no source-reply text exists, successful media uses the localized generic caption; partial or failed thumbnail hydration uses the existing localized fallback. Raw `MEDIA:` paths are never displayed.
### Canonical And Explicit MEDIA Attachments
The general attachment extractor considers normalized assistant roles only. Its preferred transcript evidence is OpenClaw's canonical persisted `__openclaw.media` array. Each fact may contribute one ordered `path` or `url` plus bounded filename, content type, and size metadata; the containing assistant message id is retained for Main-side outgoing-record validation. Canonical facts do not authorize access: every reference and metadata value remains untrusted and passes through the existing Main attachment boundary.
For the legacy directive form, after optional leading whitespace, a whole line must start with the case-insensitive `MEDIA:` token and contain exactly one reference. Single- or double-quoted references may contain spaces and must close with the same quote; unquoted references cannot contain whitespace. One accepted line produces one candidate, and multiple lines retain transcript order. When a canonical fact and directive identify the same URI in one assistant message, the canonical fact wins. The current source-reference bound is `4096` characters.
Accepted reference forms are absolute POSIX paths, Windows drive paths, `file://` URIs, `~/` paths, paths relative to the registered execution cwd, and HTTP or HTTPS URLs. Relative paths are accepted only when execution cwd is available. Canonical structured values may contain spaces. Unknown URI schemes, malformed URLs or quotes, empty references, Markdown/list wrappers, inline prose without canonical evidence, ordinary bare paths without canonical evidence, and wrapped directives are rejected. Markdown backtick and tilde fences follow the delimiter character and opening length; all content remains ignored until a valid close with the same delimiter and at least that length. The parser does not recover or render surrounding transcript prose.
Transcript and ACP messages are partitioned by real user boundaries; leading orphan assistant content is ineligible. OpenClaw ACP does not project assistant `MEDIA:` attachments, so ClawX must read this bounded transcript supplement. To align it without parsing user-authored marker text, each ACP user segment retains only the ordered, binary-free text blocks produced by OpenClaw's prompt flattening: text and embedded text remain text, `resource_link` becomes OpenClaw's escaped `[Resource link]` form, and image/audio/blob data is omitted. User matching then removes only the known OpenClaw working-directory envelope and normalizes line endings and surrounding whitespace; it does not use broad fuzzy matching or globally strip resource markers. Because transcript history is a bounded suffix and cross-source message ids are not durable, alignment proceeds newest-to-oldest with the tuple of normalized flattened user text and duplicate occurrence from the tail. Attachment-only empty text remains eligible under the same real-user boundary and occurrence rules. A live supplement additionally requires the optimistic ACP user identity and restricts extraction to that current turn. Missing, duplicate, or ambiguous anchors are skipped instead of assigned by ordinal offset or nearest-turn guesswork.
Every asynchronous result is valid only for the same active session key, ACP generation, supplement operation, current attempt, and, for live recovery, user-turn identity. Session changes, new loads or prompts, cancellation/invalidation, and the delayed retry superseding the immediate attempt prevent stale mutation.
Candidates already proven to be image-generation completions remain inline images and are suppressed from the paperclip-card path. General attachments are deduplicated only within a conversation turn by the opaque identity returned after Main authorization. Deduplication spans immediate and delayed reads, repeated history loads, native ACP resources, general compatibility evidence, and generated-image evidence. Native ACP attachment evidence wins regardless of arrival order; an equivalent inline generated image suppresses the paperclip card. An unavailable result does not reserve a resolved identity, so a stable candidate from the delayed read can replace the same synthetic projection and upgrade it to available.
Every standard or compatibility attachment reference is resolved through Main's session-scoped attachment boundary. Main derives the execution cwd from the successful ACP load, checks the exact session and generation, permits existing regular files outside the active workspace, and re-resolves each preview read or open. HTTP and HTTPS references are revalidated before external open; outgoing media URLs retain their managed-record binding. See `harness/reference/acp-attachment-access-control.md`.
Image generation and general attachments share transcript fetch coordination and opaque resolved media identities only. Generated images remain inline; general attachments render as paperclip rows after assistant prose.
## Historical Evidence
After successful `loadSession` for an existing session, the store may call:
```ts
hostApi.sessions.history({ sessionKey, limit: 1000 });
```
A pure image-generation extractor scans messages in transcript order. It first records an `image_generate` start from a tool result, then accepts a later internal-UI `message` tool source reply or assistant completion associated with that task. OpenClaw's runtime-generated inter-session completion trigger remains part of the originating user turn rather than starting a new end-user turn. Assistant media captions have their `MEDIA:` directives removed before display, and a task-correlated text-only assistant reply may restore a failure explanation. A message-tool reply or image completion without preceding task context is rejected. Separately, the general attachment extractor may accept canonical persisted assistant media facts or explicit assistant `MEDIA:` directives without image-generation context under the restrictions above. Read failure, no accepted evidence, duplicate evidence, or a stale generation leaves the ACP timeline unchanged.
These are the only transcript-derived Chat content supplements. Metadata-only whole-turn timing is also permitted, but it must not become a general recovery mechanism for missing turns, tool cards, file activity, plans, permissions, thoughts, or ordinary messages.
## Rejected Compatibility Alternatives
Main does not manufacture ACP `agent_message_chunk` resource events from transcript evidence because that would misrepresent compatibility data as native protocol replay. The ACP page does not reuse legacy Chat path extraction or rendering because that would restore competing history authorities. Standard-ACP-only behavior is insufficient while the distributed adapter omits assistant media, but the exception remains removable when upstream emits standard resources. Canonical persisted media facts are explicit structured evidence; bare-path or broad prose extraction without those facts remains rejected because false positives would widen the local-file trust surface.
## Trace Channel
Main owns one memory-only ACP trace ring buffer. The current implementation keeps 500 chronological entries with monotonic sequence numbers and ISO timestamps. `diagnostics.acpTrace()` returns a snapshot; Renderer records compact projection decisions through `diagnostics.recordAcpTrace()`.
Main records bridge lifecycle and summarized upstream/downstream routing. Renderer records reason-coded compatibility decisions such as start detection, rejection, dedupe, thumbnail result, stale drop, and append. Recording is best-effort and must never alter Chat behavior.
Before storage, Main validates and sanitizes all entries. The sanitizer removes secret-like keys and bearer/API-key values, truncates long strings, and bounds arrays and nesting. Call sites must submit summaries and must not include transcript bodies, binary media, or full ACP notifications; the generic sanitizer is defense in depth and cannot identify every semantically sensitive short value. Renderer payloads are untrusted. The trace is not persisted and has no user-visible UI.
## Validation Anchors
Key tests are `tests/unit/acp-image-generation-compat.test.ts`, `tests/unit/acp-media-attachments.test.ts`, `tests/unit/acp-chat-store.test.ts`, `tests/unit/attachment-access.test.ts`, `tests/unit/acp-trace.test.ts`, `tests/unit/acp-chat-service.test.ts`, `tests/e2e/chat-acp-attachments.spec.ts`, and the generated-media cases in `tests/e2e/chat-acp-inline-timeline.spec.ts` and `tests/e2e/chat-run-state-events.spec.ts`.
This reference consolidates the former image-generation completion, debug trace, and historical transcript supplement designs.
@@ -0,0 +1,78 @@
# Chat Workspace And Navigation
Status: current workspace reference, reviewed 2026-07-23.
Related scenario: `chat-workspace-and-navigation`
Related rules: `session-workspace-authority`, `sidebar-session-attention-authority`, `ui-i18n-design-tokens`, `office-preview-safety`, `web-browser-security-and-lifecycle`
Related tasks: `chat-workspace-context`, `sidebar-session-attention`, `office-document-preview`, `web-browser`
## Workspace Authority
OpenClaw's persisted ACP `cwd` is authoritative for a bound session. The global workspace is only the default for a new or not-yet-bound session. Resolution is:
1. Recoverable session `workspacePath` projected from OpenClaw ACP metadata.
2. Global workspace for a new or local unbound session.
3. `~/.openclaw/workspace` when a historical session has no recoverable cwd.
The effective workspace is shared by ACP load/prompt, the composer, sidebar grouping, the right-side workspace browser, and tool-derived file activity. A bound session is read-only in the composer and is not moved when the global selection changes. Missing or unreadable bound paths show unavailable/error state instead of silently changing roots.
ClawX persists global and recent workspace selections plus custom display labels through Main-owned settings APIs. On editable new or unbound chats, the composer menu shows the canonical default once, followed by deduplicated non-default workspaces from the most-recent list and known session paths, then the native folder picker. Recent entries stay first; all entries use custom display labels when available, keep the full path as hover text, and update only the global selection until first send binds the session. Custom labels are keyed by canonical path and never replace path identity or ACP cwd authority. Renderer session state may mirror the bound path for UI coordination, but must not become a competing persistent session-to-path authority. Targeted `@agent` sends intentionally use the target agent workspace and remain an explicit branch. Navigation records that workspace on the target session placeholder before reactive loading; a newly targeted agent's first send creates its main ACP session and shares one load identity with the prompt so navigation cannot supersede delivery.
## First Send And Titles
First send initializes the ACP session with the selected cwd and then marks the local session as created/bound. A fresh session generated at cold start to replace hidden heartbeat history is marked as the same kind of local placeholder; it cannot appear as a normal empty session or bypass first-send creation. Gateway event and canonical-list reconciliation preserve the local `createdLocally` marker until acknowledgement, even when OpenClaw already reports the same key with the ACP bridge display name. The acknowledgement atomically restores a raced-away placeholder when necessary, clears the marker, and seeds a missing automatic sidebar title from the raw first prompt. The newly visible row therefore never falls back to the bridge client identity while transcript title hydration catches up. Existing explicit or cached labels win. ACP keeps `_meta.prefixCwd: true`; disabling cwd injection would break OpenClaw context. Automatic titles instead normalize away one leading `[Working directory: ...]` envelope and subsequent whitespace.
Normalization applies to automatic sources such as Gateway-derived title and Main transcript summary. It never changes an explicit user label, never removes a non-leading marker, and treats the exact truncated envelope form as a missing title so a better summary can replace it. OpenClaw's synthetic `<first 8 session UUID characters> (YYYY-MM-DD)` fallback is also treated as missing only when it matches the row's full session id; Main's transcript summary then supplies the first user prompt. Opening and closing rename mode without changing the value must not persist any displayed fallback as an explicit label.
## Sidebar Navigation
Sessions are grouped by workspace, not by date bucket. The default workspace sorts first and other workspace labels use natural ordering. Within a group, activity sorts descending using:
1. Hydrated session last activity.
2. Summary `updatedAt`.
3. Timestamp parsed from the session key.
4. Zero.
Each group initially displays five sessions and loads five more at a time. Collapse and visible-count state are per workspace and in memory. Relative time and ordering use the same timestamp; actions replace the timestamp on hover or keyboard focus.
Non-default workspace headers expose a rename action on hover or keyboard focus. A custom name updates both the sidebar group and the composer workspace chip; the header and chip keep the full filesystem path in their title text.
Sidebar validates distinct non-default group paths through Main. A confirmed unavailable group shows a warning badge and destructive delete action; available, unresolved, and default groups do not. One confirmation hard-deletes the group's sessions sequentially across agents. Successful sessions disappear together, failed sessions remain for retry, and workspace recents/labels are removed only after the full group succeeds.
## Sidebar Session Attention
OpenClaw Gateway session rows are the sole authority for sidebar run state. ClawX subscribes to `sessions.changed`, reconciles exact session keys into the existing session catalog, and uses canonical `sessions.list` snapshots for startup and reconnect recovery. ACP prompts, ACP timeline events, and Gateway agent runtime events do not provide a second status source.
The trailing row content has strict `busy > unread > timeago` precedence. A Gateway-active row shows the localized busy indicator. An observed busy-to-idle transition shows the localized unread indicator until the conversation is opened, after which the relative activity time returns.
Read state follows visible Chat integration rather than the retained current-session key. Chat marks its session visible on mount and on each session-key change, clears visibility on unmount, and treats completion for that visible session as read. Routes such as Settings may retain the current key, but completion there remains unread. The sidebar click path also marks the session read synchronously before navigating to Chat.
The versioned attention store persists only exact-key `observedBusy` and `unread` state. This allows a later idle canonical snapshot to recover completion when ClawX previously observed the run as busy, including across an app restart. A run that starts and finishes while ClawX is fully offline cannot be inferred and must not create unread state. Run-scoped cron keys also cannot drive base-row attention because the bundled Gateway does not expose a recoverable canonical relationship.
The complete projection, persistence, list/event ordering, failure recovery, and future `sessions.patch({ unread: false })` migration are documented in `harness/reference/sidebar-session-attention.md`.
## Workspace Browser And Local HTML Preview
The right panel tabs are Workspace, Preview, and Changes. Workspace keeps the store tab value `browser`; authorized local HTML opens in `preview`. The Workspace tree uses `react-arborist`, includes hidden files, uses relative path as node identity, and remains read-only: no edit, drag/drop, or multi-select. Agent and path tags replace the older `Workspace - agent` header. Home is compacted to `~`, the path's final segment remains visible, and the full value is available as a title.
File icons come only from trusted bundled assets. Selecting a file preserves the existing preview behavior and backend boundary.
Local HTML Preview uses one hardened Electron guest as an implementation detail. The HTML anchor marks the Preview body while the route-stable host mounted by `MainLayout` owns the guest. There is no browser tab, empty guest entry, Home page, or address bar. Stable selectors are `html-preview-anchor`, `html-preview-host`, and `html-preview-webview`. Its file-only security and inert-link contract is documented separately in `harness/reference/web-browser.md`.
## Office Document Preview
The Workspace and Preview surfaces support read-only `.docx` and `.pptx` files; legacy `.doc` and `.ppt` files remain system-open-only. Extension is authoritative, and compressed DOCX/PPTX input is limited to 20 MB before Renderer parsing. Scoped workspace and attachment references use only their authorized Host API read route and never fall back to a naked path. Workspace Browser intentionally retains its existing Host-validated absolute-path read flow.
DOCX generated content is isolated and its links are non-interactive. PPTX renders one slide at a time, and kept-mounted artifact surfaces conditionally mount it so the shared Electron Renderer has a single mounted PPTX viewer. Cleanup releases ClawX-owned resources and invokes public `destroy()` exactly once, while the reviewed dependency-owned retained-resource limitation remains accepted. Exact security and lifecycle requirements are in `harness/specs/rules/office-preview-safety.md`; dependency choices, rendering decisions, user-visible limitations, and future hardening are in `harness/reference/office-document-preview.md`.
## Question Navigation
The Chat question directory belongs to the active ACP timeline rather than workspace persistence. Its current behavior is documented in `harness/reference/acp-chat.md`.
## Validation Anchors
Key tests include `tests/unit/workspace-context.test.ts`, `tests/unit/session-title.test.ts`, `tests/unit/session-buckets.test.ts`, `tests/unit/sidebar-session-buckets.test.ts`, `tests/unit/use-new-chat-action.test.tsx`, `tests/unit/chat-store-session-label-fetch.test.ts`, `tests/unit/workspace-browser-body.test.tsx`, `tests/unit/office-file-viewers.test.tsx`, `tests/unit/chat-acp-page.test.tsx`, `tests/unit/artifact-panel-store.test.ts`, `tests/unit/artifact-panel.test.tsx`, `tests/unit/main-layout.test.tsx`, `tests/unit/web-browser-host.test.tsx`, `tests/e2e/chat-workspace-context.spec.ts`, `tests/e2e/chat-acp-attachments.spec.ts`, `tests/e2e/chat-file-changes.spec.ts`, and `tests/e2e/office-document-preview.spec.ts`.
This reference consolidates the former workspace sidebar, chat workspace context, sidebar workspace UI, and ACP working-directory title designs. The later flat activity-sorted sidebar supersedes the earlier recency buckets.
+15
View File
@@ -0,0 +1,15 @@
# Electron E2E Parallelism
ClawX launches one Electron process per Playwright test with a test-scoped HOME and user-data directory. Ordinary specs can therefore run in separate workers without sharing application stores or OpenClaw files.
The Playwright project graph has three ordered lanes:
1. `exclusive` runs tests tagged `@exclusive` with one worker.
2. `parallel` runs all ordinary functional tests with the configured worker count after `exclusive` succeeds.
3. `performance` runs tests tagged `@performance` with one worker after functional tests finish.
Real clipboard tests are exclusive because Electron renderer instances read and write the same OS clipboard. Renderer performance tests run last because concurrent Electron processes distort CPU, GPU, frame-pacing, and elapsed-time evidence even when their files are otherwise isolated. `test.describe.configure({ mode: 'serial' })` is not sufficient for either case because it does not prevent another spec file or project from running at the same time.
New tests are parallel by default. A test that uses an OS-global resource must import and apply `E2E_EXCLUSIVE_TAG`; a host performance profile must use `E2E_PERFORMANCE_TAG`. Extend `tests/unit/e2e-parallel-policy.test.ts` when another recognizable global API is introduced. No static check can identify every possible external side effect, so reviewers must classify tests that use native dialogs, keychains, fixed ports, fixed writable paths, external runtimes, or other machine-global state.
Use `CLAWX_E2E_WORKERS` to override the ordinary worker count on constrained or high-capacity machines. Playwright project dependencies make a directly filtered ordinary spec run the exclusive prerequisite first; add `--project=parallel --no-deps` when a focused command intentionally needs only an audited ordinary spec. `pnpm run perf:chat` selects the performance project without running its dependencies.
@@ -0,0 +1,29 @@
# Electron Rendering Performance
Status: hardware-acceleration policy and interaction profile baselined 2026-08-01.
Related scenarios: `acp-chat-experience`, `chat-workspace-and-navigation`
Related rule: `electron-rendering-performance`
Related task: `restore-hardware-accelerated-rendering`
## Runtime Policy
ClawX leaves Electron and Chromium hardware acceleration enabled by default. Main must not call `app.disableHardwareAcceleration()` or append a global `disable-gpu` switch. Chromium owns driver detection and fallback; users with a broken driver may still launch ClawX with Chromium's native `--disable-gpu` switch.
Headless Linux and virtualized CI may report software compositing because no usable GPU is present. Tests must distinguish that environment fallback from an application-owned global disable policy. Desktop GPU assertions therefore run only where the test environment provides a real desktop GPU.
## Diagnostic Contract
`pnpm run perf:chat` covers both high-frequency ACP streaming and idle interaction with a rich static Markdown document. The interaction workload records sidebar-collapse and vertical-scroll frame intervals, Renderer performance metrics, DOM size, GPU feature status, and Renderer/Main CPU profiles. It uses generated content and writes only ignored Playwright artifacts.
For a reported desktop regression, first reproduce with the user's real conversation and record `app.isHardwareAccelerationEnabled()` plus `app.getGPUFeatureStatus()` after `gpu-info-update`. Compare repeated runs on the same machine. Main CPU profiles do not include browser/GPU process rasterization or compositing, so a profile dominated by Chromium `(program)` time must be interpreted together with frame pacing and GPU status rather than as unexplained React work.
Do not add machine-independent frame-time gates. Preserve semantic assertions, generated workload shape, and artifact schemas; compare repeated local or controlled-run medians when reviewing rendering changes.
## Validation Anchors
- Main policy: `electron/main/index.ts` and `tests/unit/main-hardware-acceleration.test.ts`.
- Desktop runtime behavior: `tests/e2e/hardware-acceleration.spec.ts`.
- Streaming and interaction profiles: `tests/e2e/renderer-performance.spec.ts` through `pnpm run perf:chat`.
+80
View File
@@ -0,0 +1,80 @@
# Markdown Rendering
Status: migration contract baselined 2026-08-01; implementation is validated by the related task.
Related scenarios: `acp-chat-experience`, `chat-workspace-and-navigation`
Related rule: `markdown-rendering-safety-and-performance`
Related task: `replace-markdown-renderer-with-streamdown`
## Rendering Ownership
ClawX has two application Markdown surfaces with distinct update behavior and one shared renderer configuration:
| Surface | Mode | Content |
| --- | --- | --- |
| ACP Chat | `streaming` | Assistant message and process Markdown parts |
| Markdown file preview | `static` | Authorized local Markdown file content |
User messages remain literal React text and tool output remains preformatted. Neither enters Streamdown. The migration is presentation-only: ACP transport, event ordering, timeline reduction, store cadence, history, and Renderer/Main boundaries do not change.
The shared plugin, rehype, component, animation, controls, and link-safety values remain module-scoped. Stable references allow Streamdown to retain completed block output instead of invalidating memoized blocks on each chunk.
## Plugin Contract
Exactly these optional capabilities are enabled:
- `@streamdown/code` for Shiki-backed fenced-code highlighting.
- `@streamdown/math` for KaTeX, configured with `singleDollarTextMath: true`.
- `@streamdown/cjk` for CJK-aware autolink and punctuation boundaries.
`@streamdown/mermaid` is not a direct dependency and is not configured. A `mermaid` fence remains an ordinary highlighted code block and never becomes a diagram, SVG, or interactive Mermaid container.
KaTeX remains a direct dependency because the math plugin requires its CSS. The application imports `katex/dist/katex.min.css` exactly once. It also imports `streamdown/styles.css` exactly once so the selected animation keyframes and data-attribute styles exist. Tailwind scans Streamdown and each installed plugin distribution, but no Mermaid distribution path.
## Content Safety
Streamdown does not expand the authority of generated content:
- User text and tool output remain literal outside the Markdown renderer.
- The shared rehype list retains Streamdown sanitization and hardening but omits raw-HTML parsing. Source HTML such as `<script>alert(1)</script>` remains visible text and does not create an element.
- Links render through `BrowserLink`, which has no interactive anchor role or navigation. Streamdown link-safety UI is disabled because links are already inert.
- ACP Markdown images continue through `isSafeAcpImageSource`; an unapproved source does not become an image request.
- Table, Mermaid, code download, and line-number controls are disabled. Fenced code alone exposes Streamdown's copy control with its label supplied through `react-i18next`; the control remains disabled while a response is streaming.
Static preview keeps `remark-frontmatter` for YAML (`---`) and TOML (`+++`) frontmatter. Parsed frontmatter is omitted from visible output. There is no custom frontmatter splitter, metadata card, or metadata `<pre>`.
## Streaming And Animation
ACP Chat repairs incomplete Markdown while the response is active, but animation state is narrower than transport state. The Renderer derives active segment IDs from the open ACP assistant message segments only while send or cancel is active. A Markdown part receives `isAnimating`, word animation, and `caret="circle"` only when all of these conditions hold:
- Its assistant segment is currently open.
- It is the segment's final part.
- Its part kind is Markdown.
Earlier parts, completed segments, thoughts, user messages, and tool output never animate. The animation is word-level `fadeIn` with `duration: 140` and `stagger: 0`; character-level animation is forbidden. Previously completed words and blocks must remain stable as later chunks arrive, and the caret disappears when the send settles.
## Presentation Contract
Chat keeps the assistant-without-bubble layout and ClawX's established prose rhythm. Scoped Streamdown selectors restore heading and horizontal-rule margins over Streamdown's root spacing utility, compact ordered, unordered, and task-list items, and remove table wrapper borders while retaining the cell grid. Fenced code preserves Shiki's source-row spans as block lines, soft-wraps long lines, uses a compact right-aligned language header with vertically centered actions, and exposes copy without download; file preview keeps its preview-specific headings and inline code. Styling uses existing ClawX surfaces, text colors, dark-mode variants, and other design tokens; Streamdown defaults must not leak broad global changes into unrelated prose.
The supported math contract includes `$...$`, `$$...$$`, `\(...\)`, and `\[...\]`. CJK tests anchor punctuation exclusion from autolinks. Code tests wait for Shiki token output rather than assuming highlighting is synchronous.
## Performance Baseline And Review
`pnpm run perf:chat` builds the production Renderer and executes a deterministic 80-turn history plus 300 streaming chunks. Before renderer changes and after migration, run it three times on the same machine and retain each generated `renderer-benchmark.json`, `renderer.cpuprofile`, and `main.cpuprofile` under ignored `test-results/` paths.
Compare before/after medians for elapsed time, Renderer TaskDuration, ScriptDuration, layout and style duration, long-task count and duration, and sampled Markdown/React CPU stacks. Median TaskDuration and ScriptDuration must each stay within 10 percent of baseline. At least one of median ScriptDuration or sampled Markdown/render CPU time must improve by 10 percent or more. A miss requires profiling animation, Shiki, and last-block costs rather than weakening the threshold. Absolute machine timings are evidence for the local comparison, not automated cross-machine gates.
Build with `pnpm exec vite build --sourcemap` and inspect chunk sizes and source maps. Streamdown and Shiki are expected costs. The review must confirm no direct Mermaid plugin and no unexpected eager Mermaid renderer chunk. Dormant code retained by Streamdown core is measured and documented rather than described as Mermaid UI support.
## Validation Anchors
Shared configuration is anchored by `src/components/markdown/streamdown-config.ts` and `tests/unit/streamdown-config.test.tsx`.
Static preview behavior is anchored by `src/components/file-preview/MarkdownPreview.tsx`, `tests/unit/markdown-preview.test.tsx`, `tests/unit/file-preview-body.test.tsx`, and `tests/e2e/markdown-file-preview.spec.ts`.
Streaming state and rendering are anchored by `src/pages/Chat/AcpTimeline.tsx`, `src/pages/Chat/AcpAssistantTurn.tsx`, `src/pages/Chat/AcpMessageSegment.tsx`, `tests/unit/acp-chat-components.test.tsx`, and `tests/e2e/chat-streamdown-rendering.spec.ts`.
Existing soft-wrap, KaTeX, plain-assistant, and table-theme behavior remains anchored by `tests/e2e/chat-code-block-wrap.spec.ts`, `tests/e2e/chat-latex-rendering.spec.ts`, `tests/e2e/chat-assistant-markdown-plain.spec.ts`, and `tests/e2e/chat-table-header-light.spec.ts`. Performance evidence is produced by `tests/e2e/renderer-performance.spec.ts` through `pnpm run perf:chat`.
@@ -0,0 +1,197 @@
# Office Document Preview
Status: implemented contract, reviewed 2026-07-23.
Related scenarios: `chat-workspace-and-navigation`, `acp-chat-experience`, `acp-file-activity`
Related rule: `office-preview-safety`
Related task: `office-document-preview`
## Format And Limit Contract
Inline Office preview is extension-authoritative. Only the OOXML extensions below enter an Office parser:
| Extension | MIME mapping | Preview kind | Parser | Compressed input limit |
| --- | --- | --- | --- | --- |
| `.docx` | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` | `docx` | `docx-preview` | 20 MB (`20 * 1024 * 1024` bytes) |
| `.pptx` | `application/vnd.openxmlformats-officedocument.presentationml.presentation` | `pptx` | `pptxviewjs@1.1.9` | 20 MB (`20 * 1024 * 1024` bytes) |
The extension wins when MIME conflicts. MIME alone never opts an unknown, missing, `.doc`, or `.ppt` extension into an OOXML parser. Legacy `.doc` and `.ppt` remain system-open-only. Office previews are read-only and do not expose Source or Diff tabs.
The shared discriminated limit contract is exact:
| Preview target | Maximum accepted input |
| --- | --- |
| Text | 2 MB (`2 * 1024 * 1024` bytes) |
| DOCX or PPTX rich preview | 20 MB (`20 * 1024 * 1024` bytes) |
| Image, PDF, or sheet rich preview | 50 MB (`50 * 1024 * 1024` bytes) |
The maximum itself is accepted and one byte above it is rejected. The Office limit applies to compressed input before parsing. Known over-limit files do not mount a viewer or import a parser. Unknown-size files use the same value as the Host API read `maxBytes`, so a race-time size increase returns `tooLarge` without transferring parser input.
## Dependencies And Loading
- `docx-preview` converts DOCX bytes to the generated HTML and CSS used for page preview. Its incomplete Word layout model is an accepted fidelity limitation.
- Exactly `pptxviewjs@1.1.9` parses PPTX packages and paints one slide at a time to Canvas. The version is pinned because the reviewed global-state, scheduler, cleanup, and accepted-retention decisions are specific to 1.1.9.
- `jszip` satisfies the PPTX parser's peer dependency and is the ZIP implementation used by the selected Office parsing dependencies.
- `chart.js` supplies `chart.js/auto`, which the selected `pptxviewjs` ESM build imports to paint supported embedded charts.
`FilePreviewBody` and `WorkspaceBrowserBody` load both Office viewer components with React `lazy()`. Each viewer dynamically imports its parser only after an authorized, in-limit binary read succeeds. This keeps the viewers, `jszip`, `chart.js`, and parser code out of the synchronous chat entry path and ensures rejected input cannot trigger parser initialization.
## Read Authority
Each viewer selects exactly one existing binary route and passes the 20 MB maximum:
| Target authority | Read route |
| --- | --- |
| Ordinary local path, including Workspace Browser's already validated absolute path | `readBinaryFile(filePath, { maxBytes })` |
| Explicit `WorkspaceFileRef` | `readWorkspaceBinary({ ...workspaceFileRef, maxBytes })` |
| Explicit `AttachmentFileRef` | `readAttachmentBinary(attachmentFileRef, maxBytes)` |
A target containing both scoped reference types is invalid and fails before any read. A scoped target never retries through `filePath`, another scope, or a naked-path API. Workspace Browser deliberately retains its existing Host-validated absolute-path route; other workspace-derived file activity enters Preview with its `WorkspaceFileRef`. Remote attachments do not enter preview and no preview-specific download flow exists.
Document bytes remain inside the existing Renderer/Main Host API boundary. The Renderer passes `Uint8Array` to parser APIs and does not use direct filesystem access, document `fetch()`, parser URL loaders, temporary files, uploads, Gateway endpoints, or a Main-process or external conversion service.
## Over-Limit Authority Routing
Over-limit behavior follows the target's authority rather than the display surface:
| Target | Behavior |
| --- | --- |
| Ordinary local Preview target | Show the too-large/direct-open surface with confirmed system open and reveal actions. |
| Workspace Browser validated absolute path | Show the same confirmed direct-open and reveal actions. |
| Local authorized attachment known to be over limit | `attachmentOpenMode()` chooses the existing scoped `hostApi.files.openAttachment()` system-open flow. |
| Remote attachment | Keep the existing scoped system-open flow; do not preview or download for preview. |
| `WorkspaceFileRef` Preview target | Show `tooLarge` without naked-path shell actions. |
| Scoped attachment whose bounded read detects a race-time size increase | Show `tooLarge` without falling back to a naked path. |
This distinction is required: ordinary paths own local shell authority, while scoped references retain only their scoped Host API authority.
## DOCX Rendering
`DocxViewer` creates a new detached body container and style container for each target generation. It invokes `renderAsync()` while both are disconnected, then appends the current generation's completed containers to an open Shadow Root on the React-owned host. Generated document CSS and DOM therefore cannot rewrite ClawX layout, and stale reads or renders cannot replace the selected document.
The render options are exact:
```ts
{
className: 'clawx-docx',
inWrapper: true,
ignoreWidth: false,
ignoreHeight: false,
ignoreFonts: false,
breakPages: true,
ignoreLastRenderedPageBreak: false,
renderHeaders: true,
renderFooters: true,
renderFootnotes: true,
renderEndnotes: true,
renderChanges: false,
renderComments: false,
renderAltChunks: false,
useBase64URL: true,
experimental: false,
debug: false,
}
```
`renderAltChunks: false` prevents embedded HTML parts from entering the preview. Comments and tracked changes are disabled. `useBase64URL: true` avoids library-created Blob URL lifetime and keeps generated resources releasable with the Shadow Root containers.
Capturing `click` and `auxclick` listeners on the Shadow Root prevent the default action of every generated anchor. Hash, HTTP(S), file, and custom-protocol links are all non-interactive; DOCX preview cannot navigate the ClawX window or invoke shell authority.
Pages remain centered, vertical, authored-size paper sheets. A `ResizeObserver` resets body CSS `zoom` to `1`, measures the widest `section.clawx-docx`, and applies `Math.min(1, host.clientWidth / widestPageWidth)`. Chromium CSS zoom scales dimensions and flow together. The viewer scales down to fit but never enlarges above authored size.
On target replacement or unmount, ClawX disconnects the observer, removes generated style/body containers, clears their children, and drops its direct byte and DOM references. An uncancellable render may finish after cleanup, but generation checks prevent it from attaching stale content.
## PPTX Rendering And Scheduling
`PptxViewer` uses one React-owned Canvas keyed by target identity. Unlike DOCX resources, the initial PPTX Canvas is mounted when `pptxviewjs` renders into it; it is not first rendered detached. Target identity, committed-generation checks, and latest-request checks prevent stale work from publishing, while React key replacement or unmount detaches the obsolete Canvas.
The `PPTXViewer` constructor receives exactly these behaviorally significant options:
```ts
{
canvas,
enableThumbnails: false,
slideSizeMode: 'fit',
backgroundColor: '#ffffff',
autoChartRerenderDelayMs: 0,
}
```
Before initial rendering, the viewer waits for positive container width and height for at most 60 checks, using at most 59 animation-frame waits. It applies the current container width and height as Canvas CSS dimensions before every render. `slideSizeMode: 'fit'` preserves the source aspect ratio within the centered preview surface.
A module-level promise queue serializes all `pptxviewjs` operations across lifecycles: construction, `loadFile()`, slide-count access, initial render, restored-position render, navigation, chart refresh, resize render, and `destroy()`. Each render request carries its generation, request identity, latest slide, and latest measured size; work made obsolete before execution is skipped. A failed current render terminates that lifecycle, while a rejected obsolete render cannot replace or fail the new target.
The presentation is parsed once per mounted target. Initial rendering always paints slide index zero. If the owning surface has a stored index for the same target identity, the viewer clamps it to the loaded slide range and then renders it. Position display is one-based, navigation is disabled at boundaries and while rendering, and `onSlideIndexChange` fires only after a successful current render.
The `ResizeObserver` uses a 100 ms trailing debounce. The callback does not render directly; after the debounce it re-reads dimensions and queues a current-slide refresh. Setting `autoChartRerenderDelayMs: 0` disables the dependency's uncancellable delayed chart render. The global `chartRenderingComplete` listener coalesces events while a refresh is pending and submits refreshes through the same serialized scheduler. Cleanup removes the listener and observer and cancels owned timers and animation frames.
## Single PPTX Instance
`pptxviewjs@1.1.9` stores presentation chart and ZIP state in Renderer globals including `window.currentProcessor` and `window.currentZipData`. At most one `PptxViewer` may therefore be mounted in the shared Electron Renderer. This is a correctness requirement, not a performance preference: concurrent decks could resolve chart or package data from the wrong presentation.
Workspace and Preview surfaces remain mounted to preserve surrounding UI state, but each conditionally mounts its PPTX child only while its artifact tab is active. CSS-only hiding is insufficient. A development assertion rejects a second concurrent viewer. The owning Workspace and Preview surfaces retain slide positions in maps keyed by target identity; switching away destroys and unmounts the viewer, and switching back reparses the deck and restores the clamped position.
Cleanup queues the active instance's public `destroy()` exactly once after preceding dependency work. ClawX removes all listeners, observers, timers, animation frames, queued request references, and its direct instance and Canvas ownership. The dependency limitations below mean this does not claim full internal reclamation.
## Fullscreen Preview Surface
The Chat Preview header exposes a localized icon control that moves the selected `FilePreviewBody` into a portal filling the Renderer viewport. This is an application overlay, not Electron window fullscreen, and applies consistently to every file format supported by the Preview surface. It preserves target identity and target-keyed PPTX slide position while switching between compact panel layout and full layout.
The same header control exits fullscreen, and Escape provides a keyboard exit. Switching away from the Preview artifact tab also closes the overlay. Portal transitions may remount a viewer, but the previous PPTX lifecycle is torn down before the replacement becomes active so the single-mounted-viewer invariant remains intact.
## States And Errors
Both viewers expose four lifecycle states:
- `loading`: authorized read, lazy parser import, parse, or initial render is in progress.
- `ready`: DOCX pages or the current PPTX slide and controls are visible.
- `tooLarge`: preflight or the bounded Host API read rejects input above 20 MB.
- `error`: authority validation, read, empty input, parse, layout sizing, or render failed.
Errors use localized format-specific generic messages and never show parser exceptions, paths from parser errors, or stack traces. Corrupt, malformed, encrypted, password-protected, empty, and otherwise unsupported OOXML inputs may fail into `error`. There is no automatic retry loop. Reselecting or reopening a target creates a new load.
## Non-Goals
- Legacy `.doc` or `.ppt` parsing or conversion.
- Editing, saving, comments, tracked changes, Word search, or table-of-contents tooling.
- Pixel-identical Microsoft Word or PowerPoint layout.
- DOCX link opening or application-window navigation from generated content.
- PPTX thumbnails, slide-navigation keyboard shortcuts, animation, transitions, media playback, presenter mode, or automatic slide shows. The generic Preview surface can fill the application viewport, but it does not implement PowerPoint presenter behavior or native Electron fullscreen.
- Remote-attachment downloading for preview.
- Main-process, server, cloud, or external-service conversion.
- Changes to existing PDF, spreadsheet, image, HTML, Markdown, source, or diff behavior.
## Rejected Alternatives
- MIME-driven Office parser selection was rejected because legacy or unknown extensions must not enter an OOXML parser.
- Main-process or cloud conversion, temporary-file conversion, parser URL loading, and Renderer `fetch()` were rejected to preserve existing authority and data boundaries.
- DOCX light-DOM rendering and interactive generated links were rejected because document CSS and navigation must not gain application authority.
- Transform-only DOCX scaling was rejected because transformed pages can overlap later flow; Chromium CSS zoom scales layout dimensions with content.
- Keeping multiple PPTX viewers mounted under CSS `hidden` was rejected because shared dependency globals can cross-contaminate presentations.
- Independent initial, navigation, chart, and resize render paths were rejected because uncancelled operations can race. One serialized scheduler owns every dependency operation and render source.
- The library's delayed chart rerender was rejected in favor of an owned, coalesced event refresh. Patching `pptxviewjs` internals was also rejected; the reviewed public API and accepted limitation remain explicit.
## Accepted Risks And Limitations
- Both ZIP-based parsers run in the Renderer and can briefly occupy the UI thread on complex in-limit files.
- A 20 MB compressed cap reduces but does not eliminate ZIP expansion or high peak-memory risk.
- `docx-preview` is not Word's pagination engine; wrapping, page breaks, fonts, and layout can differ.
- `pptxviewjs` has incomplete PowerPoint fidelity for uncommon shapes, fonts, animations, transitions, and media.
- Embedded fonts depend on available platform fonts and fallbacks.
- Public `destroy()` in `pptxviewjs@1.1.9` does not fully clear internal caches, URLs, delayed work, or chart-related globals. Repeated presentation switches may retain dependency-owned memory until the Renderer exits. The single-instance rule prevents concurrent cross-presentation corruption but does not eliminate this accepted retention risk.
## Future Hardening
The current 20 MB check is a product performance guard, not a complete malicious-ZIP boundary. Future ZIP hardening may add pre-parse entry-count, expansion-ratio, and XML-complexity budgets. Such checks must preserve the same target authority routes and fail before either parser receives bytes; they are not implemented or implied by the current release.
## Validation Anchors
Format classification and limits are anchored by `shared/file-preview/limits.ts`, `src/lib/generated-files.ts`, `src/lib/file-preview-capabilities.ts`, `tests/unit/generated-files.test.ts`, and `tests/unit/open-file-utils.test.ts`.
Renderer authority, DOCX isolation/options/links/zoom, PPTX construction/sizing/scheduling/chart behavior/restoration/cleanup, stale-generation handling, and generic errors are anchored by `src/components/file-preview/DocxViewer.tsx`, `src/components/file-preview/PptxViewer.tsx`, and `tests/unit/office-file-viewers.test.tsx`.
Surface preflight, authority-specific fallback, conditional mounting, and position ownership are anchored by `src/components/file-preview/FilePreviewBody.tsx`, `src/components/file-preview/WorkspaceBrowserBody.tsx`, `src/components/file-preview/ArtifactPanel.tsx`, `src/pages/Chat/AcpTurnFileActivity.tsx`, `src/pages/Chat/AcpAttachmentPart.tsx`, `tests/unit/file-preview-body.test.tsx`, `tests/unit/workspace-browser-body.test.tsx`, `tests/unit/artifact-panel.test.tsx`, and `tests/unit/acp-chat-components.test.tsx`.
`tests/e2e/office-document-preview.spec.ts` uses real deterministic DOCX/PPTX packages to anchor Shadow Root page rendering, Canvas pixels, chart completion, slide navigation, per-target position restoration, constrained-panel resizing, viewport-filling Preview transitions, the single-mounted-viewer invariant, Host API read routes, and absence of legacy direct IPC.
@@ -0,0 +1,23 @@
# OpenClaw Config Delivery
ClawX bundles OpenClaw 2026.7.1-2. OpenClaw owns the field-level decision between a no-op snapshot update, hot application, subsystem restart, and in-process Gateway restart.
Provider, Agent, Channel, skill, proxy, image-generation, and plugin-install helpers express config changes as mutators. One Main-owned coordinator owns selection of the authoritative baseline and the commit:
1. If Gateway is running, call `config.get` and require its runtime-shaped `config` object and `hash`. The coordinator accepts `raw` only as a compatibility fallback for older responses.
2. Clone the runtime-shaped config, apply the mutator, and call `config.set` with the serialized result and `baseHash: hash`. Using source-shaped `raw` as the preferred baseline can misalign redacted secret paths with OpenClaw's runtime-shaped restore baseline.
3. Retry one base-hash conflict from a fresh `config.get`; fail other RPC errors without writing around the running Gateway. If `config.set` durably wrote the exact requested snapshot but its response was lost when OpenClaw began a native code-1012 reload, verify that persisted snapshot after Gateway leaves running state and accept the existing commit without replaying it.
4. Treat success as converged and do not send `SIGUSR1` or schedule a redundant ClawX process replacement.
5. If Gateway is stopped or starting, apply the same mutator to `resolveOpenClawConfigPath()` under the shared config lock and do not start the Gateway.
This is not a write-then-notify design. No provider, Agent, Channel, skill, proxy, image-generation, or plugin-install helper may write the active config independently. The coordinator prevents a locally read stale snapshot from overwriting concurrent Gateway or CLI config changes.
Gateway WebSocket tracing must redact the complete serialized `raw` payload for `config.set`, `config.patch`, and `config.apply`; key-based structural redaction cannot inspect secrets embedded inside that string.
Coordinator-backed reads follow the same authority rule: prefer the runtime-shaped `config.get.config` object while Gateway is running and use JSON5 file parsing while it is not. Compound views derive all config-backed fields from one snapshot.
OpenClaw 2026.7.1-2 keeps auth-profile SQLite snapshots in memory. After a completed auth-store write batch, ClawX calls `secrets.reload` once when Gateway is running. `config.set` does not replace this refresh. Agent `models.json` needs no explicit RPC because OpenClaw re-reads it when its file fingerprint changes.
Before launch, upgrade compatibility cleanup checks the canonical `state/openclaw.sqlite` update-check row. If it exists, the SQLite row is authoritative and any legacy root `update-check.json` is moved with restrictive permissions under `backups/`; otherwise the JSON remains in place for OpenClaw to import. This cleanup runs after the one-time upgrade snapshot and prevents harmless updater-bookkeeping differences from blocking Gateway readiness or triggering an ineffective doctor retry. The snapshot is removed after either the native ready event or a successful RPC-router readiness fallback, covering the race where a fast Gateway emits readiness before ClawX attaches its WebSocket client.
Full ClawX process replacement remains necessary after a successful coordinator commit when values are injected only at process creation, including proxy environment changes, or for explicit manual lifecycle and health/crash recovery. OpenClaw config categories must not be duplicated as a ClawX restart whitelist.
@@ -0,0 +1,96 @@
# OpenClaw File Activity
Status: current compatibility and safety reference, reviewed 2026-07-23.
Related scenario: `acp-file-activity`
Related rules: `tool-derived-file-safety`, `session-workspace-authority`, `attachment-access-safety`, `office-preview-safety`
Related tasks: `restore-acp-file-activity`, `acp-media-attachments`, `acp-attachment-open-with`, `unify-acp-file-cards`, `office-document-preview`
## Semantics And Ownership
File activity is a pure Renderer projection over the active ACP timeline. It records file changes declared by successful OpenClaw file-editing tool calls. It is not a Git diff, a verified disk diff, or a session-start baseline.
ClawX does not scan or watch the workspace, create snapshots, infer shell/script side effects, parse arbitrary prose, call `sessions.files.list` to manufacture diffs, or persist an activity ledger. Main does not interpret tool semantics; it only performs workspace-scoped read/stat and explicit native file actions.
The supported tools are exactly `write`, `edit`, and `apply_patch`. Tool identity is the trimmed lowercase segment before the first colon in OpenClaw's ACP title. Status must be `completed`. Unsupported, malformed, pending, running, failed, and cancelled calls remain ordinary tool cards but produce no file activity.
## Canonical Inputs
For `write` and `edit`, path fields use this precedence: `path`, `file_path`, `filePath`, `file`.
`write` accepts string `content`, displays an empty-to-new fragment, and uses action `created`. This describes tool intent and does not assert that the file did not previously exist. A valid path without string content may produce a path-only record with unavailable line counts.
`edit` accepts `edits: Array<{ oldText, newText }>` and the official top-level `oldText`/`newText` compatibility shape. Invalid entries are skipped. Broad aliases such as `old_string` and `new_string` are intentionally unsupported.
`apply_patch` accepts OpenClaw's patch envelope and optional `<<EOF`, `<<'EOF'`, or `<<"EOF"` wrapper. Supported sections are Add, Update, Delete, and an immediate Move-to after Update. Add lines use `+`; Update lines use space, `-`, and `+`; the first Update chunk may omit `@@`; later chunks require it; `*** End of File` is syntax, not content. Grammar failure rejects the complete tool payload without partial activity. After a valid parse, independently unsafe paths may be omitted while valid in-workspace records remain.
A move normally creates source deletion and destination creation with update fragments attached to the destination. Equal normalized paths collapse to one modification.
## Data Model And Aggregation
The conceptual records are:
```ts
type AcpFileChangeFragment = {
oldText: string;
newText: string;
sequence: number;
};
type AcpFileActivity = {
turnId: string;
toolCallId: string;
toolName: 'write' | 'edit' | 'apply_patch';
relativePath: string;
action: 'created' | 'modified' | 'deleted';
fragments: AcpFileChangeFragment[];
sequence: number;
};
```
The implementation types in `src/lib/acp/openclaw-file-activities.ts` are authoritative. Sequence is derived display order, not persisted identity. Turn association reuses the ACP display grouping algorithm, including tool-only turns.
Reducer tool identity prevents duplicate activity. Within a turn, each path gets one button and summary while retaining chronological activities and fragments. Across the session, Changes groups by relative path in first-activity order and keeps turn records chronological. Exact duplicate pairs are omitted; safe chains compose when prior new text equals later old text; independent fragments share one display diff without claiming to be a cumulative patch.
Line counts normalize CRLF, compare fragments, and sum additions/removals. Missing countable fragments produce unavailable counts rather than invented zeroes.
## Path Security
Tool paths are untrusted. `workspaceRoot` is the containment boundary and `executionCwd` is the ACP working directory. Relative paths resolve against execution cwd; both relative and absolute candidates must remain lexically inside workspace root and use the same path family. Replay without authoritative root and cwd produces no projection.
Preview and explicit native actions use a relative reference end to end:
```ts
type WorkspaceFileRef = {
workspaceRoot: string;
relativePath: string;
};
```
Main independently canonicalizes each read/stat/native-action request, checks real paths and nearest existing parents, rejects traversal, non-files, and symlink escape, and avoids following unsafe final links. Handler discovery, selected-handler open, and reveal each re-resolve the `WorkspaceFileRef`; selected-handler open performs an additional callback revalidation immediately before native invocation. Renderer lexical rejection prevents activity UI for obvious outside paths. A later Main rejection keeps the historical activity while refusing the requested file operation.
Tool-derived targets are read-only in-app previews and never use naked-path shell APIs. Created and modified activity may expose a separate Open with menu whose native actions are backed only by workspace-scoped Host API operations; deleted activity does not. For HTML, the menu first offers browser navigation to the file URL constructed from the effective workspace root and contained relative path. The native adapter receives a Main-owned canonical path and opaque handler id, and Main revalidates the workspace reference before invocation. Linux offers only workspace-scoped reveal after the browser action where eligible.
`src/pages/Chat/AcpFileCard.tsx` supplies the shared attachment/file-activity presentation shell and target-aware menu without sharing grants. In-limit DOCX/PPTX activity reaches the Office viewers through its `WorkspaceFileRef`; parsing and single-viewer constraints are documented in `harness/reference/office-document-preview.md`.
## Separation From Attachments
File activity and user-facing attachments are separate projections and security boundaries. Incidental paths in tool input or output remain tool-derived evidence: they cannot become attachment cards, resolve outside the workspace, or use attachment-scoped authorization. Attachment evidence must instead come from standard ACP resource content, a Main-owned user staging record, or the bounded explicit assistant `MEDIA:` exception documented in `harness/reference/acp-generated-media-and-diagnostics.md#bounded-transcript-exceptions`.
Main establishes attachment session and relative-path context only when the ACP session load or creation succeeds. Each attachment resolve, preview read, and system or external open then revalidates the exact session, generation, reference, and canonical target; unlike tool-derived file activity, explicit attachment evidence may resolve outside the workspace. File activity never enters that attachment pipeline: its explicit native actions remain restricted to the canonical workspace through `WorkspaceFileRef`. The complete attachment boundary is documented in `harness/reference/acp-attachment-access-control.md`.
## User Experience And Replay
Each assistant turn shows one file button and one summary per eligible path. Created/modified buttons open current-file Preview and include Open with; deleted buttons open Changes and omit Open with. Changes is session-scoped, grouped by file, and shows at most one diff editor per turn and path. Empty sessions explicitly state that the session has no file changes.
When a preview supports multiple views, its segmented switcher shares the trailing side of the file name/path header rather than consuming a separate row. HTML files expose `Preview` then `Source`, default to the sandboxed rendered preview, and preserve the same scoped read result when switching views.
Full ACP structured replay restores available activity through the same projection. Transcript-only or incomplete replay does not infer missing records. Session switch clears the projection with the active timeline.
## Validation Anchors
Key tests include `tests/unit/openclaw-file-activities.test.ts`, `tests/unit/files-api-workspace.test.ts`, the file-preview component suites, and `tests/e2e/chat-file-changes.spec.ts`.
This reference replaces the former OpenClaw file activity hydration design while retaining its protocol grammar, security model, and aggregation semantics.
@@ -0,0 +1,187 @@
# Sidebar Session Attention
Status: current architecture reference, reviewed 2026-07-23.
Related scenarios: `gateway-backend-communication`, `chat-workspace-and-navigation`
Related rule: `sidebar-session-attention-authority`
Related task: `sidebar-session-attention`
## Authority And Rationale
OpenClaw Gateway session rows are the sole authority for sidebar run state. The existing `useChatStore.sessions` collection remains the Renderer session catalog; attention adds presentation state, not a second catalog. This lets one projection cover ClawX prompts, channel-triggered work, and other Gateway clients whenever the Gateway projects the run onto the same catalog session key.
ACP prompt state and ACP timeline updates are scoped to an initialized agent connection and cannot observe the whole shared session catalog. Gateway `agent` lifecycle events and ClawX's local `sending` state describe other concerns and can be incomplete for work initiated elsewhere. None of them may derive or override sidebar busy or unread state. Renderer code continues to use the Main-owned Gateway connection through `hostApi`, `useGatewayStore.rpc`, and `hostEvents`; it does not open another transport.
The bundled OpenClaw 2026.6.10 behavior supporting this authority is:
1. `sessions.subscribe` enables `sessions.changed` notifications for a Gateway connection.
2. A notification includes a session snapshot when the Gateway can provide one.
3. `sessions.list` reconstructs `hasActiveRun` from the active-run registry and is the canonical recovery snapshot.
4. The OpenClaw WebUI applies reliable event snapshots and reloads the list when it cannot apply an event safely.
5. Terminal status overrides a stale active-run boolean; otherwise the boolean is authoritative, with `running` as the compatibility fallback.
When validating this upstream contract against a new OpenClaw version, inspect the session-list projection in `list.ts` and the WebUI Gateway reducer in `event.ts`, as well as the protocol definitions for subscription, event, and patch fields. Basenames are stated here because upstream source layout can move between releases.
## Catalog Normalization
`src/stores/chat/session-catalog.ts` supplies the shared allowlisted normalizer for both list rows and event patches. It trims the catalog key, lowercases and trims status, accepts finite numeric or parseable string activity timestamps, converts second timestamps to milliseconds, maps `lastChannel` before `channel`, and projects only known `ChatSession` fields. Unknown payload properties never enter the catalog.
List rows use the normalizer as complete row snapshots. Event rows use the same field conversion as presence-aware patches:
- An omitted property is not merged and leaves the existing value unchanged.
- An explicit boolean `false`, especially `hasActiveRun: false`, is retained rather than treated as absent.
- Explicit `null` clears an optional non-null `ChatSession` property; the catalog does not store literal nulls.
- A present value of an unsupported type is neither copied nor interpreted as a clear.
For a `sessions.changed` payload, identity and source selection are exact:
1. The envelope key is the first non-empty normalized top-level `sessionKey`, then top-level `key`.
2. The nested key is normalized from `session.key`.
3. If both keys exist and differ, reject the event and request a canonical reload.
4. Otherwise the resolved key is the nested key, then the envelope key.
5. A nested `session` object is the row source when present; otherwise the top-level envelope is the patch source.
6. An unknown row may be inserted only from a nested snapshot with its own non-empty, non-conflicting key. A partial envelope for an unknown key requires a reload.
7. `reason === "delete"` is accepted only with a valid envelope key and removes that exact key.
Catalog and attention identity is the normalized exact session key. Existing cron parsing may map a run-scoped key to a base key for activity sorting, but a key containing a cron run identity is never inserted, merged into, or reconciled as base-row attention. The current Gateway list cannot recover that relationship after reconnect.
## Run Projection
`projectSessionRunState` normalizes `status` with `trim().toLowerCase()` and returns `busy`, `idle`, or `unknown` in this exact order:
1. A recognized terminal status returns idle even if stale `hasActiveRun: true` is present. Bundled terminal values are `done`, `failed`, `timeout`, and `killed`; accepted aliases are `completed`, `finished`, `error`, `aborted`, and `cancelled`.
2. When present as a boolean, `hasActiveRun` returns busy for true and idle for false, regardless of another non-terminal status.
3. With no boolean, normalized `status === "running"` returns busy.
4. Every other row returns unknown and cannot create or clear an attention transition.
Attention reconciliation and sidebar presentation call this same helper. Event `phase`, activity timestamps, ACP state, and runtime events are not inputs to this projection.
## Attention State And Transitions
`src/stores/session-attention.ts` stores exact-key `{ observedBusy, unread }` records. Its Zustand persistence uses the versioned Renderer storage key `clawx.session-attention`, currently version 1. Only `bySessionKey` is persisted; `visibleSessionKey` is memory-only. Migration and merge sanitize the full persisted map and fall back to an empty map if any entry is malformed, so bad local data cannot block the sidebar.
The transition table is normative:
| Previous attention | Gateway projection | Visible Chat session | Result |
| --- | --- | --- | --- |
| Any | Busy | Any | Set `observedBusy=true`; retain the existing unread bit. |
| `observedBusy=true` | Idle | Same exact key | Set `observedBusy=false`, `unread=false`. |
| `observedBusy=true` | Idle | Different key or none | Set `observedBusy=false`, `unread=true`. |
| No observed busy | Idle | Any | Do not create unread; retain existing unread state. |
| Any | Unknown | Any | Preserve both attention fields. |
Retaining unread when another run becomes busy is intentional. The spinner hides the older dot while busy, but completion reveals unread again unless the conversation became visible. Persisting `observedBusy` also proves the restart-recovery case where ClawX observed busy, exited, and later receives an idle canonical row.
Filtered, partial, or temporarily incomplete lists do not prune missing attention entries. Only an exact deletion or explicit local session removal deletes one. Ordered transition folds commit one final attention map, avoiding intermediate spinner/dot renders.
The sidebar trailing area has strict `busy > unread > timeago` precedence:
- A live busy projection shows the localized spinner and hides unread and time.
- Idle with unread shows the localized blue dot and hides time.
- Idle and read shows the existing relative timestamp and full timestamp title.
- For an unknown live projection, persisted `observedBusy` shows the spinner, then persisted unread shows the dot, otherwise time remains visible.
The indicator labels are localized in all supported Chat locales, and the dot is not the only accessible unread indication. Attention never changes session activity ordering.
## Visible Session And Read Semantics
Read authority is the visibly mounted Chat conversation, not merely `currentSessionKey`. The Chat page calls `setVisibleSession(currentSessionKey)` while mounted and whenever the key changes, then calls `setVisibleSession(null)` on cleanup. Setting a non-null visible key atomically records visibility and clears that key's unread bit. Clearing visibility does not mark any conversation read.
A conversation is read in either case:
- Its exact key is visibly mounted in Chat when busy-to-idle is reconciled.
- The user activates its sidebar row. The click path calls `markRead` synchronously before switching/loading and navigating to Chat.
Deep links and programmatic navigation are covered by the Chat visibility effect. Settings and other routes can retain `currentSessionKey`, but because Chat is unmounted they are not read authority; completion there becomes unread.
## Gateway Epoch Subscription
`src/stores/gateway.ts` identifies a ready Gateway runtime as `${pid ?? "none"}:${connectedAt ?? "none"}:${port}`. A changed ready identity advances a numeric session-catalog generation. Leaving ready/running state clears the synchronized identity so a recovered connection establishes a new epoch.
For each ready epoch the coordinator:
1. Initializes generation-scoped event buffers and clears prior per-key and successful-list timestamp fences.
2. Calls `sessions.subscribe` once for that observed identity.
3. Forces `sessions.list` in `finally`, whether subscription succeeds or fails.
4. Logs subscription or hydration failure without blocking chat; a later ready epoch retries subscription.
Events arriving while subscription or an older list is pending are retained for the current generation. Forced epoch hydration cannot be satisfied by an older in-flight ordinary load: it queues a successor load after the old flight settles. Generation checks fence subscription, list, and replay work so a response from an old Gateway cannot install current state. Periodic Gateway status reconciliation can rediscover a missed restart and establish the corresponding epoch without repeatedly subscribing to an unchanged identity.
## List And Event Ordering
`sessions.changed` provides low-latency updates; `sessions.list` is canonical startup, reconnect, and uncertainty recovery. Every list request, including ordinary throttled loads, buffers session events in arrival order while the request is in flight.
For a successful timestamped list transaction:
1. Normalize, filter, and deduplicate the list into the candidate catalog.
2. Start attention reconciliation with the canonical list rows, excluding exact keys made uncertain by untimestamped buffered events.
3. Replay finite-timestamp buffered events in arrival order when `event.ts >= list.ts`. Equality is accepted because equal Gateway timestamps do not prove the event preceded the snapshot; only `event.ts < list.ts` is discarded.
4. Represent applied row snapshots and exact deletions as ordered attention transitions and fold them in memory.
5. Publish the final catalog and final attention result, not intermediate list/event states.
6. Schedule one forced follow-up when an applied event is partial, unsafe, or otherwise requests canonical recovery.
A successful finite `list.ts` advances the epoch's successful-list floor and each installed row's exact-key fence to `max(existingFence, list.ts)`. Outside a list flight, an event must have finite `ts`; events below the successful-list floor are discarded even for a key absent from the list. For a known exact key, an event older than its latest accepted timestamp is discarded. Equality is accepted at both fences; only strictly older timestamps are rejected. Terminal status still wins over stale `hasActiveRun` inside each accepted snapshot.
## Uncertainty And Failure Recovery
An event without finite `ts` is unorderable. It is not merged speculatively and causes one forced list recovery:
- If its exact key can be resolved, attention for that key is held unchanged while independently orderable keys may still reconcile.
- If no safe exact key can be resolved, all attention is held unchanged for that transaction.
- Missing or non-finite `list.ts` likewise prevents a reliable attention fold and schedules a follow-up list.
If `sessions.list` fails, finite current-epoch buffered events at or above the last successful-list floor are reduced against the existing catalog in arrival order. Reliable exact-key attention transitions are folded once; attention for keys touched by untimestamped events is preserved, and unscoped uncertainty preserves all attention. Applied exact deletions still clean catalog metadata and attention. One forced retry follows. If that retry also fails, the best reliable reduced state remains rather than fabricating an idle completion.
Malformed identity, conflicting nested/envelope keys, unknown partial rows, and other unsafe snapshots request throttled canonical recovery. Unknown run projection preserves the last attention state. A subscription failure does not disable list loading. A stale generation cannot recover or overwrite a newer one.
## Delete And Recreate Incarnations
An exact deletion removes the catalog row, persisted attention, cached sidebar label, and activity metadata. During buffered replay the delete occurs at its exact sequence position, so a same-key recreation starts with fresh attention before later busy and idle snapshots are folded.
Deletion also calls `clearSessionLabelHydrationTracking`. `src/stores/chat/session-label-hydration.ts` increments an in-memory incarnation included in each hydration version and clears handled/in-flight records. A recreated row with the same catalog key therefore receives a new version even if its activity timestamp and backend label are identical. Old async summary completion cannot mark the new incarnation handled or overwrite its label; new hydration can begin normally. This cleanup applies in standalone handling, successful list replay, and failed-list reduction.
## Limitations
- A run that starts and finishes while ClawX is fully closed is unobserved and cannot produce a justified unread marker with OpenClaw 2026.6.10.
- Run-scoped cron keys cannot drive base-row attention until `sessions.list` exposes a recoverable canonical relationship. They may still affect existing activity sorting.
- Local attention is presentation state, not a Gateway-wide read receipt. Another client opening a conversation does not clear ClawX's local unread bit.
- Missing rows in partial or filtered lists cannot prove deletion and therefore do not prune attention.
- Unknown Gateway state deliberately favors preserving the last indicator over guessing idle.
- The local attention store contains no messages, tool state, timelines, runtime graph, or route visibility.
## Future Gateway Unread Migration
When the bundled OpenClaw release provides durable row-level `hasActiveRun` and `unread` plus writable `sessions.patch`, replace local unread authority rather than layering Gateway unread over the current store. This migration is self-contained:
1. Confirm the upgraded protocol's list, event, patch, timestamp, and deletion semantics with source and contract tests.
2. Extend the shared allowlisted row/patch normalizer to preserve explicit boolean `unread`, including false and null/omission behavior defined by that protocol.
3. Keep the current active-run projection, exact-key catalog authority, epoch subscription, canonical hydration, event buffering, and timestamp fences.
4. Render unread directly from the normalized Gateway row. Do not infer or merge it with local `observedBusy` transitions.
5. A sidebar activation or visibly mounted Chat conversation acknowledges the exact row through the existing Main-owned RPC boundary with `sessions.patch({ unread: false })`; optimistically clearing UI is acceptable only with canonical failure recovery.
6. Remove the local transition store and retire the `clawx.session-attention` persistence key through an explicit versioned cleanup so old local bits cannot reappear.
7. Preserve `busy > unread > timeago`, visible-Chat semantics, accessibility, and exact deletion behavior in unit and Electron E2E coverage.
Do not begin this migration merely because a type exists in an unbundled upstream branch. The bundled Gateway must expose and persist the complete contract used by ClawX.
## Rejected Alternatives
- ACP prompt/timeline state: scoped to ClawX-owned agent connections and misses channel or other-client runs.
- Gateway `agent` events or local `sending`: transport/runtime lifecycle is not the canonical session catalog projection.
- `updatedAt` inference: rename, metadata, transcript maintenance, and unrelated activity would fabricate unread completions.
- `currentSessionKey` as visibility: non-Chat routes retain it and would incorrectly mark hidden conversations read.
- A second Renderer session collection: duplicates catalog authority and creates divergent merge/deletion behavior.
- Event-only state: missed notifications and reconnects require canonical `sessions.list` recovery.
- Pruning absent list rows: filtered and partial snapshots do not prove exact deletion.
- Folding run-scoped cron keys into base rows: reconnect cannot reconstruct the relationship.
- Guessing fully offline completions: there is no durable evidence in the bundled protocol.
- A Renderer-owned Gateway socket or protocol switch: violates the Main-owned communication boundary.
## Validation Anchors
Primary implementation anchors are `shared/chat/types.ts`, `src/stores/gateway.ts`, `src/stores/chat.ts`, `src/stores/chat/session-catalog.ts`, `src/stores/chat/session-status.ts`, `src/stores/chat/session-label-hydration.ts`, `src/stores/session-attention.ts`, `src/components/layout/Sidebar.tsx`, and `src/pages/Chat/index.tsx`.
Focused unit anchors are `tests/unit/session-status.test.ts`, `tests/unit/session-catalog.test.ts`, `tests/unit/session-attention.test.ts`, `tests/unit/session-label-hydration.test.ts`, `tests/unit/gateway-events.test.ts`, `tests/unit/gateway-event-dispatch.test.ts`, `tests/unit/chat-store-session-label-fetch.test.ts`, `tests/unit/chat-session-management.test.ts`, `tests/unit/sidebar-session-buckets.test.ts`, `tests/unit/i18n-locale-parity.test.ts`, and `tests/unit/harness-specs.test.ts`. End-to-end presentation and navigation are covered by `tests/e2e/chat-sidebar-session-attention.spec.ts`.
Communication changes require the task's Harness validation, communication replay/compare, typecheck, lint, Vite build, targeted unit tests, and Electron E2E test.
+40
View File
@@ -0,0 +1,40 @@
# Local HTML Preview Architecture
ClawX no longer exposes a general-purpose embedded Web Browser. The remaining Electron webview is used only to render an authorized local `.html` or `.htm` file inside the existing Preview tab.
## User flow
- Activating local HTML from an attachment, file activity, or Workspace opens Preview.
- The HTML file menu offers the built-in Preview path alongside compatible system applications.
- The Preview header offers one file-level action to open the current HTML through the system browser.
- There is no browser tab, Home page, URL input, navigation history, refresh menu, favicon, cookie/site-data UI, or blank browser entry.
## Link behavior
All links are inert:
- ClawX-rendered Markdown/content links are plain text.
- Inside HTML Preview, Main injects user-origin CSS that removes anchor and area styling and pointer interaction.
- Main also prevents navigation independently, so scripts, forms, synthetic clicks, hash navigation, redirects, and popups cannot bypass the visual restriction.
- Downloads and network requests are canceled.
## Renderer flow
HTML entry points build an ordinary `FilePreviewTarget` and call `useArtifactPanel.openPreview`. `FilePreviewBody` renders an HTML anchor in Preview. The route-stable host in `MainLayout` overlays one webview on that anchor and asks `hostApi.webBrowser.navigate` to load the selected file.
The host has no browser chrome. It exists only for an HTML `focusedFile`, remains hidden and inert when Preview is not visible, and can recover a crashed guest without restoring browsing state. Because the guest is route-stable and positioned over a Renderer anchor, it raises its stacking level above the fullscreen Preview layer whenever that anchor is portaled to the fullscreen surface.
## Main boundary
`normalizeWebBrowserHtmlFileUrl` accepts only hostless, query-free, fragment-free `file:///` URLs ending in `.html` or `.htm`. The Host API has only:
- `navigate`: load one validated local HTML URL in the registered guest.
- `openExternal`: revalidate the selected local HTML URL, then call `shell.openExternal`; it does not accept web destinations.
Main retains the exact guest identity gate, one-live-guest registry, fixed isolated `persist:clawx-web-browser` partition and User-Agent, sandbox, context isolation, web security, and disabled Node/preload surface.
The dedicated Session denies all permissions, cancels downloads, blocks network protocols, and rejects non-HTML main documents. The guest policy denies all child windows and every guest-initiated top-level or in-page navigation.
## Security consequence
The preview can execute self-contained local HTML scripts for rendering, but it cannot follow links, leave its selected document, request network data, download files, obtain device permissions, or access ClawX/Electron APIs.
@@ -0,0 +1,17 @@
---
id: acp-chat-state-and-history
title: ACP Chat State And History Authority
type: ai-coding-rule
appliesTo:
- acp-chat-experience
- acp-file-activity
- gateway-backend-communication
---
Main owns ACP process, SDK, routing lifecycle, and serialization of operations on the shared ACP connection; Renderer owns semantic reduction into an in-memory timeline. The local ACP child receives the authoritative `gatewayToken` from Electron store through `OPENCLAW_GATEWAY_TOKEN`; it must not rely on a separately resolved OpenClaw config credential or expose the token through CLI arguments or Renderer state. Notifications emitted during `session/load` are returned as one generation-scoped raw batch and reduced in one Renderer state commit. Renderer may temporarily buffer matching host events during the IPC result handoff, while each ordinary live prompt update continues through host events and is applied immediately without a Renderer batching timer. A pending prompt may retain a bounded Main routing context and Renderer timeline snapshot so navigation cannot drop its stream; those contexts must be keyed by session and generation, remain memory-only, and be released when the prompt settles. Gateway restart recovery must use explicit source-run lineage from trusted OpenClaw recovery provenance; ACP may adopt a new run only when `resumedFromRunId` matches its pending prompt, and Renderer must not reload a session based on Gateway runtime identity. An acknowledged prompt may remain pending for at most 60 seconds after disconnect so Gateway startup backoff and restart recovery can complete, while an unacknowledged send retains the 5-second deadline. Permission requests are interactive only for an active prompt. Stale session generations are ignored, and ClawX does not persist a second ACP ledger or reduced Chat history.
ACP is the preferred authority for every Chat semantic it exposes, including session routing, workspace and execution `cwd`, prompt/timeline state, and standard resource or attachment semantics. If ACP provides the value or event, implementations must not replace it with Gateway snapshots, transcript inference, local configuration, or a parallel projection. A bypass is permitted only when upstream ACP has no equivalent; it must be narrow, bounded, session- and generation-scoped, and documented with its rationale, source, limits, reconciliation behavior, and removal condition in a relevant Harness reference or rule.
ACP replay is the primary history authority. OpenClaw's native ACP adapter may reconstruct persisted transcript `toolCall` and `toolResult` records as standard `tool_call` and `tool_call_update` events when its structured event ledger is unavailable; ClawX consumes those events normally and does not perform that reconstruction itself. The only approved ClawX transcript-derived content supplements are best-effort recovery of asynchronous image-generation completions with proven `image_generate` context and recovery of explicit line-leading assistant OpenClaw `MEDIA:` attachment directives omitted by ACP. The general attachment exception does not require image-generation context, but it recovers only attachment references. When ACP replay for a cron session is completely empty, scheduled-task prompt and completion summaries may instead come from Main's typed cron-history host API. This cron exception must be anchored by Gateway `cron.runs` (with a Main-owned legacy file fallback), be generation-scoped and in memory, and never replace or duplicate non-empty ACP replay. When an anchored run summary carries OpenClaw's bounded-summary ellipsis, Main may recover that run's final assistant text from the identified run transcript only when it is longer and shares the complete persisted summary prefix; missing, mismatched, or unbounded summaries remain unchanged. A separate metadata-only supplement may annotate an ACP-replayed assistant turn with whole-turn duration because ACP `session/load` omits the original event timestamps; it cannot create turns or content. These exceptions remain marked and in memory; do not generalize them to bare paths, surrounding transcript prose, arbitrary ordinary messages, tool cards, plans, permissions, thoughts, file activity, or any parallel persisted history.
Historical transcript reads are limited to the newest `1000` message records. A successful live prompt reads content immediately and retries exactly once after `1500 ms`. General attachment and timing alignment treat history as a suffix and match the binary-free OpenClaw prompt-text projection of structured ACP user blocks by duplicate occurrence from the tail; they must not parse or globally remove user-authored resource marker text. Attachment-only empty projections remain eligible, and live content alignment also requires the current optimistic user identity. Every asynchronous result must retain the same active session, generation, supplement operation and attempt, and live turn where applicable. Unmatched, ambiguous, superseded, or stale work cannot mutate the timeline or timing annotations.
@@ -0,0 +1,14 @@
---
id: acp-compatibility-content-safety
title: ACP Compatibility Content Safety
type: ai-coding-rule
appliesTo:
- acp-chat-experience
- gateway-backend-communication
---
Standard ACP content is authoritative and preferred. A compatibility supplement is allowed only when it is explicitly marked by source, retained in memory, backed by approved structured runtime evidence or explicit assistant transcript evidence, and accompanied by reason-coded diagnostics. Compatibility data must never be represented as a native ACP event.
Approved transcript evidence has three bounded forms: asynchronous image-generation completion with proven image-generation context, including explicit internal-UI `message` tool source replies; canonical persisted assistant `__openclaw.media` facts; and general attachment recovery from whole-line, line-leading assistant OpenClaw `MEDIA:` directives outside fenced code blocks. Canonical facts and directives accept only the documented local path, `file:`, execution-cwd-relative, HTTP, and HTTPS forms. Quoted directive references may contain spaces, while unquoted directives may not; canonical structured values may contain spaces. General recovery projects only ordered attachment references and declared media metadata, never surrounding transcript prose. A trusted image-generation source reply may provide user-facing completion or failure text. Reject malformed or wrapped directives, bare or inline prose paths without canonical media facts, unknown URI schemes, incidental tool paths, and unrelated assistant prose.
Compatibility logic must not reconstruct ordinary assistant messages, thoughts, tools, plans, permissions, file activity, or a parallel Chat history. User-side OpenClaw prompt projection may be reconstructed only from structured ACP content already present in the same timeline; generated-looking user prose is not evidence and must not be stripped or parsed. Unmatched or ambiguous evidence is skipped rather than attached by guesswork. Deduplication is turn-scoped and uses only a Main-authorized opaque identity; native ACP resource content wins over equivalent compatibility evidence, generated-image evidence remains inline, and an unavailable result does not block a later available upgrade.
@@ -15,4 +15,8 @@ Rules:
- allowlists and entries must agree about which package owns a single-owner capability
- disabling a bundled plugin is required when removing it from an allowlist is not sufficient to stop runtime loading
- stale plugin registrations for unconfigured capabilities must be removed during sanitize or recovery paths
- ClawX must include `web_search` in both `tools.deny` and `gateway.tools.deny`; existing deny entries remain user-owned and browser automation plus `web_fetch` remain available
- ClawX must include `gateway`, `nodes`, `create_goal`, `get_goal`, and `update_goal` in both deny lists without blocking application-owned Gateway RPCs; it must not implicitly deny messaging, session orchestration, or agent discovery tools
- when no embedding credentials or user-owned memory-search config exist, preserve `memory_search` through OpenClaw's explicit FTS-only provider instead of disabling the tool
- migrations may replace only the exact legacy ClawX-managed memory-search default, must run at most once, and must preserve later user opt-outs
- tests for config rewrites should assert the final active config, not only intermediate helper output
@@ -0,0 +1,22 @@
---
id: attachment-access-safety
title: Attachment Access Safety
type: ai-coding-rule
appliesTo:
- acp-chat-experience
- gateway-backend-communication
---
Treat every Renderer attachment URI, metadata field, staging id, transcript id, source reference, and selected handler id as untrusted. A successful ACP load or creation establishes the Main-owned session, generation, workspace, and execution cwd used to resolve references. Main MUST validate every resolve, scoped read, list, selected-handler open, reveal, and local/remote open against the exact active session key and generation. Attachment refs, ids, opaque identities, handler ids, prior resolves, list results, and cache entries MUST NOT act as bearer capabilities, and later requests MUST NOT provide or replace the execution cwd.
Allow local targets only when an accepted absolute, home-relative, `file:`, or execution-cwd-relative reference resolves to an existing regular file or directory. Directories MUST be identified explicitly by Main, use `application/x-directory` with zero display size, and remain limited to click-initiated system open; they MUST NOT enter scoped reads, Preview, Open With discovery/selection, reveal-as-file, outgoing media, or content enumeration. Local paths are not restricted to the active workspace or managed media roots; workspace/media/staging scope is classification metadata, not a containment grant. A staging id MUST match its Main-owned record, including the exact canonical path for a selected directory. Outgoing media URLs additionally require exact attachment, URL-session, record-session, optional message-id, and managed original-file binding. Reject traversal, NUL, unknown/unsafe schemes, remote file authorities, credentials, malformed or over-4096-character references, and unauthorized outgoing records. Sanitize labels, expose only opaque identities, re-resolve before every operation, and perform final file-handle and generation checks for scoped reads.
Attachment previews MUST use attachment-scoped reads and MUST NOT fall back to naked-path or general workspace APIs. Handler list, selected-handler open, and reveal MUST remain typed attachment-scoped `files` operations routed through `src/lib/host-api.ts`; components MUST NOT add direct IPC, Gateway HTTP, raw-path shell calls, or transport switching. Each operation MUST independently resolve the original ref and active session/generation. Selected-handler open MUST perform a fresh uncached icon-free operating-system enumeration, require exact current handler membership, then re-resolve the original ref and recheck generation immediately before native invocation. It MUST reject association-key changes. A stable handler id is selection metadata, not authority. Renderer MUST NOT provide or receive a canonical path, executable/application/bundle/icon-source path, native Windows identity, association input, helper source, command line/template, or child-process environment addition.
Native adapters MUST keep their source and protocol static. macOS MUST invoke `/usr/bin/osascript -l JavaScript` with the checked-in static JXA program and positional data, use AppKit/Foundation `NSWorkspace` discovery, expose only public bundle ids, perform fresh icon-free membership validation, and invoke `/usr/bin/open -a` only with the freshly selected private bundle path and post-enumeration revalidated file. Windows MUST use the bundled static PowerShell/C# helper and documented `SHAssocEnumHandlers`/`IAssocHandler` COM protocol; it MUST derive public ids as `SHA-256(UTF8("win32\0" + nativeIdentity))`. `prepare-open` MUST receive the initial Main-owned path and 64-hex opaque id separately, enumerate exactly once, retain the matching handler, emit one exact ready record, and accept at most one post-ready invoke line containing only the freshly revalidated same-association path. Registry command parsing, dynamic helper/source interpolation, second action-time enumeration inside the retained-helper protocol, and invocation before revalidation are forbidden.
Helper and metadata bounds are mandatory: handler names at most 256 UTF-16 code units, native ids/handler inputs at most 512, native paths at most 4096, icon PNG data URLs at most 64 KiB, process lifetime five seconds, aggregate/`execFile` output at most 1 MiB, and the Windows post-ready input at most one 8192-character line. Child processes MUST use explicit executable/argument arrays, `shell: false`, and a minimal allowlisted Main-owned environment. macOS icon data MUST pass base64 and PNG-signature validation; Windows icons MUST come only from validated private paths. One invalid record or icon MUST degrade independently.
Linux handler listing MUST authorize the attachment and return the Successful Empty Result On Linux (`ok: true`, platform `linux`, empty handlers) without starting discovery; application-specific open MUST remain unsupported and reveal MUST remain attachment-scoped. Main MAY cache only normalized discovery metadata/icons/private list records for five minutes by platform and association key, with at most 128 entries. That cache is presentation-only and MUST NOT cache authorization or satisfy action-time membership validation. Normalization MUST deduplicate enumerated ids and place enumerated default rows first. Current code does not synthesize a separately reported default row; any such insertion is a guarded follow-up requiring validated metadata and unchanged fresh-membership/invocation safety.
Application discovery, helper output, metadata, and icon failures MUST be silent and isolated: omit invalid handlers, use the generic icon for one bad icon, preserve reveal, and never disable primary preview. Only failed user-selected open/reveal actions may show localized non-blocking errors. Logs/traces MUST NOT contain canonical file paths, native identities, application/bundle/icon-source paths, helper source/output, command lines, or icon data; optional traces may use only opaque attachment identity and bounded allowlisted fields. `src/pages/Chat/AcpFileCard.tsx` may share presentation and menu lifecycle with workspace file activity, but attachment and workspace reference/authorization models MUST remain distinct. See the authoritative architecture and validation map in `harness/reference/acp-attachment-access-control.md`.

Some files were not shown because too many files have changed in this diff Show More