mirror of
https://github.com/ValueCell-ai/ClawX.git
synced 2026-08-14 08:53:09 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
32a4fbf525 | ||
|
|
db82834c1c | ||
|
|
b780c46be3 | ||
|
|
b99b136c2a | ||
|
|
d4060c6dcc | ||
|
|
df53de94df | ||
|
|
d5168842de | ||
|
|
68705d96de | ||
|
|
d4c8ae5f77 | ||
|
|
e23d3e1723 | ||
|
|
0909120b03 | ||
|
|
46ff98c219 | ||
|
|
813746f5cc | ||
|
|
c4346a4b02 | ||
|
|
a9088496f5 | ||
|
|
1875dac040 | ||
|
|
3f2cd9345f | ||
|
|
bbbf6d5bb8 | ||
|
|
6dd39e8f7c | ||
|
|
d5ac6ca5e5 | ||
|
|
cdf75da7ce | ||
|
|
8508c0cd8c | ||
|
|
164489da97 | ||
|
|
f7e025cb20 | ||
|
|
b564d4a57a | ||
|
|
0f152e022b | ||
|
|
8335ca329c | ||
|
|
d0dfe84463 | ||
|
|
2679dc7aee | ||
|
|
76f22a0e8e | ||
|
|
9591deba7e | ||
|
|
04f57b286e | ||
|
|
2a4426d4ff | ||
|
|
82b7f445af | ||
|
|
230ac15cbf | ||
|
|
3a241cf09f | ||
|
|
863f9caf0f | ||
|
|
017749b169 | ||
|
|
4318fdc3f1 | ||
|
|
960f6b298d | ||
|
|
8034c5ad31 | ||
|
|
1f26cd205d |
@@ -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
|
||||
|
||||
@@ -83,7 +118,7 @@ jobs:
|
||||
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
|
||||
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
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -87,3 +87,4 @@ resources/openclaw-plugins/skillshub/
|
||||
|
||||
.opencode
|
||||
.superpowers
|
||||
.playwright-mcp
|
||||
@@ -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.
|
||||
|
||||
+99
-355
@@ -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,138 +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 設定に依存します。
|
||||
セッション側欄はワークスペース優先で整理され、既定ワークスペースを先頭に固定し、その他のワークスペースは自然順に並べます。各ワークスペースは折りたたみや追加読み込みができます。AI の返信中は行にスピナーが表示され、未確認の返信が完了すると青い点に変わり、会話を開くと相対アクティビティ時刻に戻ります。ホバーすると引き続き操作ボタンが表示されます。インポートしたワークスペースは側欄の見出しから名前を変更でき、新しい名前はチャット入力欄の下にも反映されます。見出しにホバーすると引き続きファイルシステムのパスを確認できます。選択中の会話に有効なワークスペースがある場合、新しいチャットはそれを引き継ぎ、最初の送信までは変更できます。編集可能な新規または未バインドのチャットでは、コンポーザーのワークスペースチップから最近使用したワークスペースと既存セッションのワークスペースの一覧を開き、既定ワークスペースへ戻すか別フォルダーを選べます。保存済みのワークスペースフォルダーが移動または削除されている場合、Chat はセッション作成を一時停止し、無効なパスを繰り返し再試行せずに既存のフォルダーを選ぶよう案内します。利用できない既定以外のグループには側欄で印が付き、確認後に削除できます。この操作ではグループ内の全セッションが完全に削除されます。OpenClaw が生成する UUID と日付のフォールバックタイトルは、そのセッション ID と一致する場合に限って欠落タイトルとして扱い、セッション名として保存せず、会話の最初のユーザーメッセージに置き換えて表示します。
|
||||
各 Agent は `provider/model` の実行時設定を個別に上書きできます。上書きしていない Agent は引き続きグローバルの既定モデルを継承します。
|
||||
|
||||
Chat の右パネルにあるワークスペースとプレビューの各タブでは、`.docx` と `.pptx` ファイルを読み取り専用でプレビューできます。従来形式の `.doc` と `.ppt` はアプリ内ではプレビューせず、引き続き OS 経由で開きます。DOCX のページ区切りは Microsoft Word と異なる場合があり、PPTX プレビューではアニメーション、画面切り替え、メディア再生をサポートしません。20 MB を超える Office ファイルはアプリ内でプレビューされません。
|
||||
|
||||
### シングルページ Web ブラウザ
|
||||
Chat の右パネルには、ワークスペース、プレビュー、変更、ウェブブラウザの 4 タブがあります。ウェブブラウザは初回利用時に 1 つのライブページを遅延作成し、パネルを閉じる、別のパネルタブを選ぶ、チャットセッションを切り替える、または ClawX の別ルートへ移動しても、ページを非表示にするだけで実行を継続します。そのため、非表示中もスクリプト、ネットワーク通信、音声、リソース消費が続く場合があります。専用の永続セッションはアプリ再起動後も Cookie とサイトストレージを保持しますが、起動ごとに `about:blank` から始まり、以前の URL、ページ状態、ナビゲーション履歴は復元しません。ページが favicon を提供する場合はタイトルの左側に表示され、favicon がない間は同じサイズのプレースホルダーでタイトル位置を維持します。アドレス編集中はアイコン領域全体が非表示になります。追加のブラウザタブやウィンドウ、ブックマーク、履歴の永続化、パスワードマネージャー、自動入力管理はありません。
|
||||
|
||||
トップレベルナビゲーションでは HTTP、HTTPS、および明示的に入力した標準 `file:///` URL を利用できます。通常のファイルシステムパスとその他のプロトコルは拒否されます。ローカルファイルを開くと、通常の Chromium セキュリティ規則の範囲で、読み取り可能な内容が埋め込みページに公開されます。また、`file:` URL に **システムブラウザで開く**を使うと、ブラウザではなく OS の関連付け済みアプリが起動する場合があります。許可されたポップアップ先は子ウィンドウを作らず現在のページを置き換えます。この同一ページへのフォールバックでは、`window.opener`、返されたウィンドウハンドル、空白ページを後から書き換えるスクリプト型ポップアップ、POST 本文や referrer、名前付きウィンドウ、ウィンドウ機能の完全な動作を維持できません。
|
||||
|
||||
ダウンロードには Electron と OS の既定動作がそのまま使われます。プラットフォームによってはネイティブの保存ダイアログが表示され、ユーザー操作が必要です。ClawX はカスタム保存先を指定せず、ダウンロードの進捗、履歴、管理 UI も提供しません。カメラとマイクはリクエストごとにネイティブの許可/拒否ダイアログを表示し、選択を記憶しません。クリップボードアクセスは許可され、位置情報、画面キャプチャ、通知、その他の権限は拒否されます。
|
||||
|
||||
**Cookie を消去**はブラウザセッション内の全オリジンの Cookie のみを削除し、キャッシュとサイトストレージを保持します。**サイトデータを消去**は全オリジンの HTTP/Chromium キャッシュ、Cache Storage、Local Storage、IndexedDB、Service Worker を削除し、Cookie とダウンロード済みファイルを保持します。ブラウザ通信は Electron/Chromium のシステムプロキシ解決に従います。ClawX クライアントのプロキシ設定はこのブラウザセッションへ同期されず、設定を変更しても再構成されません。
|
||||
|
||||
### 📡 マルチチャネル管理
|
||||
複数のAIチャネルを同時に設定・監視できます。各チャネルは独立して動作するため、異なるタスクに特化したエージェントを実行できます。
|
||||
現在は各チャンネルで複数アカウントを扱え、Channels ページでアカウントの Agent 紐付けやデフォルトアカウント切替を直接管理できます。
|
||||
カスタムのチャンネルアカウント ID には、ルーティング不一致を防ぐため OpenClaw 互換の正規形式(`[a-z0-9_-]`、英小文字、最大 64 文字、先頭は英小文字または数字)を必須にしています。
|
||||
ClawX には Tencent 公式の個人 WeChat チャンネルプラグインも同梱されており、Channels ページからアプリ内 QR フローで直接 WeChat を連携できます。
|
||||
|
||||
### ⏰ Cronベースの自動化
|
||||
AIタスクを自動的に実行するようスケジュール設定できます。トリガーを定義し、間隔を設定することで、手動介入なしにAIエージェントを24時間稼働させることができます。
|
||||
定期タスク画面では外部配信を「送信アカウント」と「受信先ターゲット」の 2 段階セレクターで設定できるようになりました。対応チャネルでは、受信先候補をチャネルのディレクトリ機能や既知セッション履歴から自動検出するため、`jobs.json` を手で編集する必要はありません。タスクのメッセージ入力欄でも、メインのチャット入力と同じインライン `/skill` トークン記法でスキルを挿入できるようになりました(選択中のエージェントに応じて読み込み)。スケジュールされたプロンプトから直接スキルを起動できます。スケジュール選択は**繰り返し**と**1回のみ**のタブに分かれました。繰り返しは毎時・毎日・平日・毎週・カスタム(生の cron)の頻度を時刻/曜日コントロール付きで選べ、1回のみは選択した日付(曜日を表示)と時刻に一度だけ実行します。1回のみのタスクは未来の時刻を指定する必要があり、実行後はランタイムにより自動的に削除されます。
|
||||
|
||||
|
||||
### 🧩 拡張可能なスキルシステム
|
||||
事前構築されたスキルでAIエージェントを拡張できます。統合 Skills ページはローカル優先で、管理ディレクトリや workspace のスキルをスキャンし、Gateway に依存せず有効/無効を切り替えられます。エンタープライズ拡張がある場合は、その拡張が提供する marketplace も表示できます。
|
||||
ClawX はドキュメント処理スキル(`pdf`、`xlsx`、`docx`、`pptx`)もフル内容で同梱し、起動時に管理スキルディレクトリ(既定 `~/.openclaw/skills`)へ自動配備し、初回インストール時に既定で有効化します。
|
||||
Skills ページでは OpenClaw の複数ソース(管理ディレクトリ、workspace、追加スキルディレクトリ)から検出されたスキルを表示でき、各スキルの実際のパスを確認して実フォルダを直接開けます。OpenClaw 同梱の bundled skill については、コミュニティ版ではパッケージにも表示にも `skill-creator` のみを残し、dev 起動時と packaged 起動時の両方で他の bundled skill を物理的に削除します。さらに、削除済み bundled skill の古い `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 Provider のまま継続できます。
|
||||
OpenAI-compatible ゲートウェイを **Custom プロバイダー** で使う場合、**設定 → AI Providers → Provider 編集** でカスタム `User-Agent` を設定でき、互換性が必要なエンドポイントで有効です。
|
||||
プロバイダーの編集や切り替え時、ClawX は `input: ["text", "image"]` など既存のモデル単位の能力メタデータを保持します。新しく選択した Custom プロバイダーのモデルには OpenClaw onboarding と同等の画像入力推論を適用し、不明なモデルはテキスト専用として扱います。
|
||||
Custom プロバイダーのモデル行には明示的な `contextWindow` も書き込まれ(モデルファミリーから推定、例:`gpt-5.x` → 272k)、旧バージョンで保存された行は起動時に自動補完されます。これにより OpenClaw は長いセッションを "Context overflow" エラーになる前に圧縮できます。compaction 未設定の場合は `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 は起動時に新しいバージョンを自動確認できます。更新が見つかるとアプリ内通知を表示し、ダウンロードやインストールはユーザーが選択した後にのみ実行されます。
|
||||
|
||||
---
|
||||
- **🤖 パーソナルAIアシスタント**:質問への回答、メールの下書き、ドキュメントの要約、日常タスクの支援を行う汎用AIエージェントを、クリーンなデスクトップインターフェースから設定できます。
|
||||
- **📊 自動モニタリング**:ニュースフィード、価格、特定のイベントを監視するスケジュールエージェントを設定し、結果を希望する通知チャネルへ届けられます。
|
||||
- **💻 開発者の生産性向上**:AIを開発ワークフローに統合し、コードレビュー、ドキュメント生成、繰り返しのコーディング作業を行えます。
|
||||
- **🔄 ワークフロー自動化**:複数のスキルをビジュアルな自動化パイプラインに組み合わせ、データ処理、コンテンツ変換、アクションの実行を行えます。
|
||||
|
||||
## はじめに
|
||||
|
||||
### システム要件
|
||||
|
||||
- **オペレーティングシステム**: macOS 11以上、Windows 10以上、またはLinux(Ubuntu 20.04以上)
|
||||
- **メモリ**: 最低4GB RAM(8GB推奨)
|
||||
- **ストレージ**: 1GBの空きディスク容量
|
||||
- **オペレーティングシステム**:macOS 11以上、Windows 10以上、またはLinux(Ubuntu 20.04以上)
|
||||
- **メモリ**:最低4GB RAM(8GB推奨)
|
||||
- **ストレージ**:1GBの空きディスク容量
|
||||
|
||||
### インストール
|
||||
|
||||
#### ビルド済みリリース(推奨)
|
||||
|
||||
[Releases](https://github.com/ValueCell-ai/ClawX/releases)ページから、お使いのプラットフォーム向けの最新リリースをダウンロードしてください。
|
||||
[Releases](https://github.com/ValueCell-ai/ClawX/releases) ページから、お使いのプラットフォーム向けの最新リリースをダウンロードしてください。
|
||||
|
||||
#### ソースからビルド
|
||||
|
||||
@@ -177,321 +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を管理します。
|
||||
|
||||
Chat は Electron Main が所有する ACP stdio bridge を使用します。Renderer は型付き host event を受け取り、メモリ上の ACP timeline を描画します。Gateway は providers、models、skills、workspace、settings、diagnostics、media configuration などの非 Chat 機能を引き続き担当します。
|
||||
- **プロセスモデル**:Electron Mainがウィンドウ、Gateway監視、システム統合、更新を管理します。OpenClaw GatewayはAIオーケストレーション、チャネル、スキル機能を提供し、Rendererはローカルエンドポイントへ直接アクセスしません。
|
||||
- **設定の配信**:Gateway実行中は `config.get` / `config.set` を使い、停止中または起動中は解決済みJSON5設定を更新します。通常のプロバイダー、Agent、スキル、モデル変更ではプロセスを置き換えず、認証情報は `secrets.reload` でホットリロードされます。ハートビートが4回連続で失敗した場合は、ライフサイクルで保護された復旧を要求します。
|
||||
- **ACP Chat**:Chat UIは [ACP(Agent Client Protocol)](https://agentclientprotocol.com) を介してOpenClawとやり取りし、頻繁に反復されるOpenClawの前に比較的安定したチャットプロトコル面を確保します。ACPはMainが所有するstdio bridge経由で動作し、設定リロード後の認証済み履歴リプレイ、ページ移動中のストリーミング、Mainが検証したメディア・添付ファイル・ファイルアクティビティに対応します。保護されたGateway再起動によって受理済みターンが中断された場合、パッチ済みOpenClawランタイムは復旧runを元のACP promptへ明示的に関連付け、後続のテキストとツールアクティビティを同じメモリ内ターンで継続します。その後の履歴リプレイでも、永続化されたツール境界をネイティブACP updateとして復元します。
|
||||
- **設計原則**:フロントエンドの単一入口、Mainによるトランスポート管理、再接続・タイムアウト・バックオフによるグレースフルリカバリ、安全なストレージ、CORSセーフな境界を採用しています。
|
||||
|
||||
別の会話やページを開いても、未完了の ACP 応答はストリーミングを継続します。完了前に戻ると最新のメモリ内 timeline が復元され、ライブ応答の表示が続きます。完了後は通常の ACP 履歴リプレイが引き続き唯一の正となります。
|
||||
|
||||
ACP の assistant ターンにはターン全体の所要時間が表示されます。ライブ計時はクライアントが観測した prompt ライフサイクルに従い、アプリ内を移動しても継続します。履歴の所要時間は Electron Main が範囲を限定した OpenClaw transcript のタイムスタンプから算出し、ACP リプレイですでに復元されたターンだけに付与します。
|
||||
|
||||
ACP Chat は標準 ACP resource を添付ファイルとして表示します。ユーザーが選択した画像は、ホバー時のオーバーレイにファイル名を表示するサムネイルとして描画され、その他の利用可能な添付カードはファイル名に続いて、淡色で省略可能なソースパスを表示します。現在の OpenClaw ACP adapter が assistant のメディアを省略した場合も、明示的な assistant の `MEDIA:` ディレクティブを、元のディレクティブを表示せずに添付カードとして復元できます。現在の workspace 外を含む既存のローカルファイル参照は、プレビューまたはオープンのたびに Electron Main で正確な session と generation に対して再検証されます。AI が生成したプレビュー可能なローカル添付ファイル(20 MB 以下の `.docx` と `.pptx` を含む)は、読み取り専用のアプリ内プレビューを主要操作として維持し、対応アプリで開く操作と Finder、エクスプローラー、またはシステムのファイルマネージャーで表示する操作を副次メニューから利用できます。ローカル HTML 添付ファイルでは、そのメニューの先頭項目がファイル URL を右側のウェブブラウザで開きます。ここでも Office プレビューには同じ制限があります。`.doc` と `.ppt` はシステムアプリで開く形式のままで、DOCX のページ区切りは Microsoft Word と異なる場合があり、PPTX のアニメーション、画面切り替え、メディア再生はサポートされません。対応アプリの検出は macOS と Windows のみで利用でき、Linux または検出失敗時には通知せず、ファイルの場所を表示する操作だけに切り替わります。それ以外のローカルファイル(20 MB を超える Office ファイルを含む)はユーザーのクリック後にシステムアプリで開かれます。リモートの HTTP/HTTPS 添付ファイルはクリック後に外部で開かれます。通常の文章内にある単独またはインラインのパスは添付ファイルとして扱われません。
|
||||
|
||||
ACP Chat は、runtime が画像生成メディアを信頼できる構造化メディアとして配信した場合に、生成画像のプレビューも表示できます。信頼できる OpenClaw internal-UI 配信と画像生成タスクに関連付けられた最終返信では、テキストのみの失敗説明を含む元のユーザー向け完了テキストを保持し、汎用の画像キャプションへ置き換えません。OpenClaw の履歴リプレイ中は、同じセッションで画像生成タスク開始が記録されている場合に限り、assistant の画像 `MEDIA:` マーカーがインライン画像表示へ昇格されます。ClawX は Renderer から任意にファイルシステムへアクセスするのではなく、Electron Main のホストメディア処理を通じてプレビューを読み込みます。標準 ACP の画像と resource コンテンツは引き続き推奨パスであり、そのまま描画されます。
|
||||
|
||||
### ACP ファイルアクティビティのセマンティクス
|
||||
|
||||
- ファイルアクティビティは、成功して完了した OpenClaw の `write`、`edit`、`apply_patch` 呼び出しから投影されます。ツールの認識方法は公式 OpenClaw Chat UI に準拠し、完了した呼び出しだけに絞る処理は ClawX 固有です。
|
||||
- 作成・変更されたアクティビティ行は、プレビュー可能な assistant 添付ファイルと同じファイルカードと**アプリで開く**メニューを使い、状態表示と利用可能な `+/-` 集計も保持します。HTML ファイルでは、メニューの先頭項目がローカルファイル URL を右側の**ウェブブラウザ**で開き、そのタブを有効にします。削除された行には **Changes** 操作だけを残します。アプリ一覧、選択アプリで開く操作、ファイル位置の表示は、workspace ルートと相対パスから Electron Main が毎回個別に再検証します。ツール由来のパスが添付ファイルに変換されたり、Renderer に正規化済みのネイティブパスが渡されたりすることはありません。
|
||||
- `write` はツールが宣言したとおり、作成および全行追加の差分として表示されます。対象パスがすでに存在する可能性がある場合も同様です。
|
||||
- **Changes** は、ツールが宣言したアクティビティを時系列に並べたセッション単位の記録です。Git の出力でも、検証済みソースベースラインに対する差分でもありません。
|
||||
- 各ファイルについて、Changes はアシスタントの各ターンに最大 1 つの diff エディターを表示します。安全に連結できるフラグメントは合成し、独立したフラグメントは 1 つのエディターに連結しますが、完全なファイルベースラインとの差分であるとはみなしません。
|
||||
- シェルコマンド、スクリプト、ユーザー、IDE による副作用は検出されません。
|
||||
- 完全な ACP リプレイからは記録済みのファイルアクティビティを復元できます。リプレイが不完全な場合、ClawX はフォールバック推論で欠落したアクティビティを補いません。
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────┐
|
||||
│ 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エージェントランタイムとオーケストレーション │
|
||||
│ • メッセージチャネル管理 │
|
||||
│ • スキル/プラグイン実行環境 │
|
||||
│ • プロバイダー抽象化レイヤー │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
### 設計原則
|
||||
|
||||
- **プロセス分離**: AIランタイムは別プロセスで動作し、重い計算処理中でもUIの応答性を確保します
|
||||
- **フロントエンド呼び出しの単一入口**: Renderer は host-api/api-client を通じて呼び出し、下位プロトコルに依存しません
|
||||
- **Mainによるトランスポート制御**: ACP Chat stdio bridge と Gateway トランスポートは 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.19以上(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` が自動的に適切なバリアントを選択します。
|
||||
- **Node.js**:対応するメジャー系列の22.22.3以上、24.15.0以上、または25.9.0以上(Node 24 LTS推奨)
|
||||
- **パッケージマネージャー**:pnpm 9以上(npmも対応)
|
||||
- **Linux(Ubuntu/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 イベント、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 |
|
||||
|
||||
---
|
||||
> プロジェクト構成、完全なコマンド一覧、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>
|
||||
|
||||
@@ -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,124 +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 experience—no 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.
|
||||
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 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 available, a new chat inherits the selected conversation's workspace while remaining editable until first send. Editable new or unbound chats expose the composer workspace chip as a small menu that lists recent and known-session workspaces, returns to the default workspace, or chooses another folder. If a saved workspace folder was moved or deleted, Chat pauses session creation and prompts 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. 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 also 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 `.docx` and `.pptx` files. 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.
|
||||
|
||||
### Single-Page Web Browser
|
||||
The Chat right panel has four tabs: Workspace, Preview, Changes, and Web Browser. Web Browser lazily creates one live page and keeps it running when you close the panel, select another panel tab, switch chat sessions, or visit another ClawX route; hidden pages may continue scripts, network activity, audio, and resource use. Its dedicated persistent session retains cookies and site storage across app restarts, but every new app run starts at `about:blank` without restoring the previous URL, page state, or navigation history. When a page provides a favicon, it appears beside the title; a same-size placeholder keeps the title aligned while no favicon is available, and the icon slot is hidden while editing the address. There are no additional browser tabs or windows, bookmarks, persisted history, password manager, or autofill management.
|
||||
|
||||
Top-level navigation accepts HTTP, HTTPS, and explicitly entered standard `file:///` URLs. Plain filesystem paths and other protocols are rejected. Opening a local file exposes its readable content to the embedded page under normal Chromium security rules, and using **Open in System Browser** for a `file:` URL may launch the OS-associated application instead of a browser. Allowed popup targets replace the current page rather than creating a child window; this same-page fallback cannot preserve `window.opener`, returned window handles, initially blank scripted popups, or full POST-body, referrer, named-window, and window-feature behavior.
|
||||
|
||||
Downloads keep Electron and the operating system defaults. Depending on the platform, this may present a native Save dialog and require user interaction; ClawX does not choose a custom path or provide download progress, history, or management UI. Camera and microphone access uses a native Allow/Deny prompt for every request and is never remembered. Clipboard access is allowed, while geolocation, display capture, notifications, and other permissions are denied.
|
||||
|
||||
**Clear Cookies** removes cookies for every origin in the browser session while preserving cache and site storage. **Clear Site Data** removes HTTP/Chromium cache, Cache Storage, Local Storage, IndexedDB, and Service Workers for every origin while preserving cookies and downloaded files. Browser traffic follows Electron/Chromium system-proxy resolution; ClawX client proxy settings are not synchronized to this browser session, and changing them does not reconfigure it.
|
||||
|
||||
### 📡 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. The task message field also 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/weekday controls, while Once runs the task a single time at a chosen date (with 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/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.
|
||||
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.
|
||||
|
||||
### 🔐 Secure Provider Integration
|
||||
Connect to multiple AI providers (OpenAI, Anthropic, Z.AI / GLM, 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.
|
||||
Custom-provider model rows also receive an explicit `contextWindow` (inferred from the model family, e.g. `gpt-5.x` → 272k), and rows saved by older versions are backfilled on startup, so OpenClaw can compact long sessions before they fail with "Context overflow" errors. When you have no compaction config, ClawX seeds `agents.defaults.compaction.mode = "safeguard"` and `reserveTokensFloor = 50000`; rows or configs you authored yourself are never modified (except a missing `reserveTokensFloor` may be backfilled).
|
||||
Z.AI (CN / Global) maps to OpenClaw's built-in `zai` provider (`ZAI_API_KEY`). 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-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
|
||||
|
||||
@@ -183,277 +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.
|
||||
|
||||
Chat uses an ACP stdio bridge owned by Electron Main. Renderer receives typed host events and renders an in-memory ACP timeline. Gateway remains responsible for non-Chat capabilities such as providers, models, skills, workspace, settings, diagnostics, and media configuration.
|
||||
- **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.
|
||||
|
||||
An unfinished ACP response keeps 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, explicit assistant `MEDIA:` directives can also be recovered as attachment cards without displaying the raw directive. 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 URL in the right-side Web Browser. 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; remote HTTP and HTTPS attachments open externally after a user click. Bare or inline prose paths 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 local file URL in the right-side Web Browser and activates that 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 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 & 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 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 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 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.19+ (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, ACP Chat bridge 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 translations—every 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
|
||||
|
||||
@@ -470,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
|
||||
|
||||
@@ -492,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
-343
@@ -1,148 +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`; агенты без переопределения продолжают наследовать глобальную модель по умолчанию.
|
||||
|
||||
### Одностраничный веб-браузер
|
||||
На правой панели Chat находятся четыре вкладки: «Рабочая область», «Просмотр», «Изменения» и «Веб-браузер». При первом использовании веб-браузер лениво создаёт одну активную страницу и не останавливает её при закрытии панели, выборе другой вкладки панели, переключении сессии чата или переходе на другой маршрут ClawX; скрытая страница может продолжать выполнять скрипты, обращаться к сети, воспроизводить звук и расходовать ресурсы. Выделенная постоянная сессия сохраняет cookie и хранилища сайтов после перезапуска приложения, но каждый новый запуск начинается с `about:blank` без восстановления предыдущего URL, состояния страницы или истории переходов. Если страница предоставляет favicon, он отображается рядом с заголовком; пока favicon недоступен, заполнитель того же размера сохраняет положение заголовка, а при редактировании адреса вся область значка скрывается. Дополнительных вкладок или окон браузера, закладок, сохраняемой истории, менеджера паролей и управления автозаполнением нет.
|
||||
|
||||
Навигация верхнего уровня принимает HTTP, HTTPS и явно введённые стандартные URL `file:///`. Обычные пути файловой системы и другие протоколы отклоняются. Открытие локального файла предоставляет встроенной странице доступ к его читаемому содержимому в рамках обычных правил безопасности Chromium; команда **Открыть в системном браузере** для URL `file:` может запустить связанное с файлом приложение ОС, а не браузер. Разрешённая цель всплывающего окна заменяет текущую страницу, а не создаёт дочернее окно. Такой переход в той же странице не сохраняет `window.opener`, возвращаемые дескрипторы окон, сценарии с первоначально пустым окном, а также полную семантику тела POST, referrer, именованных окон и параметров окна.
|
||||
|
||||
Для загрузок сохраняется стандартное поведение Electron и операционной системы. В зависимости от платформы может появиться нативный диалог сохранения, требующий действий пользователя; ClawX не задаёт собственный путь и не предоставляет интерфейс прогресса, истории или управления загрузками. Для каждого запроса камеры или микрофона показывается нативный диалог разрешения или запрета, а решение не запоминается. Доступ к буферу обмена разрешён; геолокация, захват экрана, уведомления и остальные разрешения отклоняются.
|
||||
|
||||
**Очистить файлы cookie** удаляет только cookie всех источников в сессии браузера, сохраняя кэш и хранилища сайтов. **Очистить данные сайта** удаляет HTTP/Chromium-кэш, Cache Storage, Local Storage, IndexedDB и Service Workers всех источников, сохраняя cookie и загруженные файлы. Трафик браузера использует системное разрешение прокси Electron/Chromium; настройки клиентского прокси ClawX не синхронизируются с этой сессией браузера, и их изменение не перенастраивает её.
|
||||
|
||||
### 📡 Управление несколькими каналами
|
||||
Настраивайте и отслеживайте несколько AI-каналов одновременно. Каждый канал работает независимо, позволяя запускать специализированных агентов для разных задач.
|
||||
Каждый канал теперь поддерживает несколько учётных записей, привязку агента к учётной записи и переключение канала по умолчанию прямо на странице Каналы.
|
||||
Для пользовательских идентификаторов учётных записей каналов ClawX требует совместимый с OpenClaw канонический формат (`[a-z0-9_-]`, строчные буквы, максимум 64 символа, должен начинаться с буквы или цифры) для предотвращения ошибок маршрутизации.
|
||||
ClawX также включает официальный плагин личного WeChat от Tencent, позволяя подключить WeChat напрямую со страницы Каналы через встроенный QR-код.
|
||||
|
||||
### ⏰ Автоматизация по расписанию
|
||||
Планируйте автоматический запуск AI-задач. Определяйте триггеры, устанавливайте интервалы и позволяйте AI-агентам работать круглосуточно без ручного вмешательства.
|
||||
На странице Cron теперь можно настроить внешнюю доставку непосредственно в форме задачи с отдельными селекторами учётной записи отправителя и цели получателя. Для поддерживаемых каналов цели получателей автоматически обнаруживаются из каталогов каналов или известной истории сессий, поэтому больше не нужно редактировать `jobs.json` вручную. Поле сообщения задачи также поддерживает вставку навыков с помощью того же синтаксиса встроенных токенов `/skill`, что и в основном окне чата (с учётом выбранного агента), поэтому запланированные подсказки могут запускать навыки напрямую. Выбор расписания разделён на вкладки **Повтор** и **Однократно**: повтор предлагает частоты «Ежечасно», «Ежедневно», «По будням», «Еженедельно» и «Свой» (произвольный cron) со встроенными элементами выбора времени/дня недели, а однократно запускает задачу один раз в выбранную дату (с показом дня недели) и время. Однократные задачи должны быть запланированы на будущее и автоматически удаляются средой выполнения после завершения.
|
||||
|
||||
### 🧩 Расширяемая система навыков
|
||||
Расширяйте возможности AI-агентов готовыми навыками. Просматривайте, устанавливайте и управляйте навыками через встроенную панель — менеджеры пакетов не нужны.
|
||||
ClawX также предварительно упаковывает полные навыки обработки документов (`pdf`, `xlsx`, `docx`, `pptx`), автоматически развёртывает их в управляемый каталог навыков (по умолчанию `~/.openclaw/skills`) при запуске и включает по умолчанию при первой установке.
|
||||
На странице Навыки отображаются навыки из нескольких источников OpenClaw (управляемый каталог, workspace и дополнительные каталоги навыков), а также показывается фактическое расположение каждого навыка для прямого открытия папки.
|
||||
|
||||
### 🔐 Безопасная интеграция провайдеров
|
||||
Подключайтесь к нескольким AI-провайдерам (OpenAI, Anthropic, Z.AI / GLM и др.) с учётными данными, безопасно хранящимися в системной связке ключей. OpenAI поддерживает как API-ключи, так и OAuth через браузер (подписка Codex).
|
||||
Для провайдеров **Custom**, используемых с OpenAI-совместимыми шлюзами, вы можете установить пользовательский `User-Agent` в **Настройки → AI Провайдеры → Редактировать провайдера** для совместимости с чувствительными эндпоинтами.
|
||||
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 взаимоисключающие, так как используют один и тот же runtime-ключ OpenClaw.
|
||||
Когда совместимый шлюз отклоняет `/models` по причинам, не связанным с аутентификацией, ClawX автоматически переключается на легковесный зонд `/chat/completions` или `/responses` при проверке API-ключа.
|
||||
|
||||
### 🌙 Адаптивные темы
|
||||
Светлая тема, тёмная тема или синхронизация с системой. ClawX автоматически адаптируется к вашим предпочтениям.
|
||||
|
||||
### 🚀 Управление автозапуском
|
||||
В **Настройки → Общие** вы можете включить **Запускать при старте системы**, чтобы ClawX автоматически запускался после входа в систему.
|
||||
|
||||
---
|
||||
- **🤖 Персональный AI-ассистент**: Настройте универсального AI-агента для ответов на вопросы, составления писем, резюмирования документов и помощи с повседневными задачами через чистый десктопный интерфейс.
|
||||
- **📊 Автоматизированный мониторинг**: Планируйте агентов для отслеживания новостных лент, цен или определённых событий и доставляйте результаты в предпочитаемый канал уведомлений.
|
||||
- **💻 Производительность разработчика**: Интегрируйте AI в рабочий процесс разработки для проверки кода, генерации документации и автоматизации повторяющихся задач.
|
||||
- **🔄 Автоматизация рабочих процессов**: Объединяйте несколько навыков в визуальные конвейеры, которые обрабатывают данные, преобразуют контент и запускают действия.
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
@@ -174,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.19+ (рекомендуется 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
|
||||
|
||||
### Руководящие принципы
|
||||
@@ -432,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
-318
@@ -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,74 +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 配置。
|
||||
会话侧边栏现在以工作空间优先组织:默认工作空间固定在最上方,其它工作空间按自然顺序排列,每个工作空间都可折叠或继续加载更多会话。AI 回复期间,会话行显示加载指示器;未查看的回复完成后显示蓝点;打开会话后恢复显示相对活跃时间,悬停时仍会露出操作按钮。导入的工作空间可从侧边栏标题处重命名,新名称会同步显示在对话输入框下方,同时悬浮标题仍可查看文件系统路径。如果当前所选会话存在有效工作空间,新对话会继承该工作空间,并在首次发送前保持可编辑。对于可编辑的新对话或未绑定对话,输入框的工作空间卡片会打开一个小菜单,列出最近使用及现有会话中的工作空间,并可切回默认工作空间或选择其它目录。如果保存的工作空间文件夹已被移动或删除,Chat 会暂停创建会话并提示选择现有文件夹,而不会持续重试失效路径。不可用的非默认工作空间会在侧边栏显示标记,并可在确认后删除;该操作会永久删除分组中的全部会话。OpenClaw 生成的 UUID 加日期兜底标题只有在与该会话 ID 匹配时才会被视为缺失标题,随后改用会话的首条用户消息展示,而不会被持久化为会话名称。
|
||||
每个 Agent 还可以单独覆盖自己的 `provider/model` 运行时设置;未覆盖的 Agent 会继续继承全局默认模型。
|
||||
|
||||
Chat 右侧面板的工作空间和预览选项卡支持以只读方式预览 `.docx` 和 `.pptx` 文件。旧版 `.doc` 和 `.ppt` 文件不会在应用内预览,而是继续通过操作系统打开。DOCX 的分页效果可能与 Microsoft Word 不同;PPTX 预览不支持动画、切换效果或媒体播放。超过 20 MB 的 Office 文件不会在应用内预览。
|
||||
|
||||
### 单页面 Web 浏览器
|
||||
Chat 右侧面板包含四个选项卡:工作空间、预览、变更和网页浏览器。网页浏览器会在首次使用时延迟创建一个实时页面;关闭面板、切换面板选项卡、切换聊天会话或前往 ClawX 的其它路由时,页面只会隐藏并继续运行,因此脚本、网络活动、音频和资源占用都可能持续。专用持久会话会在应用重启后保留 Cookie 和站点存储,但每次启动都从 `about:blank` 开始,不恢复上次的 URL、页面状态或导航历史。页面提供网站图标时,图标会显示在标题左侧;没有图标时,同尺寸占位图标会保持标题对齐,编辑地址时则隐藏整个图标位。该功能不提供额外浏览器标签页或窗口、书签、持久化历史、密码管理器或自动填充管理。
|
||||
|
||||
顶层导航支持 HTTP、HTTPS 和明确输入的标准 `file:///` URL;普通文件系统路径及其它协议会被拒绝。打开本地文件会在 Chromium 的常规安全规则下向嵌入页面暴露其中可读取的内容;对 `file:` URL 使用**在系统浏览器中打开**时,操作系统也可能改用文件关联应用,而不是浏览器。允许的弹窗目标会替换当前页面,不会创建子窗口;这种同页面回退无法保留 `window.opener`、返回的窗口句柄、先打开空白页再写入内容的脚本弹窗,也不能完整保持 POST 请求体、referrer、命名窗口和窗口特性行为。
|
||||
|
||||
下载完全沿用 Electron 和操作系统的默认行为。根据平台不同,系统可能显示原生“保存”对话框并需要用户操作;ClawX 不会指定自定义路径,也不提供下载进度、历史或管理界面。摄像头和麦克风权限会对每次请求显示原生“允许/拒绝”提示,且不会记住选择。剪贴板访问允许使用;地理位置、屏幕捕获、通知及其它权限均会被拒绝。
|
||||
|
||||
**清除 Cookie**会删除浏览器会话中所有来源的 Cookie,同时保留缓存和站点存储。**清除网站数据**会删除所有来源的 HTTP/Chromium 缓存、Cache Storage、Local Storage、IndexedDB 和 Service Worker,同时保留 Cookie 与已下载文件。浏览器流量使用 Electron/Chromium 的系统代理解析;ClawX 客户端代理设置不会同步到该浏览器会话,修改这些设置也不会重新配置它。
|
||||
|
||||
### 📡 多频道管理
|
||||
同时配置和监控多个 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 与浏览器 OAuth(Codex 订阅)登录。
|
||||
在开发者模式下,独立的“图像生成”页面支持配置 OpenAI 兼容生图端点(Base URL、API Key 和模型名,例如 `gpt-image-2`),生图请求会走专用的 `/v1/images/generations` 服务,聊天仍继续使用正常的 OpenAI Provider。
|
||||
如果你通过 **自定义(Custom)Provider** 对接 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 可以在启动时自动检查新版本。发现更新后会显示应用内提示;只有在你选择操作后,才会下载或安装更新。
|
||||
|
||||
---
|
||||
- **🤖 个人 AI 助手**:配置一个通用 AI 智能体,可以回答问题、撰写邮件、总结文档并协助处理日常任务——全部通过简洁的桌面界面完成。
|
||||
- **📊 自动化监控**:设置定时智能体来监控新闻动态、追踪价格变动或监听特定事件,结果将推送到你偏好的通知渠道。
|
||||
- **💻 开发者效率工具**:将 AI 融入你的开发工作流,使用智能体进行代码审查、生成文档或自动化重复性编码任务。
|
||||
- **🔄 工作流自动化**:将多个技能串联起来,创建复杂的自动化流水线——处理数据、转换内容、触发操作,全部通过可视化方式编排。
|
||||
|
||||
## 快速上手
|
||||
|
||||
@@ -171,7 +108,7 @@ ClawX 可以在启动时自动检查新版本。发现更新后会显示应用
|
||||
|
||||
从 [Releases](https://github.com/ValueCell-ai/ClawX/releases) 页面下载适用于你平台的最新版本。
|
||||
|
||||
#### 从源码构建
|
||||
#### 从源码开始
|
||||
|
||||
```bash
|
||||
# 克隆仓库
|
||||
@@ -193,10 +130,10 @@ pnpm dev
|
||||
3. **技能包** – 选择适用于常见场景的预配置技能
|
||||
4. **验证** – 在进入主界面前测试你的配置
|
||||
|
||||
如果系统语言在支持列表中,向导会默认选中该语言;否则回退到英文。
|
||||
|
||||
> Moonshot(Kimi)说明: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 发现工具仍然可用。
|
||||
|
||||
### 代理设置
|
||||
|
||||
@@ -204,231 +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。
|
||||
- 如果启用了 Telegram,ClawX 还会把代理同步到 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 主进程统一管理。
|
||||
|
||||
Chat 使用由 Electron Main 持有的 ACP stdio bridge。Renderer 接收类型化 host events,并渲染内存中的 ACP timeline。Gateway 仍负责 providers、models、skills、workspace、settings、diagnostics 和 media configuration 等非 Chat 能力。
|
||||
- **进程模型**: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 安全。
|
||||
|
||||
打开其它会话或页面时,尚未完成的 ACP 回复仍会继续流式接收。若在回复完成前返回,ClawX 会恢复最新的内存 timeline 并继续显示实时输出;回复完成后,普通 ACP 历史回放仍是唯一事实来源。
|
||||
|
||||
ACP assistant 回合会显示整轮耗时。Live 计时跟随客户端观测到的 prompt 生命周期,并在应用内导航后保持连续;历史耗时由 Electron Main 根据有界的 OpenClaw transcript 时间戳计算,而且只能标注 ACP 回放已经恢复出的回合。
|
||||
|
||||
ACP Chat 会将标准 ACP resource 渲染为附件。用户选择的图片会显示为缩略图,并在悬停蒙层中显示文件名;其它可用的附件卡片会显示文件名,以及灰色、可截断的来源路径。当前 OpenClaw ACP adapter 遗漏 assistant 媒体时,显式的 assistant `MEDIA:` 指令也可恢复为附件卡片,且不会显示原始指令。现有本地文件引用(包括当前 workspace 外的路径)在每次预览或打开前,都会由 Electron Main 按精确的 session 和 generation 重新验证。AI 生成且可预览的本地附件(包括不超过 20 MB 的 `.docx` 和 `.pptx` 文件)会保留主要的只读应用内预览操作,并提供次级菜单,可通过兼容应用打开,或在 Finder、文件资源管理器或系统文件管理器中显示。对于本地 HTML 附件,该菜单第一项会在右侧网页浏览器中打开文件 URL。Office 预览在此处也有相同限制:`.doc` 和 `.ppt` 仍通过系统应用打开,DOCX 的分页效果可能与 Microsoft Word 不同,PPTX 的动画、切换效果和媒体播放不受支持。兼容应用发现仅在 macOS 和 Windows 上可用;在 Linux 上或发现失败时,会静默降级为仅显示文件位置。其它本地文件(包括超过 20 MB 的 Office 文件)会在用户点击后通过系统应用打开;远程 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 文件,菜单第一项会在右侧**网页浏览器**中打开本地文件 URL 并激活该选项卡;已删除的活动行只保留 **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、Dreams 或频道失败会显示为能力降级,而不是全局 Gateway 故障。
|
||||
- 可用以下命令确认监听进程:
|
||||
- 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/zh-CN/architecture.md](docs/zh-CN/architecture.md)。
|
||||
|
||||
## 开发指南
|
||||
|
||||
### 前置要求
|
||||
|
||||
- **Node.js**:22.19+(推荐 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` 会自动选择正确版本。
|
||||
- **Node.js**:22.22.3+ / 24.15.0+(推荐) / 25.9.0+
|
||||
- **包管理器**:pnpm 9+
|
||||
- **Linux(Ubuntu/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 事件、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 |
|
||||
|
||||
---
|
||||
> 项目结构、技术栈、完整命令列表、E2E 并行策略、性能诊断与通信回归检查等细节,请参阅 [docs/zh-CN/development.md](docs/zh-CN/development.md)。
|
||||
|
||||
## 参与贡献
|
||||
|
||||
@@ -437,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
|
||||
|
||||
### 贡献规范
|
||||
|
||||
@@ -449,7 +198,6 @@ CI 中的 `comms-regression` 会校验必选场景与阈值。
|
||||
- 按需更新文档
|
||||
- 保持提交原子化且描述清晰
|
||||
|
||||
---
|
||||
|
||||
## 致谢
|
||||
|
||||
@@ -461,7 +209,6 @@ ClawX 构建于以下优秀的开源项目之上:
|
||||
- [shadcn/ui](https://ui.shadcn.com/) – 精美设计的组件库
|
||||
- [Zustand](https://github.com/pmndrs/zustand) – 轻量级状态管理
|
||||
|
||||
---
|
||||
|
||||
## 社区
|
||||
|
||||
@@ -475,13 +222,10 @@ ClawX 构建于以下优秀的开源项目之上:
|
||||
|
||||
我们正在启动 ClawX 合作伙伴计划,寻找能够帮助我们将 ClawX 介绍给更多客户的合作伙伴,尤其是那些有定制化 AI 智能体或自动化需求的客户。
|
||||
|
||||
合作伙伴负责帮助我们连接潜在用户和项目,ClawX 团队则提供完整的技术支持、定制开发与集成服务。
|
||||
|
||||
如果你服务的客户对 AI 工具或自动化方案感兴趣,欢迎与我们合作。
|
||||
合作伙伴负责帮助我们连接潜在用户和项目,ClawX 团队则提供完整的技术支持、定制开发与集成服务。如果你服务的客户对 AI 工具或自动化方案感兴趣,欢迎与我们合作。
|
||||
|
||||
欢迎私信我们,或发送邮件至 [public@valuecell.ai](mailto:public@valuecell.ai) 了解更多。
|
||||
|
||||
---
|
||||
|
||||
## Stars 历史
|
||||
|
||||
@@ -489,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>
|
||||
|
||||
@@ -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.
|
||||
@@ -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 |
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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`
|
||||
- Windows(PowerShell):`Get-NetTCPConnection -LocalPort 18789 -State Listen`
|
||||
- ウィンドウの閉じるボタン(`X`)はClawXをトレイに隠すだけで、完全終了ではありません。完全終了にはトレイメニューの **Quit ClawX** を使用してください。
|
||||
@@ -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 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 |
|
||||
@@ -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.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は起動時に新しいバージョンを確認します。更新が利用可能になるとアプリ内プロンプトを表示し、選択した場合にのみダウンロードとインストールを実行します。
|
||||
@@ -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`エントリーポイント経由で実行され、ターミナル入力の安定性を保ちます。
|
||||
@@ -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** в меню трея.
|
||||
@@ -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 |
|
||||
@@ -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 проверяет наличие новых версий при запуске. Если обновление доступно, приложение показывает запрос; скачивание и установка выполняются только после вашего выбора.
|
||||
@@ -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`, чтобы сохранить стабильное поведение ввода в терминале.
|
||||
@@ -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`
|
||||
- Windows(PowerShell):`Get-NetTCPConnection -LocalPort 18789 -State Listen`
|
||||
- 点击窗口关闭按钮(`X`)默认只是最小化到托盘,并不会完全退出应用。请在托盘菜单中选择 **Quit ClawX** 执行完整退出。
|
||||
@@ -0,0 +1,107 @@
|
||||
# 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` 会自动选择正确版本。
|
||||
|
||||
### 项目结构
|
||||
|
||||
```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 |
|
||||
@@ -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 与浏览器 OAuth(Codex 订阅)登录。
|
||||
在开发者模式下,独立的“图像生成”页面支持配置 OpenAI 兼容生图端点(Base URL、API Key 和模型名,例如 `gpt-image-2`),生图请求会走专用的 `/v1/images/generations` 服务,聊天仍继续使用正常的 OpenAI Provider。
|
||||
如果你通过 **自定义(Custom)Provider** 对接 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 可以在启动时自动检查新版本。发现更新后会显示应用内提示;只有在你选择操作后,才会下载或安装更新。
|
||||
@@ -0,0 +1,12 @@
|
||||
# ClawX 代理设置
|
||||
|
||||
本文档是 README「代理设置」一节的详细说明。
|
||||
|
||||
- 只填写 `host:port` 时,会按 HTTP 代理处理。
|
||||
- 高级代理项留空时,会自动回退到“代理服务器”。
|
||||
- 保存代理设置后,Electron 网络层会立即重新应用代理,并自动重启 Gateway。
|
||||
- 如果启用了 Telegram,ClawX 还会把代理同步到 OpenClaw 的 Telegram 频道配置中。
|
||||
- 当 ClawX 代理处于关闭状态时,Gateway 的常规重启会保留已有的 Telegram 频道代理配置。
|
||||
- 如果你要明确清空 OpenClaw 中的 Telegram 代理,请在关闭代理后点一次“保存代理设置”。
|
||||
- 在 **设置 → 高级 → 开发者** 中,可以直接运行 **OpenClaw Doctor**,执行 `openclaw doctor --json` 并在应用内查看诊断输出。
|
||||
- 在 Windows 打包版本中,内置的 `openclaw` CLI/TUI 会通过随包分发的 `node.exe` 入口运行,以保证终端输入行为稳定。
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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, repairTrustedOfficialPluginInstallRecords, syncTrustedOfficialPluginInstallRecord, resolvePluginNpmPackagePath } 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 {
|
||||
@@ -119,7 +124,7 @@ function cleanupStaleBuiltInExtensions(): void {
|
||||
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);
|
||||
}
|
||||
@@ -191,10 +196,9 @@ 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);
|
||||
syncTrustedOfficialPluginInstallRecord(dirName, targetDir);
|
||||
} catch (err) {
|
||||
logger.warn(`[plugin] Failed to ${isInstalled ? 'auto-upgrade' : 'install'} ${channelType} plugin:`, err);
|
||||
succeeded = false;
|
||||
@@ -203,7 +207,6 @@ function ensureConfiguredPluginsUpgraded(configuredChannels: string[]): boolean
|
||||
// Same version already installed — still patch manifest ID in case it was
|
||||
// never corrected (e.g. installed before MANIFEST_ID_FIXES included this plugin).
|
||||
fixupPluginManifest(targetDir);
|
||||
syncTrustedOfficialPluginInstallRecord(dirName, targetDir);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -217,7 +220,6 @@ function ensureConfiguredPluginsUpgraded(configuredChannels: string[]): boolean
|
||||
// Skip only if installed AND same version — but still patch manifest ID.
|
||||
if (isInstalled && installedVersion && sourceVersion === installedVersion) {
|
||||
fixupPluginManifest(targetDir);
|
||||
syncTrustedOfficialPluginInstallRecord(dirName, targetDir);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -227,7 +229,6 @@ function ensureConfiguredPluginsUpgraded(configuredChannels: string[]): boolean
|
||||
mkdirSync(fsPath(join(homedir(), '.openclaw', 'extensions')), { recursive: true });
|
||||
copyPluginFromNodeModules(npmPkgPath, targetDir, npmName);
|
||||
fixupPluginManifest(targetDir);
|
||||
syncTrustedOfficialPluginInstallRecord(dirName, targetDir);
|
||||
} catch (err) {
|
||||
logger.warn(`[plugin] Failed to ${isInstalled ? 'auto-upgrade' : 'install'} ${channelType} plugin from node_modules:`, err);
|
||||
succeeded = false;
|
||||
@@ -257,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;
|
||||
@@ -266,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;
|
||||
@@ -526,7 +539,10 @@ export async function syncGatewayConfigBeforeLaunch(
|
||||
// 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.
|
||||
measureSync(timingsMs, 'trustedPluginInstallSyncMs', repairTrustedOfficialPluginInstallRecords);
|
||||
await measureAsync(timingsMs, 'trustedPluginInstallSyncMs', async () => {
|
||||
await cleanupUnconfiguredChannelPluginInstallRecords(configuredChannels);
|
||||
await repairTrustedOfficialPluginInstallRecords();
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn('Failed to auto-upgrade plugins:', err);
|
||||
}
|
||||
@@ -625,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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
+74
-201
@@ -24,7 +24,9 @@ import {
|
||||
type GatewayLifecycleState,
|
||||
getReconnectScheduleDecision,
|
||||
getReconnectSkipReason,
|
||||
isOpenClawFatalConfigExitCode,
|
||||
} from './process-policy';
|
||||
import { removeOpenClaw2026_7_1UpgradeSnapshot } from '../utils/openclaw-upgrade-snapshot';
|
||||
import {
|
||||
clearPendingGatewayRequests,
|
||||
rejectPendingGatewayRequest,
|
||||
@@ -48,11 +50,6 @@ import { GatewayLifecycleController, LifecycleSupersededError } from './lifecycl
|
||||
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,
|
||||
GATEWAY_STARTUP_SLOW_STAGE_MS,
|
||||
@@ -61,6 +58,11 @@ import {
|
||||
recordGatewayStartupStderrLine,
|
||||
} from './startup-stderr';
|
||||
import { runGatewayStartupSequence } from './startup-orchestrator';
|
||||
import {
|
||||
hasFatalRuntimeFailureSignal,
|
||||
hasInvalidConfigFailureSignal,
|
||||
hasStartupMigrationLockSignal,
|
||||
} from './startup-recovery';
|
||||
import {
|
||||
GatewayCapabilityMonitor,
|
||||
type GatewayCapabilityName,
|
||||
@@ -188,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;
|
||||
@@ -246,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);
|
||||
@@ -334,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();
|
||||
@@ -417,12 +411,28 @@ 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();
|
||||
@@ -462,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();
|
||||
}
|
||||
@@ -668,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
|
||||
*/
|
||||
@@ -810,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 {
|
||||
@@ -868,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({
|
||||
@@ -1022,7 +909,6 @@ export class GatewayManager extends EventEmitter {
|
||||
}
|
||||
|
||||
private recordGatewayAlive(): void {
|
||||
this.clearInitialReadyHeartbeatRecoveryTimer();
|
||||
this.diagnostics.lastAliveAt = Date.now();
|
||||
this.diagnostics.consecutiveHeartbeatMisses = 0;
|
||||
}
|
||||
@@ -1121,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: () => {
|
||||
@@ -1181,6 +1074,11 @@ export class GatewayManager extends EventEmitter {
|
||||
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
|
||||
@@ -1262,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({
|
||||
@@ -1286,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);
|
||||
});
|
||||
@@ -1303,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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
+2
-16
@@ -5,6 +5,7 @@
|
||||
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';
|
||||
@@ -67,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.
|
||||
@@ -604,6 +589,7 @@ if (gotTheLock) {
|
||||
}
|
||||
|
||||
gatewayManager = new GatewayManager();
|
||||
registerOpenClawConfigCoordinator(gatewayManager);
|
||||
clawHubService = new ClawHubService();
|
||||
|
||||
// Register builtin extensions and load manifest
|
||||
|
||||
@@ -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';
|
||||
@@ -78,8 +75,6 @@ import {
|
||||
} from './ipc/request-helpers';
|
||||
import { createMenu } from './menu';
|
||||
|
||||
const gatewayRpcBackpressure = new GatewayRpcBackpressure();
|
||||
|
||||
/**
|
||||
* Register all IPC handlers
|
||||
*/
|
||||
@@ -167,7 +162,7 @@ function registerTypedHostHandlers(
|
||||
updates: createUpdatesApi(appUpdater),
|
||||
uv: createUvApi(),
|
||||
settings: createSettingsApi(gatewayManager),
|
||||
gateway: createGatewayApi(gatewayManager, gatewayRpcBackpressure),
|
||||
gateway: createGatewayApi(gatewayManager),
|
||||
logs: createLogsApi(),
|
||||
channels: createChannelsApi({ gatewayManager, mainWindow }),
|
||||
agents: createAgentsApi({ gatewayManager }),
|
||||
@@ -298,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) {
|
||||
@@ -317,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) };
|
||||
@@ -345,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) };
|
||||
@@ -395,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) {
|
||||
@@ -429,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) {
|
||||
@@ -451,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 };
|
||||
@@ -724,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)}`);
|
||||
@@ -818,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');
|
||||
@@ -856,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) {
|
||||
@@ -882,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) {
|
||||
@@ -908,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) {
|
||||
@@ -961,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) {
|
||||
@@ -996,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) {
|
||||
@@ -1027,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) {
|
||||
|
||||
@@ -3,11 +3,19 @@ import {
|
||||
WEB_BROWSER_INITIAL_URL,
|
||||
WEB_BROWSER_PARTITION,
|
||||
WEB_BROWSER_USER_AGENT,
|
||||
normalizeWebBrowserTopLevelUrl,
|
||||
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;
|
||||
@@ -67,7 +75,7 @@ export function isExpectedWebBrowserAttachment(
|
||||
return params.partition === WEB_BROWSER_PARTITION
|
||||
&& params.src === WEB_BROWSER_INITIAL_URL
|
||||
&& params.useragent === WEB_BROWSER_USER_AGENT
|
||||
&& params.allowpopups === true
|
||||
&& params.allowpopups !== true
|
||||
&& params.preload === '';
|
||||
}
|
||||
|
||||
@@ -135,48 +143,70 @@ export function installWebBrowserGuestPolicy(
|
||||
}
|
||||
|
||||
guest.setUserAgent(WEB_BROWSER_USER_AGENT);
|
||||
let committedHtmlUrl = normalizeWebBrowserHtmlFileUrl(guest.getURL());
|
||||
let restoringCommittedUrl = false;
|
||||
|
||||
const rejectDisallowedNavigation = (
|
||||
details: Electron.Event<Electron.WebContentsWillNavigateEventParams>,
|
||||
const blockPageNavigation = (
|
||||
details: Electron.Event<Electron.WebContentsWillFrameNavigateEventParams>,
|
||||
): void => {
|
||||
if (!details.isMainFrame || normalizeWebBrowserTopLevelUrl(details.url) !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.warn(`[WebBrowser] Blocked top-level navigation to ${details.url}`);
|
||||
logger.warn(`[WebBrowser] Blocked guest navigation to ${details.url}`);
|
||||
details.preventDefault();
|
||||
};
|
||||
|
||||
const rejectDisallowedRedirect = (
|
||||
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 => {
|
||||
if (!details.isMainFrame || normalizeWebBrowserTopLevelUrl(details.url) !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.warn(`[WebBrowser] Blocked top-level redirect to ${details.url}`);
|
||||
logger.warn(`[WebBrowser] Blocked guest redirect to ${details.url}`);
|
||||
details.preventDefault();
|
||||
};
|
||||
|
||||
// Same-tab fallback cannot preserve window.opener, returned window handles, or full POST/referrer fidelity.
|
||||
guest.setWindowOpenHandler(({ url }) => {
|
||||
const target = normalizeWebBrowserTopLevelUrl(url);
|
||||
if (!target || !registry.owns(guest)) {
|
||||
logger.warn(`[WebBrowser] Blocked popup target ${url}`);
|
||||
return DENY_WINDOW_OPEN;
|
||||
}
|
||||
|
||||
try {
|
||||
void guest.loadURL(target).catch((error) => {
|
||||
logger.warn(`[WebBrowser] Failed to load popup target ${target}:`, error);
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn(`[WebBrowser] Failed to load popup target ${target}:`, error);
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -184,8 +214,12 @@ export function installWebBrowserGuestPolicy(
|
||||
}
|
||||
cleaned = true;
|
||||
|
||||
guest.off('will-navigate', rejectDisallowedNavigation);
|
||||
guest.off('will-redirect', rejectDisallowedRedirect);
|
||||
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);
|
||||
@@ -195,8 +229,12 @@ export function installWebBrowserGuestPolicy(
|
||||
}
|
||||
};
|
||||
|
||||
guest.on('will-navigate', rejectDisallowedNavigation);
|
||||
guest.on('will-redirect', rejectDisallowedRedirect);
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -1,140 +1,56 @@
|
||||
import {
|
||||
dialog,
|
||||
session,
|
||||
type BrowserWindow,
|
||||
type MessageBoxOptions,
|
||||
type MessageBoxReturnValue,
|
||||
type Session,
|
||||
} from 'electron';
|
||||
import { WEB_BROWSER_PERMISSION_LABELS } from '@shared/i18n/resources';
|
||||
import { resolveSupportedLanguage } from '@shared/language';
|
||||
import {
|
||||
WEB_BROWSER_PARTITION,
|
||||
WEB_BROWSER_USER_AGENT,
|
||||
normalizeWebBrowserHtmlFileUrl,
|
||||
} from '@shared/web-browser';
|
||||
import { logger } from '../utils/logger';
|
||||
import { getSetting } from '../utils/store';
|
||||
import type { WebBrowserGuestRegistry } from './web-browser-policy';
|
||||
|
||||
const CLIPBOARD_PERMISSIONS = new Set([
|
||||
'clipboard-read',
|
||||
'clipboard-sanitized-write',
|
||||
'deprecated-sync-clipboard-read',
|
||||
]);
|
||||
const DOWNLOAD_OBSERVED_SESSIONS = new WeakSet<Session>();
|
||||
|
||||
export interface ConfigureWebBrowserSessionOptions {
|
||||
registry: WebBrowserGuestRegistry;
|
||||
getMainWindow: () => BrowserWindow | null;
|
||||
getLanguage?: () => Promise<string | undefined>;
|
||||
showMessageBox?: (
|
||||
window: BrowserWindow,
|
||||
options: MessageBoxOptions,
|
||||
) => Promise<MessageBoxReturnValue>;
|
||||
}
|
||||
|
||||
export function configureWebBrowserSession(
|
||||
options: ConfigureWebBrowserSessionOptions,
|
||||
_options: ConfigureWebBrowserSessionOptions,
|
||||
): Session {
|
||||
const browserSession = session.fromPartition(WEB_BROWSER_PARTITION, { cache: true });
|
||||
const getLanguage = options.getLanguage ?? (() => getSetting('language'));
|
||||
// Resolve the method at request time so Electron E2E tests can replace the native dialog after startup.
|
||||
const showMessageBox = options.showMessageBox
|
||||
?? ((window, messageOptions) => dialog.showMessageBox(window, messageOptions));
|
||||
|
||||
// The macOS UA is fixed on every platform for stable website compatibility and deterministic requests.
|
||||
// Keep a deterministic identity even though this session may load only local HTML.
|
||||
browserSession.setUserAgent(WEB_BROWSER_USER_AGENT);
|
||||
|
||||
browserSession.setPermissionCheckHandler((_contents, permission) => (
|
||||
CLIPBOARD_PERMISSIONS.has(permission)
|
||||
));
|
||||
|
||||
browserSession.setPermissionRequestHandler((contents, permission, callback, details) => {
|
||||
let callbackCalled = false;
|
||||
const respond = (allowed: boolean): void => {
|
||||
if (callbackCalled) return;
|
||||
callbackCalled = true;
|
||||
callback(allowed);
|
||||
};
|
||||
|
||||
if (CLIPBOARD_PERMISSIONS.has(permission)) {
|
||||
respond(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (permission === 'geolocation') {
|
||||
// ClawX has no location service, so websites cannot receive a meaningful location.
|
||||
respond(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (permission !== 'media' || !options.registry.owns(contents)) {
|
||||
respond(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const mediaDetails = details as Electron.MediaAccessPermissionRequest;
|
||||
const mediaTypes = new Set(mediaDetails.mediaTypes ?? []);
|
||||
const requestsCamera = mediaTypes.has('video');
|
||||
const requestsMicrophone = mediaTypes.has('audio');
|
||||
if (!requestsCamera && !requestsMicrophone) {
|
||||
respond(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const mainWindow = options.getMainWindow();
|
||||
if (!mainWindow) {
|
||||
respond(false);
|
||||
return;
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const language = resolveSupportedLanguage(await getLanguage());
|
||||
const labels = WEB_BROWSER_PERMISSION_LABELS[language];
|
||||
const capability = requestsCamera && requestsMicrophone
|
||||
? labels.cameraAndMicrophone
|
||||
: requestsCamera
|
||||
? labels.camera
|
||||
: labels.microphone;
|
||||
const origin = mediaDetails.securityOrigin || mediaDetails.requestingUrl;
|
||||
|
||||
if (!options.registry.owns(contents)) {
|
||||
respond(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await showMessageBox(mainWindow, {
|
||||
type: 'question',
|
||||
title: labels.title,
|
||||
message: labels.message
|
||||
.replace('{{origin}}', origin)
|
||||
.replace('{{capability}}', capability),
|
||||
buttons: [labels.allow, labels.deny],
|
||||
defaultId: 0,
|
||||
cancelId: 1,
|
||||
noLink: true,
|
||||
});
|
||||
respond(result.response === 0 && options.registry.owns(contents));
|
||||
} catch (error) {
|
||||
logger.warn('[WebBrowser] Native media permission dialog failed:', error);
|
||||
respond(false);
|
||||
}
|
||||
})();
|
||||
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);
|
||||
// Preserve Electron's default save location and UI by observing without cancelling or setting a path.
|
||||
browserSession.on('will-download', (_event, item) => {
|
||||
item.once('done', (_doneEvent, state) => {
|
||||
if (state === 'interrupted') {
|
||||
logger.warn('[WebBrowser] Download interrupted');
|
||||
}
|
||||
});
|
||||
browserSession.on('will-download', (event) => {
|
||||
event.preventDefault();
|
||||
});
|
||||
}
|
||||
|
||||
// This isolated browser Session intentionally does not mirror client proxy settings or recycle connections.
|
||||
return browserSession;
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ 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 = {
|
||||
@@ -393,11 +394,16 @@ export class AcpChatService {
|
||||
this.historicalGeneration = null;
|
||||
}
|
||||
this.permissionsEnabled = true;
|
||||
const messageId = payload.messageId ?? randomUUID();
|
||||
const isSlashCommand = payload.message?.trimStart().startsWith('/') === true;
|
||||
await connection.prompt({
|
||||
sessionId: acpSessionId,
|
||||
prompt,
|
||||
messageId: payload.messageId ?? randomUUID(),
|
||||
_meta: { sessionKey: payload.sessionKey, prefixCwd: true },
|
||||
// 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,
|
||||
@@ -489,7 +495,7 @@ export class AcpChatService {
|
||||
}
|
||||
|
||||
private async initializeConnectionOnce(attempt: number): Promise<AcpConnection> {
|
||||
if (!this.connection) this.connection = this.spawnConnection();
|
||||
if (!this.connection) this.connection = await this.spawnConnection();
|
||||
const connection = this.connection;
|
||||
const child = this.child;
|
||||
|
||||
@@ -544,9 +550,15 @@ export class AcpChatService {
|
||||
});
|
||||
}
|
||||
|
||||
private spawnConnection(): ClientSideConnection {
|
||||
private async spawnConnection(): Promise<ClientSideConnection> {
|
||||
const gatewayToken = await getSetting('gatewayToken');
|
||||
const spec = getOpenClawEmbeddedForkSpec(['acp']);
|
||||
const forked = fork(spec.modulePath, spec.args, spec.options);
|
||||
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');
|
||||
|
||||
@@ -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,29 +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);
|
||||
}
|
||||
// Agent model changes must be picked up by the running Gateway before
|
||||
// the next send; otherwise the UI can show the new selection while the
|
||||
// active runtime still answers with the previous model.
|
||||
scheduleGatewayReload(ctx, 'update-agent-model');
|
||||
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);
|
||||
});
|
||||
@@ -96,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) => {
|
||||
@@ -122,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 };
|
||||
},
|
||||
};
|
||||
|
||||
@@ -48,6 +48,7 @@ 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',
|
||||
@@ -106,6 +107,7 @@ type LocalScope = 'workspace' | 'openclaw-media' | 'staging';
|
||||
|
||||
type ResolvedLocal = {
|
||||
kind: 'local';
|
||||
entryKind: 'file' | 'directory';
|
||||
canonicalPath: string;
|
||||
scope: LocalScope;
|
||||
mimeType: string;
|
||||
@@ -571,13 +573,21 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
}
|
||||
if (!isSamePath(canonicalCandidate, stagedPath)) throw new AttachmentFailure('invalidReference');
|
||||
const stagedStat = await fs.stat(canonicalCandidate);
|
||||
if (!stagedStat.isFile()) throw new AttachmentFailure('notFile');
|
||||
const entryKind = stagedStat.isFile()
|
||||
? 'file'
|
||||
: stagedStat.isDirectory()
|
||||
? 'directory'
|
||||
: null;
|
||||
if (!entryKind) throw new AttachmentFailure('notFile');
|
||||
return {
|
||||
kind: 'local',
|
||||
entryKind,
|
||||
canonicalPath: canonicalCandidate,
|
||||
scope: 'staging',
|
||||
mimeType: mimeTypeHint || mimeTypeForPath(canonicalCandidate),
|
||||
size: stagedStat.size,
|
||||
mimeType: entryKind === 'directory'
|
||||
? DIRECTORY_MIME_TYPE
|
||||
: mimeTypeHint || mimeTypeForPath(canonicalCandidate),
|
||||
size: entryKind === 'directory' ? 0 : stagedStat.size,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -589,7 +599,12 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
throw new AttachmentFailure(attachmentFailure(error));
|
||||
}
|
||||
const targetStat = await fs.stat(canonicalCandidate);
|
||||
if (!targetStat.isFile()) throw new AttachmentFailure('notFile');
|
||||
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)
|
||||
@@ -598,10 +613,13 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
|
||||
return {
|
||||
kind: 'local',
|
||||
entryKind,
|
||||
canonicalPath: canonicalCandidate,
|
||||
scope,
|
||||
mimeType: mimeTypeHint || mimeTypeForPath(canonicalCandidate),
|
||||
size: targetStat.size,
|
||||
mimeType: entryKind === 'directory'
|
||||
? DIRECTORY_MIME_TYPE
|
||||
: mimeTypeHint || mimeTypeForPath(canonicalCandidate),
|
||||
size: entryKind === 'directory' ? 0 : targetStat.size,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -624,6 +642,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
if (!resolved) throw new AttachmentFailure('invalidReference');
|
||||
return {
|
||||
kind: 'local',
|
||||
entryKind: 'file',
|
||||
canonicalPath: resolved.path,
|
||||
scope: 'openclaw-media',
|
||||
mimeType: resolved.mimeType,
|
||||
@@ -687,7 +706,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
...(displayPath ? { displayPath } : {}),
|
||||
mimeType: target.mimeType,
|
||||
size: target.size,
|
||||
target: { kind: 'local', scope: target.scope, ref },
|
||||
target: { kind: 'local', scope: target.scope, entryKind: target.entryKind, ref },
|
||||
};
|
||||
} catch (error) {
|
||||
return { ok: false, displayName, error: attachmentFailure(error) };
|
||||
@@ -699,6 +718,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
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');
|
||||
@@ -730,6 +750,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
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');
|
||||
@@ -801,9 +822,10 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
}
|
||||
};
|
||||
|
||||
const requireCurrentLocalTarget = async (ref: AttachmentFileRef): Promise<ResolvedLocal> => {
|
||||
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');
|
||||
}
|
||||
@@ -814,7 +836,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
ref: AttachmentFileRef,
|
||||
): Promise<AttachmentOpenHandlersResult> => {
|
||||
try {
|
||||
const target = await requireCurrentLocalTarget(ref);
|
||||
const target = await requireCurrentLocalFileTarget(ref);
|
||||
if (dependencies.openWith.platform === 'linux') {
|
||||
return { ok: true, platform: 'linux', handlers: [] };
|
||||
}
|
||||
@@ -841,7 +863,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
payload: OpenAttachmentWithPayload,
|
||||
): Promise<OpenAttachmentResult> => {
|
||||
try {
|
||||
const target = await requireCurrentLocalTarget(payload?.ref);
|
||||
const target = await requireCurrentLocalFileTarget(payload?.ref);
|
||||
if (typeof payload?.handlerId !== 'string'
|
||||
|| !payload.handlerId.trim()
|
||||
|| payload.handlerId.length > HANDLER_ID_MAX_LENGTH) {
|
||||
@@ -850,7 +872,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
await dependencies.openWith.open(
|
||||
target.canonicalPath,
|
||||
payload.handlerId,
|
||||
async () => (await requireCurrentLocalTarget(payload.ref)).canonicalPath,
|
||||
async () => (await requireCurrentLocalFileTarget(payload.ref)).canonicalPath,
|
||||
);
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
@@ -860,8 +882,8 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
|
||||
|
||||
const revealAttachment = async (ref: AttachmentFileRef): Promise<OpenAttachmentResult> => {
|
||||
try {
|
||||
await requireCurrentLocalTarget(ref);
|
||||
const revalidated = await requireCurrentLocalTarget(ref);
|
||||
await requireCurrentLocalFileTarget(ref);
|
||||
const revalidated = await requireCurrentLocalFileTarget(ref);
|
||||
shell.showItemInFolder(revalidated.canonicalPath);
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
|
||||
@@ -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 };
|
||||
},
|
||||
|
||||
@@ -1,45 +1,8 @@
|
||||
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 { createAcpChatService } from './acp-chat-service';
|
||||
import type { AcpSessionAccessRegistry } from './acp-session-access-registry';
|
||||
import { isRecord } from './payload-utils';
|
||||
|
||||
const VISION_MIME_TYPES = new Set([
|
||||
'image/png',
|
||||
'image/jpeg',
|
||||
'image/bmp',
|
||||
'image/webp',
|
||||
]);
|
||||
|
||||
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,
|
||||
@@ -53,75 +16,6 @@ export function createChatApi({
|
||||
const acpChat = createAcpChatService(mainWindow, acpSessionAccessRegistry, gatewayManager);
|
||||
|
||||
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 media: name=${item.fileName}, mimeType=${item.mimeType}, 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: messageLength=${message.length}, attachments=${imageAttachments.length}, fileRefs=${fileReferences.length}`,
|
||||
);
|
||||
const result = await gatewayManager.rpc('chat.send', rpcParams, 120000);
|
||||
const hasRunId = isRecord(result) && typeof result.runId === 'string';
|
||||
logger.info(`[chat:sendWithMedia] RPC result: runId=${hasRunId ? 'present' : 'absent'}`);
|
||||
const response = hasRunId
|
||||
? { runId: result.runId as string }
|
||||
: 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),
|
||||
|
||||
+103
-19
@@ -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(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -569,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),
|
||||
|
||||
@@ -612,12 +612,16 @@ export function createFilesApi(dependencies: FilesApiDependencies = {}): Complet
|
||||
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;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
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 { approvePendingLocalDeviceRequests } from '../utils/control-ui-device-pairing';
|
||||
@@ -12,10 +11,6 @@ type HealthPayload = {
|
||||
probe?: unknown;
|
||||
};
|
||||
|
||||
type ControlUiPayload = {
|
||||
view?: unknown;
|
||||
};
|
||||
|
||||
type RpcPayload = {
|
||||
method?: unknown;
|
||||
params?: unknown;
|
||||
@@ -30,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 () => {
|
||||
@@ -52,13 +44,11 @@ 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 });
|
||||
const url = buildOpenClawControlUiUrl(port, token);
|
||||
void approvePendingLocalDeviceRequests(gatewayManager).catch((error) => {
|
||||
logger.debug(`[gateway] Control UI device auto-approve skipped: ${String(error)}`);
|
||||
});
|
||||
@@ -71,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);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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`).
|
||||
@@ -185,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,
|
||||
@@ -522,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) {
|
||||
@@ -579,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) {
|
||||
@@ -604,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(
|
||||
@@ -626,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) {
|
||||
@@ -742,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;
|
||||
}
|
||||
|
||||
@@ -775,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 (
|
||||
@@ -803,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 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -473,7 +473,7 @@ async function loadSessionSummary(sessionKey: string, workspacePath: string | nu
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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 { normalizeWebBrowserTopLevelUrl } from '../../shared/web-browser';
|
||||
import { normalizeWebBrowserHtmlFileUrl } from '../../shared/web-browser';
|
||||
|
||||
export interface WebBrowserApiDependencies {
|
||||
browserSession: Session;
|
||||
@@ -18,9 +18,9 @@ function requireLiveGuest(registry: WebBrowserGuestRegistry): WebContents {
|
||||
}
|
||||
|
||||
function requireAllowedUrl(url: string): string {
|
||||
const normalizedUrl = normalizeWebBrowserTopLevelUrl(url);
|
||||
const normalizedUrl = normalizeWebBrowserHtmlFileUrl(url);
|
||||
if (!normalizedUrl) {
|
||||
throw new Error('Web browser URL is not allowed');
|
||||
throw new Error('Only local HTML file URLs are allowed');
|
||||
}
|
||||
return normalizedUrl;
|
||||
}
|
||||
@@ -34,7 +34,7 @@ function isAbortedLoad(error: unknown): boolean {
|
||||
export function createWebBrowserApi(
|
||||
dependencies: WebBrowserApiDependencies,
|
||||
): CompleteHostServiceRegistry['webBrowser'] {
|
||||
const { browserSession, registry } = dependencies;
|
||||
const { registry } = dependencies;
|
||||
const openExternal = dependencies.openExternal ?? ((url: string) => shell.openExternal(url));
|
||||
|
||||
return {
|
||||
@@ -48,22 +48,8 @@ export function createWebBrowserApi(
|
||||
}
|
||||
},
|
||||
|
||||
async clearCookies() {
|
||||
await browserSession.clearStorageData({ storages: ['cookies'] });
|
||||
},
|
||||
|
||||
async clearSiteData() {
|
||||
await Promise.all([
|
||||
browserSession.clearCache(),
|
||||
browserSession.clearStorageData({
|
||||
storages: ['cachestorage', 'localstorage', 'indexdb', 'serviceworkers'],
|
||||
}),
|
||||
]);
|
||||
},
|
||||
|
||||
async openExternal() {
|
||||
const guest = requireLiveGuest(registry);
|
||||
await openExternal(requireAllowedUrl(guest.getURL()));
|
||||
async openExternal({ url }) {
|
||||
await openExternal(requireAllowedUrl(url));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,50 +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;
|
||||
};
|
||||
|
||||
/**
|
||||
* Conservative context-window defaults for well-known model families, applied
|
||||
* to custom-provider model rows that would otherwise carry no `contextWindow`.
|
||||
* 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 CUSTOM_MODEL_CONTEXT_WINDOW_RULES: Array<{ pattern: RegExp; contextWindow: number }> = [
|
||||
{ pattern: /\bgpt-5/, contextWindow: 272_000 },
|
||||
{ pattern: /\b(?:gpt-4\.1|gpt-4o|o[134])\b/, contextWindow: 128_000 },
|
||||
{ pattern: /\bclaude\b|\bclaude-/, contextWindow: 200_000 },
|
||||
{ pattern: /\bgemini\b/, contextWindow: 1_048_576 },
|
||||
{ pattern: /\bkimi\b|moonshot/, contextWindow: 256_000 },
|
||||
{ pattern: /minimax/, contextWindow: 204_800 },
|
||||
{ pattern: /\bglm-5(?:\.|\b)/, contextWindow: 1_000_000 },
|
||||
{ pattern: /\bglm-4/, contextWindow: 200_000 },
|
||||
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 },
|
||||
];
|
||||
|
||||
/** Safe floor for unknown custom models: high enough to avoid compaction spam. */
|
||||
export const DEFAULT_CUSTOM_MODEL_CONTEXT_WINDOW = 131_072;
|
||||
/**
|
||||
* 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;
|
||||
|
||||
export function inferCustomModelContextWindow(modelId: string): number {
|
||||
const normalized = modelId.trim().toLowerCase();
|
||||
for (const rule of CUSTOM_MODEL_CONTEXT_WINDOW_RULES) {
|
||||
if (rule.pattern.test(normalized)) return rule.contextWindow;
|
||||
}
|
||||
return DEFAULT_CUSTOM_MODEL_CONTEXT_WINDOW;
|
||||
/**
|
||||
* 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'];
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -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,
|
||||
},
|
||||
],
|
||||
|
||||
+223
-85
@@ -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) {
|
||||
@@ -708,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) {
|
||||
@@ -746,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) => {
|
||||
@@ -829,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 });
|
||||
}
|
||||
|
||||
@@ -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
@@ -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 ───────────────────────────────────────────────────
|
||||
|
||||
+468
-288
File diff suppressed because it is too large
Load Diff
@@ -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) {
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
/**
|
||||
* Memory search default seeding for openclaw.json.
|
||||
*
|
||||
* OpenClaw enables semantic memory search by default with the `openai`
|
||||
* embedding provider, so a user without an OpenAI key gets doctor errors and
|
||||
* a broken memory_search tool. ClawX seeds `agents.defaults.memorySearch =
|
||||
* { enabled: false }` at Gateway prelaunch — but only when the user has no
|
||||
* memorySearch config anywhere (global defaults or per-agent overrides).
|
||||
* Existing user config is never modified.
|
||||
* 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);
|
||||
}
|
||||
@@ -29,18 +30,35 @@ export function hasUserMemorySearchConfig(config: Record<string, unknown>): bool
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed `agents.defaults.memorySearch = { enabled: false }` when the user has
|
||||
* no memorySearch config at all. Mutates `config` in place and returns true
|
||||
* when a change was made. Never touches existing memorySearch objects.
|
||||
* 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 ensureMemorySearchDisabledDefault(config: Record<string, unknown>): boolean {
|
||||
if (hasUserMemorySearchConfig(config)) return false;
|
||||
|
||||
export function ensureMemorySearchFtsDefault(
|
||||
config: Record<string, unknown>,
|
||||
migrateLegacyDisabledDefault = false,
|
||||
): MemorySearchDefaultResult {
|
||||
const agents = (isRecord(config.agents) ? config.agents : {}) as Record<string, unknown>;
|
||||
const defaults = (isRecord(agents.defaults) ? agents.defaults : {}) as Record<string, unknown>;
|
||||
const list = Array.isArray(agents.list) ? agents.list : [];
|
||||
if (list.some((entry) => isRecord(entry) && entry.memorySearch !== undefined)) {
|
||||
return 'unchanged';
|
||||
}
|
||||
|
||||
defaults.memorySearch = { enabled: false };
|
||||
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 true;
|
||||
return memorySearch === undefined ? 'seeded' : 'migrated';
|
||||
}
|
||||
|
||||
@@ -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'})`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -37,7 +37,10 @@ function resolveOpenClawStateDir(): string {
|
||||
}
|
||||
|
||||
function resolveOpenClawStateSqlitePath(): string {
|
||||
return join(resolveOpenClawStateDir(), 'openclaw.sqlite');
|
||||
// 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>> {
|
||||
@@ -88,6 +91,7 @@ export function upsertPluginInstallRecordsIntoSqlite(
|
||||
|
||||
ensureOpenClawStateDirExists();
|
||||
const sqlitePath = resolveOpenClawStateSqlitePath();
|
||||
mkdirSync(join(resolveOpenClawStateDir(), 'state'), { recursive: true });
|
||||
|
||||
let db: DatabaseSync | null = null;
|
||||
try {
|
||||
@@ -157,6 +161,66 @@ export function upsertPluginInstallRecordsIntoSqlite(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
|
||||
+360
-133
@@ -7,12 +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 { upsertPluginInstallRecordsIntoSqlite, ensureOpenClawStateDirExists } from './plugin-install-index';
|
||||
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;
|
||||
@@ -122,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
|
||||
@@ -131,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
|
||||
@@ -239,28 +265,57 @@ const PLUGIN_NPM_NAMES: Record<string, string> = {
|
||||
'openclaw-weixin': '@tencent-weixin/openclaw-weixin',
|
||||
};
|
||||
|
||||
const OPENCLAW_CONFIG_PATH = join(homedir(), '.openclaw', 'openclaw.json');
|
||||
|
||||
/**
|
||||
* Official @openclaw/* channel plugins that ClawX mirrors into
|
||||
* ~/.openclaw/extensions/. OpenClaw 2026.6+ requires matching
|
||||
* plugins.installs metadata so trustedOfficialInstall is true and
|
||||
* runtime APIs such as openKeyedStore are available.
|
||||
* 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.
|
||||
*/
|
||||
const TRUSTED_OFFICIAL_EXTENSION_PLUGINS: Record<string, string> = {
|
||||
whatsapp: '@openclaw/whatsapp',
|
||||
discord: '@openclaw/discord',
|
||||
qqbot: '@openclaw/qqbot',
|
||||
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[];
|
||||
};
|
||||
|
||||
type TrustedOfficialPluginInstallRecord = {
|
||||
source: 'npm';
|
||||
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;
|
||||
resolvedName: string;
|
||||
resolvedVersion: string;
|
||||
resolvedSpec: string;
|
||||
installedAt: string;
|
||||
};
|
||||
|
||||
@@ -277,58 +332,223 @@ function normalizePluginInstallPathForRecord(targetDir: string): string | null {
|
||||
function buildTrustedOfficialPluginInstallRecord(
|
||||
pluginDirName: string,
|
||||
targetDir: string,
|
||||
): TrustedOfficialPluginInstallRecord | null {
|
||||
const npmName = TRUSTED_OFFICIAL_EXTENSION_PLUGINS[pluginDirName];
|
||||
if (!npmName) return null;
|
||||
): { 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 {
|
||||
source: 'npm',
|
||||
spec: npmName,
|
||||
installPath,
|
||||
version,
|
||||
resolvedName: npmName,
|
||||
resolvedVersion: version,
|
||||
resolvedSpec: `${npmName}@${version}`,
|
||||
installedAt: new Date().toISOString(),
|
||||
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);
|
||||
}
|
||||
|
||||
function trustedInstallRecordMatches(
|
||||
existing: unknown,
|
||||
expected: TrustedOfficialPluginInstallRecord,
|
||||
): boolean {
|
||||
if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {
|
||||
return false;
|
||||
}
|
||||
const record = existing as Record<string, unknown>;
|
||||
return record.source === expected.source
|
||||
&& record.spec === expected.spec
|
||||
&& record.installPath === expected.installPath
|
||||
&& record.version === expected.version
|
||||
&& record.resolvedName === expected.resolvedName
|
||||
&& record.resolvedVersion === expected.resolvedVersion
|
||||
&& record.resolvedSpec === expected.resolvedSpec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write or refresh plugins.installs.<id> for a ClawX-mirrored official plugin.
|
||||
* Also persists the record into openclaw.sqlite for OpenClaw 2026.6+ trust checks.
|
||||
* 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 function syncTrustedOfficialPluginInstallRecord(
|
||||
export async function syncTrustedOfficialPluginInstallRecord(
|
||||
pluginDirName: string,
|
||||
targetDir: string,
|
||||
): boolean {
|
||||
): Promise<boolean> {
|
||||
const expected = buildTrustedOfficialPluginInstallRecord(pluginDirName, targetDir);
|
||||
if (!expected) return false;
|
||||
|
||||
@@ -336,58 +556,60 @@ export function syncTrustedOfficialPluginInstallRecord(
|
||||
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();
|
||||
if (!existsSync(fsPath(OPENCLAW_CONFIG_PATH))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const raw = readFileSync(fsPath(OPENCLAW_CONFIG_PATH), 'utf-8');
|
||||
const config = JSON.parse(raw) as Record<string, unknown>;
|
||||
let plugins = config.plugins;
|
||||
if (!plugins || typeof plugins !== 'object' || Array.isArray(plugins)) {
|
||||
plugins = { enabled: true, installs: {} };
|
||||
config.plugins = plugins;
|
||||
}
|
||||
|
||||
const pluginsRecord = plugins as Record<string, unknown>;
|
||||
const installs = pluginsRecord.installs;
|
||||
const installsRecord = installs && typeof installs === 'object' && !Array.isArray(installs)
|
||||
? installs as Record<string, unknown>
|
||||
: {};
|
||||
|
||||
const existing = installsRecord[pluginDirName];
|
||||
if (!trustedInstallRecordMatches(existing, expected)) {
|
||||
installsRecord[pluginDirName] = expected;
|
||||
pluginsRecord.installs = installsRecord;
|
||||
writeFileSync(
|
||||
fsPath(OPENCLAW_CONFIG_PATH),
|
||||
`${JSON.stringify(config, null, 2)}\n`,
|
||||
'utf-8',
|
||||
);
|
||||
logger.info(`[plugin] Synced trusted install metadata for ${pluginDirName}`);
|
||||
jsonChanged = true;
|
||||
}
|
||||
jsonChanged = await removeLegacyPluginInstallMetadataFromConfig(recordIds);
|
||||
} catch (error) {
|
||||
logger.warn(`[plugin] Failed to sync trusted install metadata for ${pluginDirName}:`, error);
|
||||
return false;
|
||||
// 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({
|
||||
[pluginDirName]: expected,
|
||||
[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 trusted install metadata for all mirrored official plugins on disk. */
|
||||
export function repairTrustedOfficialPluginInstallRecords(): void {
|
||||
/** 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;
|
||||
}
|
||||
syncTrustedOfficialPluginInstallRecord(pluginDirName, targetDir);
|
||||
await syncTrustedOfficialPluginInstallRecord(pluginDirName, targetDir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -464,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);
|
||||
|
||||
@@ -526,28 +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) {
|
||||
syncTrustedOfficialPluginInstallRecord(pluginDirName, targetDir);
|
||||
return { installed: true }; // no bundled source to compare, keep existing
|
||||
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) {
|
||||
syncTrustedOfficialPluginInstallRecord(pluginDirName, targetDir);
|
||||
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(
|
||||
@@ -564,21 +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);
|
||||
syncTrustedOfficialPluginInstallRecord(pluginDirName, 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.
|
||||
}
|
||||
@@ -619,8 +850,7 @@ export function ensurePluginInstalled(
|
||||
copyPluginFromNodeModules(npmPkgPath, targetDir, npmName);
|
||||
fixupPluginManifest(targetDir);
|
||||
if (existsSync(fsPath(join(targetDir, 'openclaw.plugin.json')))) {
|
||||
syncTrustedOfficialPluginInstallRecord(pluginDirName, targetDir);
|
||||
return { installed: true };
|
||||
return await finalizeInstalledMirror();
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
@@ -637,8 +867,7 @@ export function ensurePluginInstalled(
|
||||
);
|
||||
}
|
||||
} else if (existsSync(fsPath(targetManifest))) {
|
||||
syncTrustedOfficialPluginInstallRecord(pluginDirName, targetDir);
|
||||
return { installed: true }; // same version, already installed
|
||||
return await finalizeInstalledMirror(); // same version, already installed
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -673,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'),
|
||||
@@ -689,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'),
|
||||
@@ -740,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}`);
|
||||
}
|
||||
@@ -748,5 +975,5 @@ export async function ensureAllBundledPluginsInstalled(): Promise<void> {
|
||||
logger.warn(`[plugin] Failed to install/upgrade ${label} plugin:`, error);
|
||||
}
|
||||
}
|
||||
repairTrustedOfficialPluginInstallRecords();
|
||||
await repairTrustedOfficialPluginInstallRecords();
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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) };
|
||||
|
||||
@@ -42,6 +42,7 @@ export interface AppSettings {
|
||||
proxyHttpsServer: string;
|
||||
proxyAllServer: string;
|
||||
proxyBypassRules: string;
|
||||
memorySearchFtsMigrationVersion: number;
|
||||
|
||||
// Update
|
||||
updateChannel: 'stable' | 'beta' | 'dev';
|
||||
@@ -96,6 +97,7 @@ function createDefaultSettings(): AppSettings {
|
||||
proxyHttpsServer: '',
|
||||
proxyAllServer: '',
|
||||
proxyBypassRules: '<local>;localhost;127.0.0.1;::1',
|
||||
memorySearchFtsMigrationVersion: 0,
|
||||
|
||||
// Update
|
||||
updateChannel: 'stable',
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ Related scenarios: `acp-chat-experience`, `acp-file-activity`, `gateway-backend-
|
||||
|
||||
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`, `unify-acp-file-cards`
|
||||
Related tasks: `acp-media-attachments`, `acp-attachment-open-with`, `fix-acp-directory-attachments`, `unify-acp-file-cards`
|
||||
|
||||
## Trust Boundaries And Ownership
|
||||
|
||||
@@ -28,11 +28,11 @@ Listing never grants a durable capability. Application-specific open freshly enu
|
||||
|
||||
## Local Resolution And Special Scopes
|
||||
|
||||
An accepted absolute, home-relative, `file:`, or execution-cwd-relative reference may resolve to any existing regular local file, including a file outside the active workspace or managed OpenClaw directories. The target is canonicalized before use. The local `scope` returned to Renderer is classification metadata for existing UI behavior, not an authorization root:
|
||||
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 in the Main-owned staging record. The same file may also resolve from an explicit path without claiming staging identity.
|
||||
- `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.
|
||||
@@ -46,9 +46,9 @@ Main applies syntax checks before ownership checks and authorization again befor
|
||||
- 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 and canonicalize the target. Symlink targets and files outside the workspace are allowed after canonical resolution.
|
||||
- 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 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 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.
|
||||
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
|
||||
|
||||
@@ -58,11 +58,11 @@ Display labels come from approved metadata or a decoded basename. Main reduces l
|
||||
|
||||
## 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 targets use the right-side Preview panel. Unsupported, known binary, audio/video, archive, other office-document, or over-limit local targets use the system application only after a user click. HTTP and HTTPS targets open externally only after a user click.
|
||||
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 submits the already-present local file URI to the existing right-side Web Browser, equivalent to the user entering that URI in its address bar; this browser navigation is separate from native attachment operations.
|
||||
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.
|
||||
|
||||
@@ -123,7 +123,7 @@ Main caches normalized list metadata, converted icons, and private list records
|
||||
|
||||
## Failure And Privacy Semantics
|
||||
|
||||
An invalid, stale, missing, unsafe, remote-for-local-operation, or non-file reference becomes an unavailable/error result. It cannot be previewed or opened, but it does not suppress assistant prose or independently valid attachments. A valid existing file 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.
|
||||
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.
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# ACP Chat Architecture And Timeline
|
||||
|
||||
Status: current architecture reference, reviewed 2026-07-15.
|
||||
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`
|
||||
Related tasks: `acp-native-chat`, `acp-media-attachments`, `filter-openclaw-heartbeat-session`, `recover-acp-session-after-gateway-restart`
|
||||
|
||||
## Ownership
|
||||
|
||||
@@ -19,7 +19,13 @@ 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. Restricted Gateway host-event evidence may supplement asynchronous image-generation completion, but it is not a source for ordinary Chat messages or tool history.
|
||||
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
|
||||
|
||||
@@ -27,13 +33,15 @@ Renderer-visible session identity is the OpenClaw Gateway session key. Main may
|
||||
|
||||
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 can restore tools and file activity; transcript-only fallback must not invent them.
|
||||
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, live updates continue through the normal host-event route. Permission requests are accepted only after the current loaded session starts a prompt, preventing load-time or handoff requests from creating invisible waiters.
|
||||
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.
|
||||
|
||||
@@ -88,10 +96,10 @@ Available attachment cards contain a primary semantic action with keyboard activ
|
||||
|
||||
## Chat Behaviors
|
||||
|
||||
- The primary Chat view does not render the legacy Execution Graph.
|
||||
- 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. 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.
|
||||
- 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
|
||||
|
||||
@@ -17,13 +17,13 @@ Standard ACP image, `resource_link`, and URI-backed `resource` content blocks ar
|
||||
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 an explicit line-leading assistant `MEDIA:` directive outside fenced code blocks. This exception does not require image-generation context, but it recovers only the attachment reference, never the surrounding assistant message.
|
||||
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, inline prose paths, unknown URI schemes, incidental tool paths, and directives inside fenced code blocks are not general attachments.
|
||||
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
|
||||
|
||||
@@ -40,11 +40,13 @@ Accepted live evidence includes structured media fields such as `mediaUrl`, `med
|
||||
|
||||
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.
|
||||
|
||||
### Explicit MEDIA Attachments
|
||||
### Canonical And Explicit MEDIA Attachments
|
||||
|
||||
The general attachment extractor considers normalized assistant roles only. 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. The current source-reference bound is `4096` characters.
|
||||
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.
|
||||
|
||||
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. Unknown URI schemes, malformed URLs or quotes, empty references, Markdown/list wrappers, inline prose, ordinary bare paths, and wrapped references 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 render the raw directive or surrounding transcript prose.
|
||||
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.
|
||||
|
||||
@@ -64,13 +66,13 @@ After successful `loadSession` for an existing session, the store may call:
|
||||
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 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.
|
||||
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. Bare-path or broad prose extraction is rejected because false positives would widen the local-file trust surface.
|
||||
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
|
||||
|
||||
|
||||
@@ -53,13 +53,13 @@ The versioned attention store persists only exact-key `observedBusy` and `unread
|
||||
|
||||
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 Web Browser
|
||||
## Workspace Browser And Local HTML Preview
|
||||
|
||||
The right panel tabs are Workspace, Preview, Changes, and Web Browser. Workspace keeps the existing store tab value `browser`; the unrelated Electron Web Browser uses `web-browser`. 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.
|
||||
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.
|
||||
|
||||
The Web Browser is a fixed fourth tab with one persistent Electron guest. `ArtifactTab` keeps `browser` and `web-browser` distinct; `WebBrowserAnchor` marks the panel body while the route-stable `WebBrowserHost` mounted by `MainLayout` owns the live guest. The stable panel selectors are `artifact-panel-tabs`, `artifact-panel-tab-web-browser`, and `web-browser-anchor`; the global surface selectors are `web-browser-host` and `web-browser-webview`. Its session, security, lifecycle, permission, popup, download, proxy, and data-clearing contract is documented separately in `harness/reference/web-browser.md`.
|
||||
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
|
||||
|
||||
@@ -73,6 +73,6 @@ The Chat question directory belongs to the active ACP timeline rather than works
|
||||
|
||||
## 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/e2e/chat-workspace-context.spec.ts` including inherited/recent/known-workspace selection and synthetic-title replacement coverage, `tests/e2e/chat-new-session-date.spec.ts`, `tests/e2e/chat-acp-inline-timeline.spec.ts`, `tests/e2e/chat-question-directory.spec.ts`, `tests/e2e/chat-sidebar-session-attention.spec.ts`, `tests/e2e/office-document-preview.spec.ts`, and the three final Web Browser E2E specs linked from `harness/reference/web-browser.md`.
|
||||
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.
|
||||
|
||||
@@ -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`.
|
||||
@@ -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`.
|
||||
@@ -135,6 +135,12 @@ Workspace and Preview surfaces remain mounted to preserve surrounding UI state,
|
||||
|
||||
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:
|
||||
@@ -152,7 +158,7 @@ Errors use localized format-specific generic messages and never show parser exce
|
||||
- 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, keyboard shortcuts, animation, transitions, media playback, fullscreen, presenter mode, or automatic slide shows.
|
||||
- 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.
|
||||
@@ -188,4 +194,4 @@ Renderer authority, DOCX isolation/options/links/zoom, PPTX construction/sizing/
|
||||
|
||||
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, the single-mounted-viewer invariant, Host API read routes, and absence of legacy direct IPC.
|
||||
`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.
|
||||
@@ -182,6 +182,6 @@ Do not begin this migration merely because a type exists in an unbundled upstrea
|
||||
|
||||
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-store-history-retry.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`.
|
||||
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.
|
||||
|
||||
@@ -1,169 +1,40 @@
|
||||
# Web Browser
|
||||
# Local HTML Preview Architecture
|
||||
|
||||
Status: implemented contract, reviewed 2026-07-23.
|
||||
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.
|
||||
|
||||
Related scenarios: `gateway-backend-communication`, `chat-workspace-and-navigation`
|
||||
## User flow
|
||||
|
||||
Related rule: `web-browser-security-and-lifecycle`
|
||||
- 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.
|
||||
|
||||
Related task: `web-browser`
|
||||
## Link behavior
|
||||
|
||||
This reference is authoritative for the implemented Web Browser design. The task and rule named above are the executable Harness entry points; historical design and implementation-plan documents are not dependencies.
|
||||
All links are inert:
|
||||
|
||||
## Scope And Non-Goals
|
||||
- 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.
|
||||
|
||||
The Web Browser is the fixed fourth artifact-panel tab with store value `web-browser`. It is distinct from the Workspace file browser, whose value remains `browser`. The tab provides one embedded browsing context with back, forward, refresh, title/address, favicon, force refresh, data clearing, and external-open controls.
|
||||
## Renderer flow
|
||||
|
||||
The feature does not provide multiple tabs or windows, bookmarks, a browsing-history interface, URL or history restoration after restart, password or autofill management, remembered permission grants, geolocation, display capture, a download manager, a custom download destination, or full compatibility with sites that require a distinct popup browsing context. Favicons are implemented and are not a non-goal. A hover URL tooltip is intentionally absent. User-facing labels and errors are owned by the current `chat` locale resources in `shared/i18n/locales/{en,zh,ja,ru}/chat.json`; old design-document label examples are not authoritative.
|
||||
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.
|
||||
|
||||
## Trust Model And Ownership
|
||||
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.
|
||||
|
||||
The ClawX host Renderer is trusted application code; every page loaded in the guest is untrusted. Main owns the dedicated session, accepted attachment identity, single registered guest, top-level URL policy, popup policy, permissions, data clearing, and external opening. Renderer owns lazy selection state, the route-stable host and anchor geometry, webview event-derived toolbar state, immediate address feedback, and localized presentation.
|
||||
## Main boundary
|
||||
|
||||
Application address and recovery navigation must use `hostApi.webBrowser.navigate`. Main normalizes and validates the URL, obtains the registered guest from `WebBrowserGuestRegistry`, and calls `guest.loadURL()`. Renderer history, normal refresh, and force refresh use the attached webview DOM methods because they act on its existing navigation controller; Renderer application code must not call `webview.loadURL()`.
|
||||
`normalizeWebBrowserHtmlFileUrl` accepts only hostless, query-free, fragment-free `file:///` URLs ending in `.html` or `.htm`. The Host API has only:
|
||||
|
||||
This division centralizes trusted application behavior but is not a security boundary against a compromised host Renderer. Electron does not expose a cancellable Main event for every direct host-Renderer `webview.loadURL()` call, and host DOM access could invoke it. Main policy instead protects the host from untrusted guest content, rejects unauthorized attachment identities and top-level page transitions it can observe, and prevents the guest from receiving ClawX privileges.
|
||||
- `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.
|
||||
|
||||
## Identity And Session
|
||||
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 browser uses exactly partition `persist:clawx-web-browser`, creates its guest at the internal URL `about:blank`, and uses this exact UserAgent at both Session and guest level on every platform:
|
||||
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.
|
||||
|
||||
```text
|
||||
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.7559.236 Electron/40.8.4 Safari/537.36
|
||||
```
|
||||
## Security consequence
|
||||
|
||||
The persistent partition retains cookies and site storage. Only artifact-panel width is persisted by the relevant UI store, so guest creation, current URL, live page state, and in-memory navigation history restart at an uncreated guest and then `about:blank` on every application run.
|
||||
|
||||
## Address Parsing And Top-Level Policy
|
||||
|
||||
`parseWebBrowserAddress` implements address-bar parsing in this order:
|
||||
|
||||
1. Trim surrounding whitespace and reject an empty value.
|
||||
2. Reject Unix-rooted, slash- or backslash-rooted, Windows drive-rooted, UNC-like, and tilde-rooted filesystem paths. ClawX never converts a plain path into a URL.
|
||||
3. Detect an explicit URI scheme with `^[a-z][a-z\d+.-]*:`. A host token followed by a numeric port is the deliberate exception: inputs such as `localhost:3000`, `127.0.0.1:8080/status`, and `example.com:8443/path` are treated as a schemeless host plus numeric port, not as a custom scheme, and receive `https://`.
|
||||
4. Prefix every other schemeless value with `https://`, parse with the platform `URL` implementation, and return its canonical `href`.
|
||||
5. Accept only absolute `http:`, `https:`, and explicit standard `file:///` URLs. The file spelling must begin with `file:///`; hostful file URLs and abbreviated `file:` forms are rejected. Accepted file URLs must parse with an empty hostname.
|
||||
6. Reject the reserved `about:blank` URL, malformed URLs, `chrome:`, `javascript:`, `data:`, `ftp:`, and every other protocol.
|
||||
|
||||
`normalizeWebBrowserTopLevelUrl` is the stricter Main-facing policy. It trims and canonicalizes but never completes a missing scheme, never converts a path, and accepts the same `http:`, `https:`, and `file:///` set while rejecting `about:blank`. The initial `about:blank` is allowed only as part of the verified attachment identity before guest navigation policy is installed.
|
||||
|
||||
Main applies that strict policy to typed navigation, crash recovery, main-frame `will-navigate`, main-frame `will-redirect`, popup targets, and the registered guest's current URL before external opening. Subframe redirects and ordinary document subresources are not filtered by this top-level policy. Explicit `file:///` support deliberately permits a user to load locally readable files, subject to Chromium origin isolation and enabled web security.
|
||||
|
||||
## One-Guest Host Geometry, Visibility, And Focus
|
||||
|
||||
`MainLayout` mounts one `WebBrowserHost` outside routed page content. It returns no webview until `webBrowserInitialized` becomes true on first tab selection. `ArtifactPanel` renders `WebBrowserAnchor`; the host is a fixed-position overlay whose fractional `left`, `top`, `width`, and `height` mirror the connected, positive-size anchor.
|
||||
|
||||
Geometry is measured immediately and refreshed through `ResizeObserver`, window resize, capturing scroll, and `visualViewport` resize. Signals are coalesced to one `requestAnimationFrame`. A missing, disconnected, zero-width, or zero-height anchor makes the host unavailable rather than leaving stale interactive geometry.
|
||||
|
||||
After initialization the same webview DOM node and guest remain mounted across panel close, artifact-tab changes, chat-session changes, and route changes. A visible host requires an open panel, active `web-browser` tab, and valid geometry. Otherwise it uses hidden visibility, no pointer events, `aria-hidden=true`, and `inert`; it is not suspended, muted, reloaded, or destroyed, so scripts, network traffic, audio, and resource use may continue. If focus is inside when the host becomes hidden, focus moves to the Web Browser tab or the first available application focus target. A crash also moves focus out before presenting recovery UI. The More menu closes when the browser becomes hidden or crashed.
|
||||
|
||||
## Toolbar, Editing, And Async Races
|
||||
|
||||
Back and Forward reflect `canGoBack()` and `canGoForward()` and use native disabled semantics. Refresh calls `reload()` and Force Refresh calls `reloadIgnoringCache()` only on the currently attached guest.
|
||||
|
||||
The non-editing address control displays the title, falling back to the URL. It displays the first `page-favicon-updated` URL, with a same-size globe placeholder if no candidate loads. Same-document and same-origin main-frame navigation retain the current favicon; cross-origin navigation and redirects clear it until a replacement arrives. Editing hides both favicon and placeholder. Visual text truncates, while the full URL remains available to assistive technology and edit mode; hovering does not show a URL tooltip.
|
||||
|
||||
The initial blank document starts with an empty, focused, selected draft. Clicking the display snapshots the current URL into the draft. Page title or URL changes never overwrite an active draft. Escape and blur cancel without navigation and reveal the latest page title/URL. Invalid Enter input retains and refocuses the draft. Valid Enter input stays in edit mode until the Host API navigation resolves; only the latest submission may close or refocus the editor, so an older promise cannot overwrite a newer attempt.
|
||||
|
||||
Renderer assigns a generation to each Host API navigation and reports at most one localized load failure for the active request even if both `did-fail-load` and the Host API promise reject. Main and Renderer treat Electron `ERR_ABORTED` (`-3`) as a normal superseded/cancelled load. A later genuine failure is not suppressed by completion of an older request.
|
||||
|
||||
Each clear operation disables only its matching menu action. On success Renderer force-refreshes only if the captured webview is still the current generation and is attached; a guest that attaches during the operation may refresh, but a crashed or replacement guest must not. Clear failure leaves the page unchanged.
|
||||
|
||||
## Main Startup And Attachment Ordering
|
||||
|
||||
One `WebBrowserGuestRegistry` is created at module scope. During `initialize()`, Main configures the dedicated Session before proxy/network side effects and before constructing the main BrowserWindow. Session UserAgent, permission handlers, and the single default-download observer therefore exist before any guest can use the partition.
|
||||
|
||||
Immediately after BrowserWindow construction, before loading Renderer content, `installWebBrowserGuestPolicy` installs `will-attach-webview` and `did-attach-webview` listeners on the embedder. Typed Host API services are then registered before `loadMainWindow()`. This order is required: no Renderer-created webview may attach before the session policy, attachment gate, or privileged navigation service exists.
|
||||
|
||||
`will-attach-webview` synchronously accepts only the complete identity: exact partition, initial `about:blank` source, fixed UserAgent, boolean popup delivery enabled, and an empty preload value. It reserves the sole pending slot before hardening preferences. Mismatches, concurrent reservations, and additional live guests are prevented.
|
||||
|
||||
Hardening deletes preload and forces Node integration off in the main frame, subframes, and workers; plugins and insecure-content execution off; context isolation, sandboxing, and web security on. On `did-attach-webview`, Main additionally verifies webview type and exact Session, completes registry ownership, reapplies the fixed UserAgent, and installs top-level navigation, redirect, popup, cleanup, and destruction handling. The guest receives neither the ClawX preload nor `window.clawx`, `window.electron`, Node globals, or the host bridge. Ownership is released only when the registered guest is destroyed; only then may recovery reserve a replacement.
|
||||
|
||||
## Popup Policy And Rationale
|
||||
|
||||
Every `setWindowOpenHandler` result is `deny`, so no child BrowserWindow, BrowserView, WebContentsView, or second webview is created. If the target passes strict top-level normalization and the handler still owns the guest, Main manually loads it in that guest; unsupported targets and load failures are logged.
|
||||
|
||||
A distinct child browsing context is required to preserve `window.opener`, but the one-tab product cannot make one guest simultaneously be opener and child or adopt a child into the existing webview. Same-tab fallback is therefore intentional and cannot preserve returned window handles, initially blank popups populated later, `_blank` POST bodies, full referrer fidelity, named-window behavior, or window features.
|
||||
|
||||
## Permission Policy
|
||||
|
||||
Permission check and request handlers are installed on the dedicated Session before Renderer loading. Decisions are scoped to the current registered guest and are never persisted by ClawX.
|
||||
|
||||
| Permission | Check path | Request path | Persistence |
|
||||
| --- | --- | --- | --- |
|
||||
| Clipboard read, sanitized write, and deprecated compatible read | Allow | Allow without a dialog | Not recorded by ClawX |
|
||||
| Camera and microphone (`media`) | Return false so a request is made | One native origin-aware Allow/Deny dialog per request from the registered guest | Never remembered |
|
||||
| Geolocation | Deny | Deny without a dialog | Never remembered |
|
||||
| Display capture | Deny; no display-media handler | Deny | Never remembered |
|
||||
| Notifications and every other permission | Deny | Deny without a dialog | Never remembered |
|
||||
|
||||
A media request must contain audio, video, or both and must belong to the registered guest. One localized native dialog covers a combined camera/microphone request. Missing main window, empty or screen-only media types, dialog/language errors, and guest destruction or replacement before the answer all deny exactly once. Locale text is resolved at request time.
|
||||
|
||||
## Data Clearing, Downloads, Proxy, And External Opening
|
||||
|
||||
Both clear operations cover every origin in `persist:clawx-web-browser` and complete before Renderer conditionally refreshes the captured guest.
|
||||
|
||||
| Action | Clears | Preserves |
|
||||
| --- | --- | --- |
|
||||
| Clear Cookies | Cookies only | HTTP cache, Cache Storage, Local Storage, IndexedDB, Service Workers, and downloaded files |
|
||||
| Clear Site Data | HTTP/Chromium cache, Cache Storage, Local Storage, IndexedDB, and Service Workers | Cookies and downloaded files |
|
||||
|
||||
Electron default download behavior and the operating system's native flow remain in force. The single Session listener observes completion only to log interruption; it does not cancel, set a path, suppress native UI, or create progress/history UI. A platform may show a native Save dialog and wait for user interaction. Automatic saving to Downloads and unattended terminal completion are not promised.
|
||||
|
||||
The dedicated Session uses Electron/Chromium system proxy resolution. It does not inherit or synchronize ClawX client proxy settings, call `setProxy`, recycle browser connections after client-proxy changes, or alter `defaultSession` behavior.
|
||||
|
||||
External opening takes no Renderer URL argument. Main reads the registered guest's current URL, strictly validates and normalizes it, then calls `shell.openExternal`. `about:blank` is disabled. An allowed file URL remains a URL and is never passed to `shell.openPath`; the operating system may open its associated application rather than a browser.
|
||||
|
||||
## Failure Semantics And Crash Recovery
|
||||
|
||||
Parser errors keep the current page and active draft and show the error mapped from the exact parser result. Non-aborted main-frame load failures show one localized load error while retaining the current URL and controls. Policy-blocked page transitions and popup failures are logged by Main. Data-clear and external-open failures show localized errors and do not replace the page. Download interruption is log-only.
|
||||
|
||||
`render-process-gone` clears active attachment/loading/navigation state and favicon state, removes the failed webview from the rendered surface, and presents localized recovery UI. Recovery is explicit. It creates one replacement with the original attachment identity at `about:blank`; only after `did-attach` does Renderer ask the typed Host API to load the last observed URL that still passes strict top-level policy. If no such URL exists, the replacement remains blank. Recovery does not restore the crashed guest's history, page state, form state, returned popup handles, or favicon. Back and Forward reset disabled.
|
||||
|
||||
## Required Policy-Rationale Comments
|
||||
|
||||
The following non-obvious decisions must retain concise adjacent source comments. The reference carries the full rationale; comments should explain the local invariant rather than duplicate this document.
|
||||
|
||||
- `WebBrowserHost`: removing a hidden webview destroys its guest, so inactive states hide the route-stable host instead.
|
||||
- `installWebBrowserGuestPolicy`: popup children are denied and allowed targets use lossy same-tab fallback, including its opener/handle/fidelity limitation.
|
||||
- `configureWebBrowserSession`: geolocation is denied because ClawX provides no location service.
|
||||
- `configureWebBrowserSession`: the download observer deliberately preserves Electron/OS default save behavior by neither cancelling nor assigning a path.
|
||||
- `configureWebBrowserSession`: the macOS-shaped UserAgent is intentionally fixed on every platform for stable compatibility and deterministic requests.
|
||||
|
||||
## Rejected Alternatives
|
||||
|
||||
- Multiple webviews, child windows, BrowserViews, and WebContentsViews were rejected because the product contract is one persistent tab with one registry authority.
|
||||
- Mounting the webview inside routed artifact content or unmounting it while hidden was rejected because either destroys the guest and loses live state/history.
|
||||
- Restoring URL/history or persisting guest initialization was rejected; only partition storage and artifact-panel width survive restart.
|
||||
- Direct Renderer `loadURL()`, Renderer-selected partitions, scheme completion in Main, and arbitrary external-open destinations were rejected in favor of one typed privileged path and strict Main normalization.
|
||||
- Search-query guessing, plain filesystem-path conversion, hostful file URLs, broader protocols, and `about:blank` user navigation were rejected to keep top-level interpretation explicit.
|
||||
- Creating popup children for better web compatibility was rejected because it violates one-guest ownership; same-tab compatibility loss is accepted.
|
||||
- Remembered permissions, geolocation/display capture, custom download paths/management, and ClawX proxy synchronization were rejected scope and security expansions.
|
||||
- A hover URL tooltip was rejected; the URL is exposed through assistive text and edit mode. Omitting favicons is an obsolete design claim, not an implemented alternative.
|
||||
|
||||
## Implementation Anchors
|
||||
|
||||
Shared policy is defined by `WEB_BROWSER_PARTITION`, `WEB_BROWSER_INITIAL_URL`, `WEB_BROWSER_USER_AGENT`, `parseWebBrowserAddress`, `normalizeWebBrowserTopLevelUrl`, and `canOpenWebBrowserExternally` in `shared/web-browser.ts`. The typed privileged surface is `hostApi.webBrowser.navigate`, `clearCookies`, `clearSiteData`, and no-argument `openExternal`.
|
||||
|
||||
Main ownership is anchored by `WebBrowserGuestRegistry`, `isExpectedWebBrowserAttachment`, `hardenWebBrowserPreferences`, and `installWebBrowserGuestPolicy` in `electron/main/web-browser-policy.ts`; `configureWebBrowserSession` in `electron/main/web-browser-session.ts`; startup sequencing in `electron/main/index.ts`; and `createWebBrowserApi` in `electron/services/web-browser-api.ts`.
|
||||
|
||||
Renderer ownership is anchored by the `ArtifactTab` value `web-browser`, `webBrowserInitialized`, `openWebBrowser`, and `setWebBrowserAnchor` in `src/stores/artifact-panel.ts`, plus `WebBrowserAnchor`, `WebBrowserHost`, `WebBrowserToolbar`, and `WebBrowserAddressControl`. `MainLayout` mounts one `WebBrowserHost` outside routed content.
|
||||
|
||||
Stable acceptance selectors are:
|
||||
|
||||
- Panel and placement: `artifact-panel-tabs`, `artifact-panel-tab-web-browser`, and `web-browser-anchor`.
|
||||
- Persistent surface: `web-browser-host` and `web-browser-webview`.
|
||||
- Navigation: `web-browser-toolbar`, `web-browser-back`, `web-browser-forward`, `web-browser-refresh`, `web-browser-address-input`, `web-browser-address-display`, `web-browser-favicon`, and `web-browser-favicon-placeholder`.
|
||||
- Privileged actions: `web-browser-more`, `web-browser-force-refresh`, `web-browser-clear-cookies`, `web-browser-clear-site-data`, and `web-browser-open-external`.
|
||||
|
||||
## Validation Anchors
|
||||
|
||||
Contract and locale coverage is anchored by `tests/unit/harness-specs.test.ts` and `tests/unit/i18n-locale-parity.test.ts`. Shared and privileged boundaries are covered by `tests/unit/web-browser-url.test.ts`, `tests/unit/host-api-facade.test.ts`, `tests/unit/web-browser-policy.test.ts`, `tests/unit/web-browser-session.test.ts`, `tests/unit/web-browser-api.test.ts`, and `tests/unit/host-services.test.ts`. Renderer behavior and placement are covered by `tests/unit/artifact-panel-store.test.ts`, `tests/unit/artifact-panel.test.tsx`, `tests/unit/web-browser-controls.test.tsx`, `tests/unit/web-browser-host.test.tsx`, and `tests/unit/main-layout.test.tsx`.
|
||||
|
||||
`tests/e2e/web-browser-navigation.spec.ts` anchors lazy creation, tab order, controls, title/favicon presentation, absence of a hover URL tooltip, allowed and rejected navigation, same-guest popups, fixed UserAgent, explicit file URLs, and external opening. `tests/e2e/web-browser-lifecycle.spec.ts` anchors hidden background lifetime, geometry, crash replacement, cookie persistence, and lack of URL/history restoration. `tests/e2e/web-browser-policy.spec.ts` anchors guest isolation, cross-origin clearing scopes, per-request media prompts, clipboard and denied permissions, and untouched Electron/OS download behavior, including the native macOS save-sheet path.
|
||||
|
||||
## Validation Limitations
|
||||
|
||||
Unit tests use mocked Electron and DOM surfaces, so they validate policy decisions and ordering logic rather than Chromium enforcement. Electron E2E uses deterministic local pages and isolated user data; it does not establish compatibility with every website, authentication flow, popup pattern, service worker, permission type, real camera/microphone device, enterprise proxy, or hostile compromised host Renderer.
|
||||
|
||||
Native Save UI, `shell.openExternal` handling of file URLs, system proxy resolution, and permission presentation vary by operating system and environment. E2E can observe that ClawX does not cancel or assign a download path and can cover known native macOS save-sheet behavior, but cannot promise unattended completion or every platform's UI. Hidden-state tests prove retained guest identity and representative live state/history, not an upper bound on background CPU, memory, network, or audio use. Manual platform checks remain appropriate when Electron is upgraded or native behavior changes.
|
||||
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.
|
||||
|
||||
@@ -8,8 +8,10 @@ appliesTo:
|
||||
- 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. 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 ordinary live prompt updates continue through host events. 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. 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.
|
||||
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 replay is the primary history authority. The only approved 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. 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, ordinary messages, tool cards, plans, permissions, thoughts, file activity, or any parallel 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.
|
||||
|
||||
@@ -9,6 +9,6 @@ appliesTo:
|
||||
|
||||
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 two bounded forms: asynchronous image-generation completion with proven image-generation context, including explicit internal-UI `message` tool source replies; and general attachment recovery from whole-line, line-leading assistant OpenClaw `MEDIA:` directives outside fenced code blocks. The general form accepts only the documented local path, `file:`, execution-cwd-relative, HTTP, and HTTPS forms; quoted references may contain spaces, while unquoted references may not. It does not require image-generation context and projects only one ordered attachment reference per directive, 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, unknown URI schemes, incidental tool paths, and unrelated assistant prose.
|
||||
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
|
||||
|
||||
@@ -9,7 +9,7 @@ appliesTo:
|
||||
|
||||
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. 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. 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.
|
||||
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.
|
||||
|
||||
|
||||
@@ -8,6 +8,10 @@ appliesTo:
|
||||
|
||||
When channel plugin ownership changes between bundled OpenClaw extensions and external `~/.openclaw/extensions/*` installs, ClawX must normalize configuration to one active plugin identity per channel.
|
||||
|
||||
The ClawX channel configuration catalog is intentionally limited to `telegram`, `discord`, `whatsapp`, `wechat`, `dingtalk`, `feishu`, `wecom`, and `qqbot`. OpenClaw may report other channel ids, but the ClawX Channels page must not expose them as configurable or editable channel groups. Filtering an unsupported runtime channel is presentation-only and must not delete or rewrite that channel's underlying OpenClaw configuration.
|
||||
|
||||
Channel credentials and account maps must remain under `channels.<id>`; `plugins.entries.<id>` is activation metadata and must not contain ClawX-generated `accounts` or `defaultAccount` fields. Discord, WhatsApp, and QQBot are external plugins in the pinned OpenClaw runtime and must retain explicit `plugins.allow` and `{ enabled }` entries. Saving changed configuration for a supported external plugin channel while Gateway is running must use the coordinator-owned `config.set` reload without scheduling a second ClawX full restart when OpenClaw peer link repair succeeds. When peer link repair fails after plugin install, Main must schedule the guarded full restart after the config commit instead of relying on the native reload alone. A no-change retry must still start the guarded full restart path after the scoped-binding commit so a newly copied or previously undiscovered plugin is loaded. Successful WeChat QR completion must likewise leave plugin activation on a single lifecycle path. The host save response may return while activation is still pending, provided it explicitly reports that state and failures are caught and surfaced through normal Gateway status/logging. If `config.set` durably commits before its response is lost to a native code-1012 reload, Main may verify that exact persisted config and treat the transaction as committed; it must not perform an out-of-band replay.
|
||||
|
||||
For Feishu/Lark specifically:
|
||||
|
||||
- a configured Feishu channel must not leave both the bundled `feishu` plugin and the legacy external `openclaw-lark` / `feishu-openclaw-plugin` registrations active at the same time
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
id: e2e-parallel-isolation
|
||||
title: E2E Parallel Isolation
|
||||
type: ai-coding-rule
|
||||
appliesTo:
|
||||
- gateway-backend-communication
|
||||
requiredProfiles:
|
||||
- fast
|
||||
- e2e
|
||||
---
|
||||
|
||||
Electron E2E tests are parallel by default because each test owns its HOME, OpenClaw state directory, Electron user-data directory, and Host API configuration. Keep those fixtures test-scoped.
|
||||
|
||||
Tests that mutate OS-global state must use `E2E_EXCLUSIVE_TAG`. Tests that profile shared host CPU, GPU, display, or frame pacing must use `E2E_PERFORMANCE_TAG`. Do not use Playwright serial mode as a cross-file mutex; serial mode only orders tests within its own group.
|
||||
|
||||
When adding another global resource, extend the automated policy check where the resource has a recognizable API. Unknown external resources still require reviewer classification.
|
||||
|
||||
The project graph, environment isolation, and validation commands are documented in `harness/reference/e2e-parallelism.md`.
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
id: electron-rendering-performance
|
||||
title: Electron Rendering Performance
|
||||
type: ai-coding-rule
|
||||
appliesTo:
|
||||
- acp-chat-experience
|
||||
- chat-workspace-and-navigation
|
||||
requiredProfiles:
|
||||
- fast
|
||||
- e2e
|
||||
---
|
||||
|
||||
Leave Electron hardware acceleration enabled by default. Do not call `app.disableHardwareAcceleration()` or globally append `disable-gpu`; Chromium must retain driver detection and its native `--disable-gpu` troubleshooting fallback. Treat software compositing reported by headless or GPU-less CI as an environment result, not a reason to force every desktop renderer onto software rasterization.
|
||||
|
||||
Rendering performance investigations must combine frame pacing, Renderer metrics/profile data, and `app.getGPUFeatureStatus()` captured after `gpu-info-update`. Main CPU profiles do not cover browser/GPU process rasterization. Do not attribute Chromium `(program)` samples to React without an isolated variable that changes the result.
|
||||
|
||||
Keep `pnpm run perf:chat` coverage for both ACP streaming and rich static Markdown interaction. The interaction workload must exercise the production sidebar width animation and vertical Chat scroll path, record generated-only artifacts, and avoid hardware-independent timing gates. Compare repeated runs on the same machine while preserving semantic E2E assertions.
|
||||
|
||||
The full runtime policy and validation anchors are recorded in `harness/reference/electron-rendering-performance.md`.
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
id: gateway-heartbeat-safety
|
||||
title: Gateway Heartbeat Safety
|
||||
type: ai-coding-rule
|
||||
appliesTo:
|
||||
- gateway-backend-communication
|
||||
requiredTests:
|
||||
- tests/unit/gateway-manager-heartbeat.test.ts
|
||||
- tests/unit/gateway-manager-diagnostics.test.ts
|
||||
---
|
||||
|
||||
WebSocket heartbeat misses are availability evidence. A short sequence is not proof that the local Gateway process is dead because long-running model, tool, compaction, and scheduled work may temporarily delay Gateway control-plane responses.
|
||||
|
||||
Misses one through three must remain diagnostic-only: they must not terminate the socket, kill the owned Gateway process, or request `GatewayManager.restart`. A pong or any incoming Gateway message resets the sequence.
|
||||
|
||||
After four consecutive missed responses, ClawX may treat the Gateway as persistently unresponsive and request the guarded `GatewayManager.restart` path only when auto-recovery is enabled and lifecycle state is still `running`. The heartbeat callback must not directly terminate the socket or process, and it must request recovery at most once per uninterrupted miss sequence.
|
||||
|
||||
Authoritative child-process exit, WebSocket close, and Gateway restart close code 1012 signals retain their existing automatic lifecycle paths. Explicit user restart remains available.
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
id: markdown-rendering-safety-and-performance
|
||||
title: Markdown Rendering Safety And Performance
|
||||
type: ai-coding-rule
|
||||
appliesTo:
|
||||
- acp-chat-experience
|
||||
- chat-workspace-and-navigation
|
||||
requiredProfiles:
|
||||
- fast
|
||||
- e2e
|
||||
---
|
||||
|
||||
Use one module-scoped Streamdown configuration for application Markdown. ACP assistant and process Markdown uses streaming mode with incomplete-Markdown repair; Markdown file preview uses static mode. User messages and tool output remain literal and must not enter Streamdown. Enable only the code, math, and CJK plugins. Keep single-dollar math enabled, retain the direct KaTeX dependency and one application KaTeX stylesheet import, and import Streamdown styles once. Do not install or configure the Mermaid plugin; Mermaid fences remain code.
|
||||
|
||||
Preserve the existing content boundary. Build the rehype list from Streamdown defaults without raw-HTML parsing while retaining sanitization and hardening, so raw HTML is visible literal text and never becomes active DOM. Render links through inert `BrowserLink` and disable Streamdown link-safety UI because no anchor remains interactive. Markdown images must continue through `isSafeAcpImageSource`. Enable only the localized code-copy control; disable table, Mermaid, code-download, and line-number controls. Parse YAML and TOML frontmatter in static preview and omit it from output; do not restore the custom splitter or metadata card.
|
||||
|
||||
Keep plugin arrays, component maps, animation options, and security options at module scope so reference churn does not invalidate block memoization. Only the open assistant message segment's final Markdown part may set animation or caret props. Use word-level `fadeIn` with duration 140, stagger 0, and a circle caret; never animate by character. Completed segments, user messages, thoughts, earlier parts, and inactive sends must remain stable and must not acquire or restart animation.
|
||||
|
||||
Preserve ClawX design tokens, assistant-without-bubble layout, prose block spacing, compact lists, the cell-only table grid and themes, source-line-preserving soft-wrapped code with a compact right-aligned language header, vertically centered copy action, and existing inert-link and image styling. Add Electron E2E coverage for streaming Chat and static preview. Tests must cover incomplete Markdown, highlighted and copyable multiline code, all supported math delimiters, CJK punctuation, Mermaid-as-code, literal raw HTML, inert links, safe images, literal user and tool output, frontmatter omission, active-part-only animation, completed-block stability, and the existing visual contracts.
|
||||
|
||||
Capture three successful 80-turn and 300-chunk `pnpm run perf:chat` profiles before and after renderer changes on the same machine, retaining ignored Renderer metrics plus Renderer/Main CPU profiles. Compare three-run medians for elapsed time, Renderer TaskDuration, ScriptDuration, layout duration, long-task count and duration, and sampled Markdown/React stacks. TaskDuration and ScriptDuration may each regress by at most 10 percent; median ScriptDuration or sampled Markdown/render CPU time must improve by at least 10 percent. Inspect a production sourcemap build for Streamdown, Shiki, and unexpected Mermaid cost. Do not replace these relative checks with machine-specific automated timing gates.
|
||||
|
||||
The complete rationale, ownership, safety policy, and validation anchors are recorded in `harness/reference/markdown-rendering.md`.
|
||||
@@ -24,4 +24,6 @@ PPTX renders into a React-owned Canvas keyed by target identity; it is not requi
|
||||
|
||||
Because `pptxviewjs@1.1.9` shares `window.currentProcessor` and `window.currentZipData`, the Electron Renderer may have only a single mounted `PptxViewer`. Kept-mounted surfaces must conditionally mount their PPTX child only while active; CSS hiding is insufficient. Initial, restored, navigation, chart-complete, 100 ms trailing-debounced resize, and teardown operations use the shared serialized scheduler, skip obsolete requests, and never render directly from an observer or chart event. Position is retained by target identity and reported only after successful current renders. Cleanup calls each created instance's public `destroy()` exactly once in scheduler order and removes every ClawX-owned resource.
|
||||
|
||||
The Chat Preview fullscreen control is a Renderer-viewport portal, not native Electron fullscreen or PPTX presenter mode. It must preserve target-keyed slide position, exit from its localized header control or Escape, close when Preview becomes inactive, and preserve the single-mounted-`PptxViewer` invariant across portal transitions.
|
||||
|
||||
Read, parse, sizing, and render failures must terminate in localized generic states without exposing parser exceptions or retry loops. The published dependency may retain internal URLs, delayed chart work, caches, and processor/ZIP globals after public `destroy()`. This dependency-owned retained-resource limitation and incomplete Office fidelity are accepted for the first release: do not patch or conceal them, and do not claim complete reclamation. The single-instance invariant prevents concurrent cross-presentation corruption but does not eliminate retained-resource or ZIP-expansion risk. Preserve the full durable rationale and validation anchors in `harness/reference/office-document-preview.md`.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
id: openclaw-config-delivery
|
||||
title: OpenClaw Config Delivery
|
||||
type: ai-coding-rule
|
||||
appliesTo:
|
||||
- gateway-backend-communication
|
||||
requiredProfiles:
|
||||
- comms
|
||||
references:
|
||||
- harness/reference/openclaw-config-delivery.md
|
||||
---
|
||||
|
||||
ClawX must defer runtime config planning to the bundled OpenClaw Gateway.
|
||||
|
||||
The Main-owned config coordinator must own the entire read-modify-write transaction. Production helpers must not write the active OpenClaw config and then notify another layer afterward.
|
||||
|
||||
When the Gateway is running, the coordinator prefers the runtime-shaped `config.get.config` object as the mutation baseline, applies the caller's mutator, and commits through `config.set` with the returned `hash` as `baseHash`. Source-shaped `raw` is only a compatibility fallback because its redacted secret paths may not align with OpenClaw's write-side runtime snapshot. A successful mutation must not be followed by `SIGUSR1` or a redundant ClawX process restart. Base-hash conflicts retry once from a new snapshot; other RPC failures fail closed instead of performing an out-of-band file write. When `config.set` itself durably writes the exact requested config and then a native code-1012 reload drops its response, the coordinator may verify that persisted commit after Gateway leaves running state and accept it without replaying or rewriting the mutation.
|
||||
|
||||
Coordinator mutators are replayable transformations. They must not perform filesystem writes, SQLite writes, settings writes, lifecycle actions, or other non-idempotent external effects; preload required external inputs before entering the mutator and perform follow-up effects only after a successful commit.
|
||||
|
||||
Gateway WebSocket traces must replace serialized `raw` config-write payloads with a redacted marker. They must not log credentials introduced by a mutator.
|
||||
|
||||
When the Gateway is stopped or starting, the same coordinator mutates the resolved config file under the shared config lock. It must not start the Gateway solely to apply a config mutation.
|
||||
|
||||
ClawX may replace the Gateway process for process-launch environment or argument changes, explicit user restart, application lifecycle, health/crash recovery, or a failed config-delivery fallback. Provider, Agent, Channel, binding, skill, model, and ordinary plugin-entry config changes must not carry a blanket ClawX restart policy when OpenClaw can plan them.
|
||||
|
||||
All coordinator file fallback reads and writes must resolve the active config through `resolveOpenClawConfigPath()` so file delivery and Gateway RPC target the same config. No other production module may write that file.
|
||||
@@ -8,7 +8,7 @@ appliesTo:
|
||||
- gateway-backend-communication
|
||||
---
|
||||
|
||||
Treat file-tool paths as untrusted. Renderer must enforce lexical workspace containment before projection, and Main must independently enforce canonical and symlink-safe containment for every scoped read, stat, handler-list, selected-handler-open, and reveal operation. Tool-derived targets remain read-only in-app previews; created and modified activity may expose explicit native Open with and reveal actions only through `WorkspaceFileRef` Host API operations that freshly resolve a regular file inside the canonical workspace. An HTML activity may also construct a local file URL from the already-authorized workspace root and contained relative path for the existing Web Browser navigation route; this is browser navigation, not a native handler action or canonicalization claim. Deleted activity exposes neither action. Renderer must never send or receive a Main-canonicalized target, executable path, command, or command template.
|
||||
Treat file-tool paths as untrusted. Renderer must enforce lexical workspace containment before projection, and Main must independently enforce canonical and symlink-safe containment for every scoped read, stat, handler-list, selected-handler-open, and reveal operation. Tool-derived targets remain read-only in-app previews; created and modified activity may expose explicit native Open with and reveal actions only through `WorkspaceFileRef` Host API operations that freshly resolve a regular file inside the canonical workspace. An HTML activity may also construct a local file URL from the already-authorized workspace root and contained relative path for the file-only Preview route; this is preview navigation, not a native handler action or canonicalization claim. Deleted activity exposes neither action. Renderer must never send or receive a Main-canonicalized target, executable path, command, or command template.
|
||||
|
||||
File activity remains a record of completed canonical OpenClaw `write`, `edit`, and `apply_patch` inputs. It must not claim to be a verified disk or Git diff, scan the workspace, infer shell effects, or persist a separate ledger.
|
||||
|
||||
|
||||
@@ -17,8 +17,10 @@ Interactive rows use semantic controls, keyboard activation, accessible names, v
|
||||
|
||||
ACP whole-turn timing uses localized unit formatting and localized running/completed labels in all four locales. It renders as persistent muted metadata in the assistant-turn footer; copy remains the hover-only action.
|
||||
|
||||
Multi-view file previews keep their localized segmented view switcher in the trailing side of the file name/path header instead of allocating a separate content row. HTML preview retains the `Preview` then `Source` order and defaults to the rendered preview.
|
||||
Multi-view file previews keep their localized segmented view switcher in the trailing side of the file name/path header instead of allocating a separate content row. The Chat Preview surface exposes a localized, icon-only fullscreen toggle in that header; fullscreen uses the whole Renderer viewport, preserves the selected target and viewer position, exits through the same control or Escape, and closes when Preview becomes inactive. HTML preview retains the `Preview` then `Source` order and defaults to the rendered preview.
|
||||
|
||||
Open With is eligible only for an available local assistant attachment whose primary mode is Preview, or for a created/modified workspace file-activity row; deleted activity and user, remote, unavailable, pending, or system-open-only attachments do not expose it. The compact secondary button stays inside the card's right edge as a sibling of the primary action; buttons must not be nested, visually segmented, or trigger one another. Eligible local HTML menus put the built-in Web Browser action first and follow it with a separator before native applications. Discovery starts on each menu open, stale responses cannot populate a changed target, reveal remains available during loading, and all valid application rows remain in a bounded scrolling menu with default-first then locale ordering. Operating-system application names are not translated. The Radix menu must support arrow navigation, Enter activation, Escape/outside dismissal, and trigger focus restoration. Open-with, built-in-browser, loading, platform reveal, and explicit action-failure labels require matching English, Chinese, Japanese, and Russian chat locale entries. Application rows use bounded native icons when available and a generic application icon for every missing, malformed, oversized, unreadable, or failed icon.
|
||||
Open With is eligible only for an available local assistant attachment whose primary mode is Preview, or for a created/modified workspace file-activity row; deleted activity and user, remote, unavailable, pending, or system-open-only attachments do not expose it. The compact secondary button stays inside the card's right edge as a sibling of the primary action; buttons must not be nested, visually segmented, or trigger one another. Eligible local HTML menus put the built-in Preview action first and follow it with a separator before native applications. Discovery starts on each menu open, stale responses cannot populate a changed target, reveal remains available during loading, and all valid application rows remain in a bounded scrolling menu with default-first then locale ordering. Operating-system application names are not translated. The Radix menu must support arrow navigation, Enter activation, Escape/outside dismissal, and trigger focus restoration. Open-with, built-in-preview, loading, platform reveal, and explicit action-failure labels require matching English, Chinese, Japanese, and Russian chat locale entries. Application rows use bounded native icons when available and a generic application icon for every missing, malformed, oversized, unreadable, or failed icon.
|
||||
|
||||
Every Web Browser icon-only control must have a localized accessible name and matching tooltip in English, Chinese, Japanese, and Russian through the `chat` namespace. Browser navigation and the project Radix menu use semantic focus, native disabled behavior, dismissal, and focus restoration; every More item has a Lucide icon, and the hidden browser host is non-interactive and absent from the accessibility tree. Hiding or crashing a focused guest moves focus back to application chrome. The combined title/address control keeps its full URL available to assistive technology without a hover URL tooltip; its non-editing title state reserves a fixed-size icon slot with either the page favicon or a decorative placeholder, and editing hides that slot.
|
||||
The HTML Preview external-open, fullscreen, and recovery controls require localized accessible names and matching tooltips where applicable in English, Chinese, Japanese, and Russian. The hidden HTML guest is non-interactive and absent from the accessibility tree.
|
||||
|
||||
Every content link is inert plain text. HTML Preview additionally removes guest anchor styling and pointer interaction while Main blocks all navigation. Local `.html` and `.htm` file cards open in the existing Preview tab by default.
|
||||
|
||||
@@ -1,28 +1,25 @@
|
||||
---
|
||||
id: web-browser-security-and-lifecycle
|
||||
title: Web Browser Security And Lifecycle
|
||||
type: ai-coding-rule
|
||||
title: Local HTML preview security and lifecycle
|
||||
appliesTo:
|
||||
- gateway-backend-communication
|
||||
- chat-workspace-and-navigation
|
||||
requiredProfiles:
|
||||
- e2e
|
||||
- shared/web-browser.ts
|
||||
- shared/host-api/contract.ts
|
||||
- electron/main/web-browser-policy.ts
|
||||
- electron/main/web-browser-session.ts
|
||||
- electron/services/web-browser-api.ts
|
||||
- src/components/web-browser/**
|
||||
- src/components/file-preview/**
|
||||
- src/stores/artifact-panel.ts
|
||||
severity: error
|
||||
---
|
||||
|
||||
`harness/reference/web-browser.md` is the authoritative implemented contract and rationale. Changes in this area must preserve these enforceable invariants:
|
||||
# Local HTML preview security and lifecycle
|
||||
|
||||
- Keep exactly one lazily created webview, one `WebBrowserGuestRegistry` owner, and hardcoded partition `persist:clawx-web-browser`. Do not add child BrowserWindows, BrowserViews, WebContentsViews, extra webviews, Renderer-selected partitions, persisted guest initialization, URL restoration, or history restoration.
|
||||
- Configure the dedicated Session before creating/loading the main window. Install embedder attachment listeners immediately after BrowserWindow construction, register typed Host API services before Renderer loading, and permit no attachment path that can race ahead of these policies.
|
||||
- Accept only the complete attachment identity: exact partition, initial `about:blank`, fixed UserAgent, boolean popup delivery, and empty preload. Reserve only one pending attachment, verify webview type and Session on attachment, and release ownership only after destruction.
|
||||
- Delete guest preload and force Node integration off in frames and workers, plugins and insecure content off, and context isolation, sandboxing, and web security on. Guest content must never receive the ClawX preload, host bridge, Electron globals, or Node globals.
|
||||
- Keep address completion in `parseWebBrowserAddress`, including `https://` completion for schemeless hosts and host plus numeric port. Main-facing normalization must not complete schemes or paths. User, recovery, main-frame navigation, redirect, popup, and external-open destinations may be only normalized `http:`, `https:`, or explicit hostless `file:///`; user/page `about:blank`, plain paths, hostful file URLs, and other protocols remain denied. Do not extend this top-level filter to ordinary subresources or subframe redirects.
|
||||
- Renderer application and recovery navigation must use the typed `hostApi.webBrowser.navigate` boundary and must not call direct IPC or `webview.loadURL()`. Main must load only the current registered guest. External opening takes no Renderer destination and validates the guest's current URL before `shell.openExternal`; never use `shell.openPath` for this feature.
|
||||
- Keep `WebBrowserHost` route-stable and mounted after initialization. Hidden panel, tab, session, route, missing-anchor, and zero-geometry states must preserve the guest while making the host invisible, pointer-inert, accessibility-hidden, and unfocusable. Geometry must track anchor resize, viewport/window resize, and scroll without integer rounding. Move focus out when hidden or crashed; do not suspend, mute, reload, unmount, or recreate for ordinary visibility changes.
|
||||
- Preserve toolbar race guards: active drafts survive page updates; Escape/blur cancel; invalid or rejected submissions remain editable; only the latest submission may close/refocus; one active navigation produces at most one load error; `ERR_ABORTED` remains silent; and stale clear completions never reload a replacement guest. Close the More menu when hidden or crashed.
|
||||
- Preserve favicon behavior: use the first reported favicon, retain it for same-origin/same-document navigation, clear it for cross-origin main-frame navigation/redirect, use a fixed-size placeholder when absent, and hide the slot while editing. Keep the full URL available to assistive technology and edit mode without a hover URL tooltip. Every More action retains an icon; all controls, errors, prompts, and tooltips use current four-locale resources and project design tokens.
|
||||
- Every popup handler must return `deny`. An allowed target may load only in the current registered guest. Do not claim or emulate guarantees for `window.opener`, returned handles, initially blank scripted popups, `_blank` POST/referrer fidelity, named windows, or window features.
|
||||
- Permission checks may allow only the documented clipboard variants. Permission requests may additionally allow media only after one non-persisted localized native decision for the current registered guest and request. Deny missing-window, empty/screen-only media, replaced/destroyed guest, dialog failure, geolocation, display capture, notifications, and every other permission. Install no display-media handler and remember no grants.
|
||||
- Clear Cookies must clear only cookies across the partition. Clear Site Data must clear HTTP cache, Cache Storage, Local Storage, IndexedDB, and Service Workers across the partition while preserving cookies and downloads. Refresh only the same attached guest generation after successful completion.
|
||||
- Downloads must retain Electron default download behavior: do not cancel, assign a path, suppress native UI, or add management state/UI. Keep the dedicated Session on system proxy resolution; do not mirror ClawX client proxy settings, call `setProxy`, or recycle its connections for client-proxy changes.
|
||||
- Non-aborted main-frame failures remain localized and non-destructive. Crash recovery must first remove/release the failed guest, require explicit user recovery, attach one replacement at `about:blank`, and only then navigate through the Host API to the last allowed URL. Never claim restoration of history, page/form state, favicon, or popup handles.
|
||||
- Retain adjacent policy-rationale comments for route-stable hidden mounting, lossy same-tab popup fallback, unconditional geolocation denial, untouched Electron download defaults, and the cross-platform fixed macOS-shaped UserAgent. Keep full rationale and limitations in the durable reference rather than duplicating them here.
|
||||
- Treat agent-produced HTML as untrusted. Keep one dedicated-session webview with no preload, Node integration, plugins, insecure content, popup capability, or ClawX bridge; require sandboxing, context isolation, and web security.
|
||||
- Application navigation may load only a hostless, query-free, fragment-free `file:///` URL whose path ends in `.html` or `.htm`. Renderer must derive it from an already validated attachment or Workspace reference and call the typed Host API.
|
||||
- The guest is a Preview implementation detail. Do not expose a Web Browser tab, Home page, address bar, history controls, site-data controls, general HTTP navigation, or an empty guest entry point.
|
||||
- Every link is inert. Inject user-origin CSS that removes anchor/area color, decoration, pointer cursor, and pointer events. Independently prevent all guest `will-frame-navigate`, redirect, invalid programmatic, in-page, form, and script navigation.
|
||||
- Deny every popup and every permission. Cancel downloads. Block HTTP(S), WebSocket, and other network requests in the dedicated Session, and reject any non-HTML main document.
|
||||
- Keep the single-guest registry and exact attachment identity gate. Main may load a validated HTML file or open an explicitly supplied, independently revalidated local HTML URL through `shell.openExternal`; no general web URL or storage-management API belongs to this feature.
|
||||
- The route-stable host may remain mounted while another panel tab is active, but it must be invisible, pointer-inert, accessibility-hidden, and unable to receive focus.
|
||||
- All visible labels and failures use the complete English, Chinese, Japanese, and Russian locale resources and project design tokens.
|
||||
|
||||
@@ -12,6 +12,7 @@ ownedPaths:
|
||||
- electron/services/attachment-access.ts
|
||||
- electron/services/attachment-open-with.ts
|
||||
- electron/services/files-api.ts
|
||||
- electron/main/index.ts
|
||||
- resources/scripts/attachment-open-with.ps1
|
||||
- src/lib/acp/**
|
||||
- src/lib/file-preview-client.ts
|
||||
@@ -27,12 +28,20 @@ ownedPaths:
|
||||
- tests/e2e/chat-acp-inline-timeline.spec.ts
|
||||
- tests/e2e/chat-acp-attachments.spec.ts
|
||||
- tests/e2e/chat-run-state-events.spec.ts
|
||||
- tests/e2e/chat-streamdown-rendering.spec.ts
|
||||
- tests/e2e/chat-code-block-wrap.spec.ts
|
||||
- tests/e2e/chat-latex-rendering.spec.ts
|
||||
- tests/e2e/chat-assistant-markdown-plain.spec.ts
|
||||
- tests/e2e/chat-table-header-light.spec.ts
|
||||
- tests/e2e/hardware-acceleration.spec.ts
|
||||
- tests/e2e/renderer-performance.spec.ts
|
||||
requiredProfiles:
|
||||
- fast
|
||||
- comms
|
||||
conditionalProfiles:
|
||||
e2e:
|
||||
- ACP timeline presentation changes
|
||||
- Chat Markdown rendering, syntax highlighting, or animation changes
|
||||
- send, cancel, permission, media, or history behavior changes
|
||||
requiredRules:
|
||||
- renderer-main-boundary
|
||||
@@ -44,12 +53,14 @@ requiredRules:
|
||||
- tool-derived-file-safety
|
||||
- office-preview-safety
|
||||
- ui-i18n-design-tokens
|
||||
- markdown-rendering-safety-and-performance
|
||||
- electron-rendering-performance
|
||||
- comms-regression
|
||||
- docs-sync
|
||||
---
|
||||
|
||||
ACP Chat covers session load, prompt, cancel, permission, replay, timeline reduction, assistant-turn presentation and whole-turn duration, standard ACP attachments, bounded generated-media and OpenClaw MEDIA compatibility, and Chat-specific diagnostics. The user-visible attachment flow includes attachment-scoped preview, system open, selected-application open, reveal actions, and a first-position built-in Web Browser action for eligible local HTML, with platform discovery limited to macOS and Windows. Authorized local DOCX/PPTX attachments within the Office limit use scoped Preview; remote, legacy, and over-limit Office attachments retain scoped system/external-open behavior.
|
||||
ACP Chat covers session load, prompt, cancel, permission, replay, timeline reduction, assistant-turn presentation and whole-turn duration, standard ACP attachments, bounded generated-media and OpenClaw MEDIA compatibility, and Chat-specific diagnostics. The user-visible attachment flow includes attachment-scoped preview, system open, selected-application open, reveal actions, and a first-position built-in Preview action for eligible local HTML, with platform discovery limited to macOS and Windows. Authorized local DOCX/PPTX attachments within the Office limit use scoped Preview; remote, legacy, and over-limit Office attachments retain scoped system/external-open behavior. User-selected directories remain system-open-only targets: Main may open the directory after session-scoped revalidation, but directory contents are not read, enumerated, previewed, or exposed to Open With.
|
||||
|
||||
Main owns ACP transport, routing, transcript retrieval and timing extraction, workspace grants, and session/generation-scoped attachment authorization. Renderer owns the in-memory timeline, bounded compatibility and timing alignment, attachment presentation, and display grouping, including user-image thumbnails and user-selected source-path labels. ACP replay remains authoritative for historical turns and content; transcript-derived timing may only annotate an unambiguously matched ACP turn. Standard ACP content remains preferred over compatibility projections, and incidental tool paths never enter the attachment pipeline.
|
||||
|
||||
The durable architecture, exceptions, access boundary, file-activity separation, Office preview behavior, and validation anchors are documented in `harness/reference/acp-chat.md`, `harness/reference/acp-generated-media-and-diagnostics.md`, `harness/reference/acp-attachment-access-control.md`, `harness/reference/openclaw-file-activity.md`, and `harness/reference/office-document-preview.md`.
|
||||
The durable architecture, exceptions, access boundary, file-activity separation, Office preview behavior, Markdown rendering, Electron rendering performance policy, and validation anchors are documented in `harness/reference/acp-chat.md`, `harness/reference/acp-generated-media-and-diagnostics.md`, `harness/reference/acp-attachment-access-control.md`, `harness/reference/openclaw-file-activity.md`, `harness/reference/office-document-preview.md`, `harness/reference/markdown-rendering.md`, and `harness/reference/electron-rendering-performance.md`.
|
||||
|
||||
@@ -31,6 +31,6 @@ requiredRules:
|
||||
- docs-sync
|
||||
---
|
||||
|
||||
This scenario covers per-turn file buttons and summaries, session-level Changes, replay, workspace-scoped Preview, and independently revalidated Open with actions for created or modified files from successful OpenClaw `write`, `edit`, and `apply_patch` calls. HTML Open with menus can also route the existing workspace path into the right-side Web Browser as a local file URL. In-limit DOCX/PPTX activity uses `WorkspaceFileRef` Preview under the Office safety contract. Deleted activity never exposes Preview or Open with.
|
||||
This scenario covers per-turn file buttons and summaries, session-level Changes, replay, workspace-scoped Preview, and independently revalidated Open with actions for created or modified files from successful OpenClaw `write`, `edit`, and `apply_patch` calls. HTML Open with menus route the existing workspace target into the right-side Preview tab. In-limit DOCX/PPTX activity uses `WorkspaceFileRef` Preview under the Office safety contract. Deleted activity never exposes Preview or Open with.
|
||||
|
||||
The UI represents tool-declared activity, not a verified filesystem or Git diff. Detailed input grammar, aggregation, and path safety are documented in `harness/reference/openclaw-file-activity.md`; Office parsing and lifecycle constraints are in `harness/reference/office-document-preview.md`.
|
||||
|
||||
@@ -6,11 +6,11 @@ ownedPaths:
|
||||
- shared/workspace.ts
|
||||
- shared/chat/session-title.ts
|
||||
- electron/services/sessions-api.ts
|
||||
- electron/main/index.ts
|
||||
- src/lib/workspace-context.ts
|
||||
- src/hooks/use-workspace-availability.ts
|
||||
- src/stores/settings.ts
|
||||
- src/stores/chat.ts
|
||||
- src/stores/chat/session-actions.ts
|
||||
- src/stores/chat/session-catalog.ts
|
||||
- src/stores/session-attention.ts
|
||||
- src/stores/chat/session-status.ts
|
||||
@@ -19,6 +19,7 @@ ownedPaths:
|
||||
- src/components/file-preview/ArtifactPanel.tsx
|
||||
- src/components/file-preview/WorkspaceBrowserBody.tsx
|
||||
- src/components/file-preview/FilePreviewBody.tsx
|
||||
- src/components/file-preview/MarkdownPreview.tsx
|
||||
- src/components/file-preview/DocxViewer.tsx
|
||||
- src/components/file-preview/PptxViewer.tsx
|
||||
- src/components/file-preview/build-preview-target.ts
|
||||
@@ -30,6 +31,7 @@ ownedPaths:
|
||||
- src/pages/Chat/AcpTurnFileActivity.tsx
|
||||
- src/pages/Chat/AcpAttachmentPart.tsx
|
||||
- src/components/web-browser/**
|
||||
- src/components/markdown/**
|
||||
- src/stores/artifact-panel.ts
|
||||
- src/components/layout/MainLayout.tsx
|
||||
- src/pages/Chat/ChatInput.tsx
|
||||
@@ -49,9 +51,10 @@ ownedPaths:
|
||||
- tests/unit/i18n-locale-parity.test.ts
|
||||
- tests/unit/session-buckets.test.ts
|
||||
- tests/unit/generated-files.test.ts
|
||||
- tests/unit/generated-files-panel.test.tsx
|
||||
- tests/unit/open-file-utils.test.ts
|
||||
- tests/unit/file-preview-body.test.tsx
|
||||
- tests/unit/markdown-preview.test.tsx
|
||||
- tests/unit/streamdown-config.test.tsx
|
||||
- tests/unit/workspace-browser-body.test.tsx
|
||||
- tests/unit/office-file-viewers.test.tsx
|
||||
- tests/unit/artifact-panel.test.tsx
|
||||
@@ -61,15 +64,18 @@ ownedPaths:
|
||||
- tests/e2e/chat-acp-inline-timeline.spec.ts
|
||||
- tests/e2e/chat-question-directory.spec.ts
|
||||
- tests/e2e/chat-sidebar-session-attention.spec.ts
|
||||
- tests/e2e/web-browser-navigation.spec.ts
|
||||
- tests/e2e/web-browser-lifecycle.spec.ts
|
||||
- tests/e2e/web-browser-policy.spec.ts
|
||||
- tests/e2e/chat-acp-attachments.spec.ts
|
||||
- tests/e2e/chat-file-changes.spec.ts
|
||||
- tests/e2e/office-document-preview.spec.ts
|
||||
- tests/e2e/markdown-file-preview.spec.ts
|
||||
- tests/e2e/hardware-acceleration.spec.ts
|
||||
- tests/e2e/renderer-performance.spec.ts
|
||||
requiredProfiles:
|
||||
- fast
|
||||
conditionalProfiles:
|
||||
e2e:
|
||||
- workspace selection, binding, sidebar, browser, or question navigation changes
|
||||
- Markdown file-preview rendering or syntax highlighting changes
|
||||
requiredRules:
|
||||
- session-workspace-authority
|
||||
- renderer-main-boundary
|
||||
@@ -77,11 +83,13 @@ requiredRules:
|
||||
- sidebar-session-attention-authority
|
||||
- office-preview-safety
|
||||
- web-browser-security-and-lifecycle
|
||||
- markdown-rendering-safety-and-performance
|
||||
- electron-rendering-performance
|
||||
- docs-sync
|
||||
---
|
||||
|
||||
This scenario covers inheriting the selected conversation's effective workspace when creating a new Chat; selecting persisted recent, known-session, or newly browsed workspaces while the new Chat remains unbound; validating workspace availability before ACP load; deriving a newly visible local-session title atomically from its first prompt; replacing matching synthetic UUID-date fallback titles with transcript prompts; recovering from deleted global or inherited workspace paths; marking unavailable non-default sidebar groups; permanently deleting their sessions after confirmation; binding workspaces through OpenClaw ACP cwd; targeting another agent without losing that agent's workspace or first prompt; restoring historical workspace context; renaming imported workspace display labels; navigating workspace-grouped sessions with busy, unread, and relative-time status; browsing the effective workspace; using the distinct persistent Web Browser artifact tab; previewing supported Office documents under the documented safety boundaries; and jumping among user questions.
|
||||
This scenario covers inheriting the selected conversation's effective workspace when creating a new Chat; selecting persisted recent, known-session, or newly browsed workspaces while the new Chat remains unbound; validating workspace availability before ACP load; deriving a newly visible local-session title atomically from its first prompt; replacing matching synthetic UUID-date fallback titles with transcript prompts; recovering from deleted global or inherited workspace paths; marking unavailable non-default sidebar groups; permanently deleting their sessions after confirmation; binding workspaces through OpenClaw ACP cwd; targeting another agent without losing that agent's workspace or first prompt; restoring historical workspace context; renaming imported workspace display labels; navigating workspace-grouped sessions with busy, unread, and relative-time status; browsing the effective workspace; previewing authorized local HTML and supported Office documents under their documented safety boundaries; and jumping among user questions from an overlay that leaves the conversation width unchanged.
|
||||
|
||||
Workspace file browsing keeps the store value `browser`; the Electron Web Browser uses `web-browser`. Its toolbar reserves a fixed-size favicon or placeholder slot only in the non-editing title state, omits the hover URL tooltip, and gives every More menu action an icon. Current workspace resolution, ordering, title normalization, and file-browser behavior are documented in `harness/reference/chat-workspace-and-navigation.md`; the Electron guest contract is documented in `harness/reference/web-browser.md`.
|
||||
Workspace file browsing keeps the store value `browser`; local HTML uses the existing `preview` tab and has no independent browser tab or toolbar. Current workspace resolution, ordering, title normalization, and file-browser behavior are documented in `harness/reference/chat-workspace-and-navigation.md`; the HTML guest contract is documented in `harness/reference/web-browser.md`; static Markdown rendering and safety requirements are documented in `harness/reference/markdown-rendering.md`; desktop compositing and interaction profiling requirements are documented in `harness/reference/electron-rendering-performance.md`.
|
||||
|
||||
DOCX and PPTX files are accepted as read-only inline previews only at or below the 20 MB compressed-input boundary. Scoped workspace and attachment references retain their authorized read route without naked-path fallback, while Workspace Browser retains its Host-validated absolute-path flow. PPTX visibility must preserve the single mounted PPTX viewer invariant across the kept-mounted Workspace and Preview surfaces. Workspace ownership remains in `harness/reference/chat-workspace-and-navigation.md`; the complete Office contract is `harness/reference/office-document-preview.md`.
|
||||
|
||||
@@ -21,7 +21,7 @@ ownedPaths:
|
||||
- tests/unit/session-catalog.test.ts
|
||||
- tests/unit/gateway-events.test.ts
|
||||
- tests/unit/gateway-event-dispatch.test.ts
|
||||
- tests/unit/chat-store-history-retry.test.ts
|
||||
- tests/unit/chat-session-management.test.ts
|
||||
- tests/unit/chat-store-session-label-fetch.test.ts
|
||||
- tests/unit/session-label-hydration.test.ts
|
||||
- tests/e2e/chat-sidebar-session-attention.spec.ts
|
||||
@@ -44,12 +44,14 @@ conditionalProfiles:
|
||||
- channels/agents/settings UI depends on new backend response shape
|
||||
- Web Browser guest, navigation, session, permission, or data policy changes
|
||||
requiredRules:
|
||||
- openclaw-config-delivery
|
||||
- renderer-main-boundary
|
||||
- backend-communication-boundary
|
||||
- api-client-transport-policy
|
||||
- host-api-fallback-policy
|
||||
- host-events-fallback-policy
|
||||
- gateway-readiness-policy
|
||||
- gateway-heartbeat-safety
|
||||
- channel-plugin-migration-guards
|
||||
- capability-owner-resolution
|
||||
- active-config-guards
|
||||
@@ -58,6 +60,7 @@ requiredRules:
|
||||
- provider-model-selection-authority
|
||||
- sidebar-session-attention-authority
|
||||
- web-browser-security-and-lifecycle
|
||||
- e2e-parallel-isolation
|
||||
- comms-regression
|
||||
- docs-sync
|
||||
forbiddenPatterns:
|
||||
@@ -75,6 +78,8 @@ forbiddenPatterns:
|
||||
|
||||
Gateway backend communication covers all ClawX paths that move data between the visual desktop UI and OpenClaw runtime/backend services.
|
||||
|
||||
Coordinator-owned OpenClaw config mutations and their `config.get`/`config.set` transaction contract are documented in `harness/reference/openclaw-config-delivery.md`.
|
||||
|
||||
Allowed flow:
|
||||
Renderer page/component -> `src/lib/host-api.ts` or `src/lib/api-client.ts` -> Electron Main typed host service or IPC handler -> Main-owned OpenClaw Gateway WebSocket -> runtime result -> store/UI.
|
||||
|
||||
@@ -82,8 +87,16 @@ Renderer code must not own transport selection, direct IPC channels, direct Gate
|
||||
|
||||
Renderer code must not create direct Gateway WebSocket connections. Gateway frame diagnostics must be emitted by Main-process Gateway logging.
|
||||
|
||||
Typed generic Gateway RPC requests are validated by `electron/services/gateway-api.ts` and delegated directly to `GatewayManager.rpc`, including an optional positive finite timeout. This path has no Renderer Chat history/send specialization, polling queue, coalescing, or backpressure layer. ACP `session/load`, `session/prompt`, and `session/cancel` own ordinary Chat history and composer behavior independently.
|
||||
|
||||
Channel/plugin migration behavior is also part of this scenario when ClawX rewrites OpenClaw config before Gateway launch. Upgrades must preserve single-owner channel registration for migrated plugin-backed channels such as Feishu/Lark.
|
||||
|
||||
The Web Browser privileged bridge is also Main-owned: Renderer address and recovery navigation, data clearing, and external opening flow through the typed Host API. The artifact tab value `web-browser` identifies this Electron guest and remains distinct from the Workspace file browser value `browser`; UI ownership stays in `chat-workspace-and-navigation`. The durable guest contract is `harness/reference/web-browser.md`.
|
||||
ClawX's prelaunch config sanitizer also owns desktop tool policy. It must keep `web_search` in both the agent-level and Gateway-level deny lists without replacing existing deny entries or disabling managed browser automation and `web_fetch`. It must also deny the agent-facing `gateway`, `nodes`, `create_goal`, `get_goal`, and `update_goal` tools at both layers while preserving application-owned Gateway RPCs. Messaging, session orchestration, and agent discovery tools remain available unless another explicit policy denies them.
|
||||
|
||||
Gateway session-catalog subscription, normalization, ordered list/event replay, attention transitions, and reconnect recovery are documented in `harness/reference/sidebar-session-attention.md`.
|
||||
Scheduled-task history is Main-owned backend data. Current OpenClaw versions must be queried through the Gateway `cron.runs` RPC; direct run-log file reads are allowed only as a compatibility fallback for older file-backed runtimes. When a run's bounded summary ends with OpenClaw's truncation ellipsis, Main may recover the complete final assistant reply from the run transcript identified by that `cron.runs` entry, but only when the transcript reply is longer and shares the entire summary prefix. When a cron base session has no ACP replay, Renderer may project that typed host result into a generation-scoped, in-memory historical ACP timeline, but must not replace or duplicate non-empty ACP replay.
|
||||
|
||||
The local HTML Preview privileged bridge is also Main-owned: Renderer may load a validated local HTML file or open that current file externally through the typed Host API. The guest is an implementation detail of the existing `preview` tab; there is no `web-browser` artifact tab or general address navigation. The durable guest contract is `harness/reference/web-browser.md`.
|
||||
|
||||
Gateway session-catalog subscription, normalization, ordered list/event replay, attention transitions, and reconnect recovery are documented in `harness/reference/sidebar-session-attention.md`. Electron test-process isolation and global-resource scheduling are documented in `harness/reference/e2e-parallelism.md`.
|
||||
|
||||
Gateway WebSocket heartbeat misses are diagnostic availability signals for the first three consecutive misses and must not interrupt long-running work during that window. A pong or any incoming Gateway message resets the sequence. On the fourth consecutive miss, Main may request the guarded Gateway restart path when auto-recovery is enabled and lifecycle state is still running; the heartbeat callback must not directly terminate the socket or process. Authoritative process-exit and socket-close signals retain their existing automatic lifecycle paths.
|
||||
|
||||
@@ -7,12 +7,12 @@ ownedPaths:
|
||||
- electron/utils/openclaw-auth.ts
|
||||
- electron/utils/paths.ts
|
||||
- src/stores/gateway.ts
|
||||
- src/pages/Dreams/**
|
||||
requiredProfiles:
|
||||
- fast
|
||||
- comms
|
||||
requiredRules:
|
||||
- gateway-readiness-policy
|
||||
- gateway-heartbeat-safety
|
||||
- renderer-main-boundary
|
||||
- backend-communication-boundary
|
||||
- api-client-transport-policy
|
||||
@@ -20,7 +20,7 @@ requiredRules:
|
||||
- docs-sync
|
||||
---
|
||||
|
||||
Use this spec when ClawX shows the Gateway as starting/running but UI data does not refresh, Dreams cannot load, or Gateway RPC calls time out after a restart.
|
||||
Use this spec when ClawX shows the Gateway as starting/running but UI data does not refresh, memory-backed data cannot load, or Gateway RPC calls time out after a restart.
|
||||
|
||||
ClawX should prefer OpenClaw-native signals over stderr string matching:
|
||||
|
||||
@@ -28,11 +28,13 @@ ClawX should prefer OpenClaw-native signals over stderr string matching:
|
||||
- `health` provides the Gateway health snapshot; use cached `probe:false` first.
|
||||
- `status` provides presence, health, stateVersion, uptime, and session defaults.
|
||||
- `channels.status` is the channel capability signal.
|
||||
- `doctor.memory.status` is the memory/dreams capability signal.
|
||||
- `doctor.memory.status` is the memory capability signal.
|
||||
- `gateway.ready`, `health`, and `presence` events should update ClawX's main-process capability cache.
|
||||
|
||||
stderr is supporting evidence only. It should not be the primary source for deciding whether the Gateway is ready, blocked, or should be restarted.
|
||||
|
||||
WebSocket heartbeat misses show that the Gateway control plane did not answer within the observation window. The first three consecutive misses remain diagnostic-only so transient pong delays do not interrupt long-running work. A pong or any incoming message resets the sequence. A fourth consecutive miss marks persistent unresponsiveness and may request the guarded Gateway restart path when auto-recovery is enabled and lifecycle state is still running. Process exit and socket close retain their existing automatic recovery paths.
|
||||
|
||||
## Failure Shape
|
||||
|
||||
Treat these as the same incident family until proven otherwise:
|
||||
@@ -43,7 +45,7 @@ Treat these as the same incident family until proven otherwise:
|
||||
- `[gateway-startup] Slow managed Gateway startup detected`
|
||||
- `[gateway:rpc] doctor.memory.status failed`
|
||||
- `[gateway:rpc] doctor.memory.dreamDiary failed`
|
||||
- `chat.history unavailable during gateway startup`
|
||||
- `sessions.list unavailable during gateway startup`
|
||||
- Port `18789` is listening, but Gateway HTTP or WebSocket RPC does not return.
|
||||
|
||||
Important distinction:
|
||||
@@ -58,7 +60,7 @@ Capability failures are not Gateway core failures:
|
||||
|
||||
- `doctor.memory.status` timeout means memory capability degraded until `system-presence` also fails.
|
||||
- `channels.status` timeout means channel capability degraded until `system-presence` also fails.
|
||||
- dreams cron unavailable, missing memory files, stale session keys, or provider credential errors do not trigger Gateway restart by themselves.
|
||||
- memory-core cron unavailable, missing memory files, stale session keys, or provider credential errors do not trigger Gateway restart by themselves.
|
||||
|
||||
## Fast Triage
|
||||
|
||||
@@ -189,14 +191,14 @@ Expected mitigation:
|
||||
|
||||
Symptoms:
|
||||
|
||||
- Gateway handshake completes, but `system-presence`, `chat.history`, or `doctor.memory.*` times out during the first minutes.
|
||||
- Gateway handshake completes, but `system-presence`, `sessions.list`, or `doctor.memory.*` times out during the first minutes.
|
||||
- Logs mention cron repair, channel account checks, session lock cleanup, memory-core cron reconciliation, or active embedded/task runs.
|
||||
|
||||
Expected behavior:
|
||||
|
||||
- Do not mark Gateway fully ready from a pure timer fallback.
|
||||
- The fallback must probe `system-presence` before emitting ready.
|
||||
- Heartbeat recovery may defer restart during the initial grace window, but it should not loop restart while the Gateway is still performing startup work.
|
||||
- Heartbeat misses remain observable during startup work; only ten uninterrupted misses may request guarded process recovery.
|
||||
|
||||
### Capability Degraded But Core Alive
|
||||
|
||||
@@ -204,7 +206,7 @@ Symptoms:
|
||||
|
||||
- `system-presence`, `health`, or `status` succeeds.
|
||||
- `doctor.memory.status`, `doctor.memory.dreamDiary`, or `channels.status` times out.
|
||||
- stderr may mention dreams cron unavailable, missing memory files, stale session keys, or credentials provider errors.
|
||||
- stderr may mention memory-core cron unavailable, missing memory files, stale session keys, or credentials provider errors.
|
||||
|
||||
Expected behavior:
|
||||
|
||||
@@ -266,7 +268,7 @@ pnpm exec openclaw gateway call health --params '{"probe":false}' >/tmp/clawx-he
|
||||
pnpm exec openclaw gateway call status >/tmp/clawx-status.json
|
||||
```
|
||||
|
||||
7. Only after `system-presence` succeeds, verify feature-specific RPCs such as Dreams, memory doctor calls, or channel probes.
|
||||
7. Only after `system-presence` succeeds, verify feature-specific RPCs such as memory doctor calls or channel probes.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
@@ -274,9 +276,9 @@ pnpm exec openclaw gateway call status >/tmp/clawx-status.json
|
||||
- `configSyncMs` stays small relative to total startup time.
|
||||
- `system-presence` succeeds after startup settles.
|
||||
- `health` and `status` are captured in Gateway diagnostics when available.
|
||||
- Dreams page can refresh once the Gateway process is running and RPC-ready.
|
||||
- `doctor.memory.status` and `doctor.memory.dreamDiary` return when Dreams is enabled.
|
||||
- Memory doctor calls return when the memory capability is available.
|
||||
- `doctor.memory.*` and `channels.status` failures degrade their capability only and do not trigger Gateway restart.
|
||||
- The first three consecutive heartbeat misses do not replace the Gateway process; the fourth records unresponsive diagnostics and requests one guarded restart when lifecycle auto-recovery is allowed.
|
||||
- Logs no longer repeat stale runtime cache or escaped managed-skill symlink warnings for entries ClawX can safely clean.
|
||||
|
||||
## Required Regression Coverage
|
||||
@@ -287,11 +289,10 @@ For fixes in this area, run:
|
||||
pnpm run typecheck
|
||||
pnpm run lint:check
|
||||
pnpm exec vitest run tests/unit/openclaw-auth.test.ts tests/unit/skills-symlink-cleanup.test.ts tests/unit/gateway-manager-heartbeat.test.ts tests/unit/gateway-ready-fallback.test.ts
|
||||
pnpm exec playwright test tests/e2e/openclaw-dreams.spec.ts
|
||||
pnpm run build:vite
|
||||
```
|
||||
|
||||
If the change touches Gateway send/receive, fallback, readiness, or chat history, also run:
|
||||
If the change touches Gateway send/receive, generic RPC dispatch, fallback, or readiness, also run:
|
||||
|
||||
```bash
|
||||
pnpm run comms:replay
|
||||
|
||||
@@ -104,7 +104,7 @@ The authoritative durable requirements are `harness/reference/acp-attachment-acc
|
||||
| Acceptance behavior | Test or durable rule |
|
||||
| --- | --- |
|
||||
| Deterministic handler normalization, presentation-only caching, 256/512/4096 and process/protocol bounds, icon degradation, sanitized environment, static JXA, SHA-256 Windows IDs, Main-owned association input, and post-ready invocation | `tests/unit/attachment-open-with.test.ts`, `attachment-access-safety` |
|
||||
| Real macOS and Windows native bridge validity, static bundled helper resolution, and packaged-resource identity | `tests/unit/attachment-open-with-native.test.ts`, `.github/workflows/check.yml`, `.github/workflows/release.yml` |
|
||||
| Real macOS and Windows native bridge validity, static bundled helper resolution, and packaged-resource identity; native CI smoke allows cold PowerShell compilation overhead while mocked service tests enforce the production process timeout | `tests/unit/attachment-open-with-native.test.ts`, `tests/unit/attachment-open-with.test.ts`, `.github/workflows/check.yml`, `.github/workflows/release.yml` |
|
||||
| Per-operation attachment authorization, generation revalidation, forged-handler rejection, scoped reveal, and sensitive diagnostic-payload exclusion | `tests/unit/attachment-access.test.ts`, `attachment-access-safety` |
|
||||
| Shared `AcpFileCard` sibling controls, exact attachment eligibility, lazy/repeated discovery, stale-result rejection, sorting, icon fallback, silent failure, localization, and keyboard interaction | `tests/unit/acp-chat-components.test.tsx`, `ui-i18n-design-tokens` |
|
||||
| End-to-end click routing, typed host requests, platform menu behavior, and failure isolation | `tests/e2e/chat-acp-attachments.spec.ts` |
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user