Compare commits

..
389 changed files with 48073 additions and 10257 deletions
+38
View File
@@ -0,0 +1,38 @@
# Local real cc-connect validation template.
# Save real values in .env.cc-connect.local. That file is gitignored.
# Required for real OAuth, packaged OAuth, and Feishu E2E paths.
# Point at the auth.json that may be copied into an isolated managed CODEX_HOME.
# Use ~/.codex/auth.json only when that import is intentional.
CLAWX_REAL_CODEX_AUTH_JSON=
# Required for OpenAI API-key provider/model chat validation.
# The verifier maps this to child-process OPENAI_API_KEY without writing the value to reports.
CLAWX_REAL_OPENAI_API_KEY=
# Optional: override the model used by the real OpenAI API-key smoke.
# Leave empty to use the test default.
CLAWX_REAL_OPENAI_MODEL=
# Optional: set OPENAI_API_KEY directly instead when external tools need the standard name.
# OPENAI_API_KEY=
# Required for Feishu/Lark live channel lifecycle validation.
CLAWX_REAL_FEISHU_APP_ID=
CLAWX_REAL_FEISHU_APP_SECRET=
# A real user/open_id accepted by the bot. The lifecycle test verifies that
# cc-connect preserves this admin together with ClawX's local bridge admin.
CLAWX_REAL_FEISHU_ADMIN_FROM=
# Optional Feishu/Lark settings.
# Values for CLAWX_REAL_FEISHU_DOMAIN: feishu, lark, cn, global, or a full API base URL.
CLAWX_REAL_FEISHU_DOMAIN=feishu
CLAWX_REAL_FEISHU_ACCOUNT_ID=real_feishu_bot
CLAWX_REAL_FEISHU_ALLOW_FROM=
# Optional manual Feishu/Lark inbound delivery smoke.
# Set this only when a sandbox tenant chat can send the marker to the configured bot
# while the E2E test is waiting.
CLAWX_REAL_FEISHU_INBOUND_E2E=
CLAWX_REAL_FEISHU_INBOUND_MARKER=
CLAWX_REAL_FEISHU_INBOUND_TIMEOUT_MS=180000
+1 -1
View File
@@ -118,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 tests/unit/safe-fs.test.ts
run: pnpm exec vitest run tests/unit/attachment-open-with.test.ts tests/unit/attachment-open-with-native.test.ts
- name: Generate extension bridge
run: pnpm run ext:bridge
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
electron-e2e:
name: Electron E2E (${{ matrix.os }})
runs-on: ${{ matrix.os }}
timeout-minutes: 20
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
+140 -8
View File
@@ -10,7 +10,7 @@ on:
workflow_dispatch:
inputs:
version:
description: 'Version to release (e.g., 1.0.0)'
description: 'Version label for an unsigned smoke build (e.g., 1.0.0-beta.smoke)'
required: true
permissions:
@@ -31,6 +31,7 @@ jobs:
release:
needs: validate-release
strategy:
fail-fast: false
matrix:
include:
- os: macos-latest
@@ -114,21 +115,43 @@ jobs:
if: matrix.platform == 'mac'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CSC_LINK: ${{ secrets.MAC_CERTS }}
CSC_KEY_PASSWORD: ${{ secrets.MAC_CERTS_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
CSC_IDENTITY_AUTO_DISCOVERY: ${{ github.event_name == 'workflow_dispatch' && 'false' || 'true' }}
CSC_LINK: ${{ github.event_name == 'push' && secrets.MAC_CERTS || '' }}
CSC_KEY_PASSWORD: ${{ github.event_name == 'push' && secrets.MAC_CERTS_PASSWORD || '' }}
APPLE_ID: ${{ github.event_name == 'push' && secrets.APPLE_ID || '' }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ github.event_name == 'push' && secrets.APPLE_APP_SPECIFIC_PASSWORD || '' }}
APPLE_TEAM_ID: ${{ github.event_name == 'push' && secrets.APPLE_TEAM_ID || '' }}
run: |
ulimit -n 65536
echo "File descriptor limit: $(ulimit -n)"
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
unset CSC_LINK CSC_KEY_PASSWORD APPLE_ID APPLE_APP_SPECIFIC_PASSWORD APPLE_TEAM_ID
fi
pnpm run package:mac
- name: Verify macOS packaged runtime resources
if: matrix.platform == 'mac'
run: |
pnpm run verify:packaged-runtime-resources -- --resources=release/mac/ClawX.app/Contents/Resources --platform=darwin --arch=x64
pnpm run verify:packaged-runtime-resources -- --resources=release/mac-arm64/ClawX.app/Contents/Resources --platform=darwin --arch=arm64
- name: Smoke native macOS packaged cc-connect runtime
if: matrix.platform == 'mac'
run: pnpm run smoke:cc-connect:packaged -- --allow-unsigned=${{ github.event_name == 'workflow_dispatch' && '1' || '0' }}
# Windows specific steps
- name: Build Windows
if: matrix.platform == 'win'
run: pnpm run package:win
- name: Verify Windows packaged runtime resources
if: matrix.platform == 'win'
run: pnpm run verify:packaged-runtime-resources -- --resources=release/win-unpacked/resources --platform=win32 --arch=x64
- name: Smoke native Windows packaged cc-connect runtime
if: matrix.platform == 'win'
run: pnpm run smoke:cc-connect:packaged
# Detect release channel from tag to skip code signing for alpha/beta builds
- name: Detect Windows release channel
if: matrix.platform == 'win'
@@ -276,6 +299,23 @@ jobs:
if: matrix.platform == 'linux'
run: pnpm run package:linux
- name: Verify Linux packaged runtime resources
if: matrix.platform == 'linux'
run: |
pnpm run verify:packaged-runtime-resources -- --resources=release/linux-unpacked/resources --platform=linux --arch=x64
pnpm run verify:packaged-runtime-resources -- --resources=release/linux-arm64-unpacked/resources --platform=linux --arch=arm64
- name: Smoke native Linux x64 packaged cc-connect runtime
if: matrix.platform == 'linux'
run: xvfb-run -a pnpm run smoke:cc-connect:packaged
- name: Upload native runtime smoke evidence
uses: actions/upload-artifact@v4
with:
name: runtime-smoke-${{ matrix.platform }}-native
path: artifacts/cc-connect/packaged-smoke-*.json
retention-days: 7
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
@@ -292,12 +332,103 @@ jobs:
!release/builder-debug.yml
retention-days: 7
runtime-smoke-macos-x64:
needs: validate-release
runs-on: macos-15-intel
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '24'
cache: 'pnpm'
- name: Prefer HTTPS for public GitHub git dependencies
run: |
git config --global "url.https://github.com/.insteadOf" "git@github.com:"
git config --global --add "url.https://github.com/.insteadOf" "ssh://git@github.com/"
- name: Install dependencies
run: pnpm install
- name: Build native macOS x64 unpacked app
env:
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
SKIP_PREINSTALLED_SKILLS: '1'
run: |
pnpm run package
node scripts/run-electron-builder.mjs --mac dir --x64 --publish never
- name: Verify and smoke native macOS x64 runtime
run: |
pnpm run verify:packaged-runtime-resources -- --resources=release/mac/ClawX.app/Contents/Resources --platform=darwin --arch=x64
pnpm run smoke:cc-connect:packaged -- --allow-unsigned=1
- name: Upload macOS x64 runtime smoke evidence
uses: actions/upload-artifact@v4
with:
name: runtime-smoke-macos-x64
path: artifacts/cc-connect/packaged-smoke-darwin-x64.json
retention-days: 7
runtime-smoke-linux-arm64:
needs: validate-release
runs-on: ubuntu-24.04-arm
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '24'
cache: 'pnpm'
- name: Prefer HTTPS for public GitHub git dependencies
run: |
git config --global "url.https://github.com/.insteadOf" "git@github.com:"
git config --global --add "url.https://github.com/.insteadOf" "ssh://git@github.com/"
- name: Install dependencies and X virtual framebuffer
run: |
pnpm install
sudo apt-get update
sudo apt-get install -y xvfb
- name: Build native Linux arm64 unpacked app
env:
SKIP_PREINSTALLED_SKILLS: '1'
run: |
pnpm run package
node scripts/run-electron-builder.mjs --linux dir --arm64 --publish never
- name: Verify and smoke native Linux arm64 runtime
run: |
pnpm run verify:packaged-runtime-resources -- --resources=release/linux-arm64-unpacked/resources --platform=linux --arch=arm64
xvfb-run -a pnpm run smoke:cc-connect:packaged
- name: Upload Linux arm64 runtime smoke evidence
uses: actions/upload-artifact@v4
with:
name: runtime-smoke-linux-arm64
path: artifacts/cc-connect/packaged-smoke-linux-arm64.json
retention-days: 7
# ──────────────────────────────────────────────────────────────
# Job: Publish to GitHub Releases
# ──────────────────────────────────────────────────────────────
publish:
needs: release
needs: [release, runtime-smoke-macos-x64, runtime-smoke-linux-arm64]
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/')
steps:
- name: Download release artifacts only
@@ -389,8 +520,9 @@ jobs:
# releases/vX.Y.Z/ → permanent archive, never deleted
# ──────────────────────────────────────────────────────────────
upload-oss:
needs: release
needs: [release, runtime-smoke-macos-x64, runtime-smoke-linux-arm64]
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/')
steps:
- name: Download release artifacts only
+71 -19
View File
@@ -93,6 +93,18 @@ ClawXは公式の**OpenClaw**コアを直接ベースに構築されています
私たちはアップストリームのOpenClawプロジェクトとの厳密な整合性を維持することにコミットしており、公式リリースが提供する最新の機能、安定性の改善、エコシステムの互換性に常にアクセスできることを保証します。
開発者モードを有効にし、OpenClaw が active runtime の場合、サイドバーにはネイティブの Dreams ページも表示され、ClawX 内で OpenClaw の記憶レビュー、夢日記、基本メンテナンス操作を扱えます。詳細な診断が必要な場合は、そのページから完全版の OpenClaw Dreams UI も開けます。
ClawX には runtime 抽象レイヤーもあります。OpenClaw は既定 runtime とロールバック経路のままで、**設定 → Gateway → Runtime** から任意の同梱 `cc-connect` runtime に切り替えられます。パッケージ版は cc-connect バイナリと OpenAI Codex ネイティブ CLI bundle の両方を app resources に含め、runtime 起動はグローバルインストール、PATH 上のバイナリ、起動時ダウンロードに依存しません。ClawX はアップグレード後も共有できる app config、credential、runtime data、skills、workspace を `~/.clawx`(または `CLAWX_DATA_HOME`)に保持し、`~/.cc-connect` を自動変更しません。GUI chat は cc-connect BridgePlatform 経由で Codex project agent に接続し、管理 project は cc-connect の Codex app-server stdio backend を使うため、リアルタイムの tool progress を共通 Chat execution graph へ直接反映できます。cc-connect の公開 history に channel session の tool packet がない場合、ClawX は所有する Agent の workspace に限定して一致するローカル Codex transcript から history を補完します。承認ボタンと cc-connect card の選択肢は実行グラフに表示され、応答はすべて cc-connect の公開 `card_action` プロトコルを通じて返されます。Runtime が生成した画像、ファイル、音声、動画の packet も BridgePlatform 経由で返り、Chat の添付として表示され続けます。各 Agent は既定でフルオートを使用し、Agent のモデル/runtime 設定で「承認を求める」(`suggest`)を個別に選択できます。新しい agent は `~/.clawx/workspaces/agents/<id>` を使い、既存の OpenClaw workspace は移動や所有権変更なしで元のパスを再利用できます。provider/model、native cron、enabled skills は管理された cc-connect/Codex runtime に同期されます。
Agent と channel の設定は `~/.clawx` を canonical source とします。cc-connect が active の間は保存しても `~/.openclaw/openclaw.json` を書き換えず、OpenClaw に戻すと Gateway 起動前に互換 projection を再生成します。
cc-connect mode では、Codex provider sync は OpenAI API key、OpenAI OAuth/Codex、Ollama、および Responses API を公開する OpenAI-compatible Custom provider をサポートします。Custom provider の header は環境変数参照として管理 config に書き込まれるため、secret や session header は永続化されません。Chat Completions として設定された Custom provider は、この経路が Codex の Responses wire API を使うため、chat 配信前に unsupported として報告されます。
OAuth provider account ごとに独立した管理 `CODEX_HOME` を持ちます。runtime 起動時にユーザーのグローバル Codex login を自動採用することはなく、選択した account に対する明示的な Codex OAuth import が必要です。
cc-connect はメッセージング platform bridge も担当します。cc-connect が active runtime の場合、channel status probe は OpenClaw Gateway に固定せず runtime abstraction 経由でルーティングされ、設定済み channel account はバインド先 agent を所有する cc-connect project にミラーされます。channel の保存や削除では cc-connect Management API で管理 config を reload し、可能な場合は完全な runtime restart なしで platform 変更を反映します。Developer Mode のサイドバーのページショートカットは cc-connect Web Admin を開き、OpenClaw Dreams ショートカットは OpenClaw runtime 専用のままです。
---
## 機能
@@ -101,18 +113,22 @@ ClawXは公式の**OpenClaw**コアを直接ベースに構築されています
インストールから最初のAIインタラクションまで、すべてのセットアップを直感的なグラフィカルインターフェースで完了できます。ターミナルコマンド不要、YAMLファイル不要、環境変数の探索も不要です。
### 💬 インテリジェントチャットインターフェース
モダンなチャット体験を通じてAIエージェントとコミュニケーションできます。複数の会話コンテキスト、メッセージ履歴、エージェント応答の Markdown レンダリング(GitHub 風テーブルや KaTeX による LaTeX 数式 `$インライン$``$$ブロック$$``\(インライン\)``\[ブロック\]` を含む)をサポートし、ユーザー入力は常にプレーンテキストとして表示します。さらに、マルチエージェント構成ではメイン入力欄の `@agent` から対象エージェントへ直接ルーティングできます。
モダンなチャット体験を通じて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` ファイルを読み取り専用でプレビューできます。プレビューのヘッダーから選択中のファイルを ClawX の表示領域全体に拡大でき、同じボタンまたは Esc で右パネルへ戻れます。従来形式の `.doc``.ppt` はアプリ内ではプレビューせず、引き続き OS 経由で開きます。DOCX のページ区切りは Microsoft Word と異なる場合があり、PPTX プレビューではアニメーション、画面切り替え、メディア再生をサポートしません。20 MB を超える Office ファイルはアプリ内でプレビューされません。
Chat の右パネルにあるワークスペースとプレビューの各タブでは、`.docx``.pptx` ファイルを読み取り専用でプレビューできます。従来形式の `.doc``.ppt` はアプリ内ではプレビューせず、引き続き OS 経由で開きます。DOCX のページ区切りは Microsoft Word と異なる場合があり、PPTX プレビューではアニメーション、画面切り替え、メディア再生をサポートしません。20 MB を超える Office ファイルはアプリ内でプレビューされません。
### ローカル HTML プレビュー
Chat の右パネルにはワークスペース、プレビュー、変更だけがあり、汎用ウェブブラウザ、ホーム画面、アドレスバーはありません。許可済みのローカル `.html` / `.htm` 添付ファイル、ファイルアクティビティ、ワークスペースファイルは既定でプレビューに開きます。ファイル操作では ClawX 内蔵プレビューまたはシステムアプリを選択でき、プレビューのヘッダーから現在の HTML ファイルをシステムブラウザで開くこともできます
### シングルページ Web ブラウザ
Chat の右パネルにはワークスペース、プレビュー、変更、ウェブブラウザの 4 タブがあります。ウェブブラウザは初回利用時に 1 つのライブページを遅延作成し、パネルを閉じる、別のパネルタブを選ぶ、チャットセッションを切り替える、または ClawX の別ルートへ移動しても、ページを非表示にするだけで実行を継続します。そのため、非表示中もスクリプト、ネットワーク通信、音声、リソース消費が続く場合があります。専用の永続セッションはアプリ再起動後も Cookie とサイトストレージを保持しますが、起動ごとに `about:blank` から始まり、以前の URL、ページ状態、ナビゲーション履歴は復元しません。ページが favicon を提供する場合はタイトルの左側に表示され、favicon がない間は同じサイズのプレースホルダーでタイトル位置を維持します。アドレス編集中はアイコン領域全体が非表示になります。追加のブラウザタブやウィンドウ、ブックマーク、履歴の永続化、パスワードマネージャー、自動入力管理はありません
すべてのリンクはクリックできません。ClawX が描画するリンクは通常のテキストとして表示され、HTML プレビュー内のリンクからもリンク装飾とポインター操作が除去されます。フォーム、スクリプトによる移動、リダイレクト、ページ内移動、ポップアップ、ダウンロード、ネットワーク要求、デバイス権限もブロックされます。自己完結したローカル HTML は表示できますが、選択中の文書から移動することはできません。
トップレベルナビゲーションでは 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チャネルを同時に設定・監視できます。各チャネルは独立して動作するため、異なるタスクに特化したエージェントを実行できます。
@@ -123,13 +139,14 @@ ClawX には Tencent 公式の個人 WeChat チャンネルプラグインも同
### ⏰ Cronベースの自動化
AIタスクを自動的に実行するようスケジュール設定できます。トリガーを定義し、間隔を設定することで、手動介入なしにAIエージェントを24時間稼働させることができます。
定期タスク画面では外部配信を「送信アカウント」と「受信先ターゲット」の 2 段階セレクターで設定できるようになりました。対応チャネルでは、受信先候補をチャネルのディレクトリ機能や既知セッション履歴から自動検出するため、`jobs.json` を手で編集する必要はありません。タスクのメッセージ入力欄でも、メインのチャット入力と同じインライン `/skill` トークン記法でスキルを挿入できるようになりました(選択中のエージェントに応じて読み込み)。スケジュールされたプロンプトから直接スキルを起動できます。スケジュール選択は**繰り返し**と**1回のみ**のタブに分かれました。繰り返しは毎時・毎日・平日・毎週・カスタム(生の cron)の頻度を時刻/曜日コントロール付きで選べ、1回のみは選択した日付(曜日を表示)と時刻に一度だけ実行します。1回のみのタスクは未来の時刻を指定する必要があり、実行後はランタイムにより自動的に削除されます。
定期タスクの実行中は、Gateway を情報源とする一時的なオーバーレイに進捗が表示されます。完了した会話内容の正本は引き続き ACP リプレイまたは定期タスク履歴であり、外部の定期タスク実行が Chat から停止またはキャンセルできる ACP プロンプトになることはありません
runtime が **今すぐ実行** を非同期で受け付ける場合、ClawX はトリガー確認をブロックせず、Cron カードに最新の完了結果が表示されるか、制限された停止条件に達するまで runtime 管理のジョブをバックグラウンド更新します
### 🧩 拡張可能なスキルシステム
事前構築されたスキルで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` エントリも一緒に掃除します。
cc-connect runtime が有効な場合、有効化されたローカル skills は app userData 配下の管理 Codex home にミラーされ、同梱 Codex agent がグローバル skill ディレクトリを読まずに同じ skill セットを使えます。
### 🔐 セキュアなプロバイダー統合
複数のAIプロバイダー(OpenAI、Anthropic、Z.AI / GLMなど)に接続でき、資格情報はシステムのネイティブキーチェーンに安全に保存されます。OpenAI は API キーとブラウザ OAuth(Codex サブスクリプション)の両方に対応しています。
@@ -138,7 +155,7 @@ OpenAI-compatible ゲートウェイを **Custom プロバイダー** で使う
プロバイダーの編集や切り替え時、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.AICN / Global)は OpenClaw 組み込みの `zai` プロバイダー(`ZAI_API_KEY`)に対応し、既定モデルは `glm-5.2` です。Code Plan プリセットで Coding Plan エンドポイント(`…/api/coding/paas/v4`)へ切り替え、通常 API`…/api/paas/v4`)も利用できます。CN と Global は同じ OpenClaw ランタイムキーを共有するため同時追加できません。
互換ゲートウェイで `/models` が認証以外の理由で使えない場合、ClawX は API キー検証時に設定済みモデルを使った軽量な `/chat/completions` または `/responses` プローブへ自動フォールバックします。
互換ゲートウェイで `/models` が認証以外の理由で使えない場合、ClawX は API キー検証時に軽量な `/chat/completions` または `/responses` プローブへ自動フォールバックします。
### 🌙 アダプティブテーマ
ライトモード、ダークモード、またはシステム同期テーマ。ClawXはあなたの好みに自動的に適応します。
@@ -191,7 +208,7 @@ ClawXを初めて起動すると、**セットアップウィザード**が以
### プロキシ設定
ClawXには、Electron、OpenClaw Gateway、またはTelegramなどのチャネルがローカルプロキシクライアントを介してインターネットにアクセスする必要がある環境向けに、組み込みのプロキシ設定が含まれています。
ClawXには、Electron、OpenClaw Gateway、任意の cc-connect/Codex runtime、またはTelegramなどのチャネルがローカルプロキシクライアントを介してインターネットにアクセスする必要がある環境向けに、組み込みのプロキシ設定が含まれています。
**設定 → ゲートウェイ → プロキシ**を開いて以下を設定します:
@@ -212,10 +229,11 @@ ClawXには、Electron、OpenClaw Gateway、またはTelegramなどのチャネ
- `host:port`のみの値はHTTPとして扱われます。
- 高度なプロキシフィールドが空の場合、ClawXは`プロキシサーバー`にフォールバックします。
- プロキシ設定を保存すると、Electronのネットワーク設定が即座に再適用され、ゲートウェイが自動的に再起動されます。
- cc-connect runtime モードでは、Codex 子プロセスが同じ `HTTP_PROXY``HTTPS_PROXY``ALL_PROXY`、バイパス環境値を継承します。
- ClawXはTelegramが有効な場合、プロキシをOpenClawのTelegramチャネル設定にも同期します。
- ClawXのプロキシが無効な状態では、Gatewayの通常再起動時に既存のTelegramチャネルプロキシ設定を保持します。
- OpenClaw設定のTelegramプロキシを明示的に消したい場合は、プロキシ無効の状態で一度「保存」を実行してください。
- **設定 → 詳細 → 開発者** では **OpenClaw Doctor** を実行でき、`openclaw doctor --json` の診断出力をアプリ内で確認できます。
- **設定 → 詳細 → 開発者** の Runtime Doctor は、OpenClaw では `openclaw doctor --json` を実行します。cc-connect では同梱の `cc-connect doctor user-isolation``codex doctor --json` を組み合わせ、モード 0600 の監査レポートを ClawX 管理の runtime ディレクトリへ保存します。Doctor Fix は OpenClaw 専用です。
- Windows のパッケージ版では、同梱された `openclaw` CLI/TUI は端末入力を安定させるため、同梱の `node.exe` エントリーポイント経由で実行されます。
---
@@ -224,20 +242,20 @@ ClawXには、Electron、OpenClaw Gateway、またはTelegramなどのチャネ
ClawXは、**デュアルプロセス + Host API 統一アクセス**構成を採用しています。Renderer は単一クライアント抽象を呼び出し、プロトコル選択とライフサイクルは Main が管理します:
Chat は Electron Main が所有する ACP stdio bridge を使用します。Renderer は型付き host event を受け取り、メモリ上の ACP timeline を描画します。Gateway は providers、models、skills、workspace、settings、diagnostics、media configuration などの非 Chat 機能を引き続き担当します。
Chat transport は active runtime に応じて切り替わりますが、Renderer の境界は 1 つに保たれます。OpenClaw Chat は Electron Main が所有する ACP stdio bridge を使用しRenderer は型付き host event を受け取ってメモリ上の ACP timeline を描画します。cc-connect Chat は `RuntimeManager` から cc-connect BridgePlatform 経由で dispatch され、session history、progress、approval、generated media も同じ経路を通ります。両モードで Renderer は同じ Host API facade を使い、Codex を直接呼び出しません。非 Chat 機能も runtime provider 経由で dispatch され、OpenClaw 固有操作は OpenClaw adapter 内に限定されます。
別の会話やページを開いても、未完了の 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 添付ファイルでは、そのメニューの先頭項目が右側のプレビューでファイルを開きます。ここでも Office プレビューには同じ制限があります。`.doc``.ppt` はシステムアプリで開く形式のままで、DOCX のページ区切りは Microsoft Word と異なる場合があり、PPTX のアニメーション、画面切り替え、メディア再生はサポートされません。対応アプリの検出は macOS と Windows のみで利用でき、Linux または検出失敗時には通知せず、ファイルの場所を表示する操作だけに切り替わります。それ以外のローカルファイル(20 MB を超える Office ファイルを含む)はユーザーのクリック後にシステムアプリで開かれます。ユーザーが選択したフォルダー添付も送信後に利用可能なまま保持され、クリックするとシステムのファイルマネージャーで開きます。ClawX はフォルダー内を読み取りまたはプレビューしません。リモートの HTTP/HTTPS 添付ファイルはクリック後に外部で開かれます。正規メディア情報がない通常の文章内単独またはインラインパスは添付ファイルとして扱われません。
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 ファイルでは、メニューの先頭項目が右側の**プレビュー**でファイルを開きます。削除された行には **Changes** 操作だけを残します。アプリ一覧、選択アプリで開く操作、ファイル位置の表示は、workspace ルートと相対パスから Electron Main が毎回個別に再検証します。ツール由来のパスが添付ファイルに変換されたり、Renderer に正規化済みのネイティブパスが渡されたりすることはありません。
- 作成・変更されたアクティビティ行は、プレビュー可能な assistant 添付ファイルと同じファイルカードと**アプリで開く**メニューを使い、状態表示と利用可能な `+/-` 集計も保持します。HTML ファイルでは、メニューの先頭項目がローカルファイル URL を右側の**ウェブブラウザ**で開き、そのタブを有効にします。削除された行には **Changes** 操作だけを残します。アプリ一覧、選択アプリで開く操作、ファイル位置の表示は、workspace ルートと相対パスから Electron Main が毎回個別に再検証します。ツール由来のパスが添付ファイルに変換されたり、Renderer に正規化済みのネイティブパスが渡されたりすることはありません。
- `write` はツールが宣言したとおり、作成および全行追加の差分として表示されます。対象パスがすでに存在する可能性がある場合も同様です。
- **Changes** は、ツールが宣言したアクティビティを時系列に並べたセッション単位の記録です。Git の出力でも、検証済みソースベースラインに対する差分でもありません。
- 各ファイルについて、Changes はアシスタントの各ターンに最大 1 つの diff エディターを表示します。安全に連結できるフラグメントは合成し、独立したフラグメントは 1 つのエディターに連結しますが、完全なファイルベースラインとの差分であるとはみなしません。
@@ -263,24 +281,24 @@ ACP Chat は、runtime が画像生成メディアを信頼できる構造化メ
│ │ • モダンなコンポーネントベースUI(React 19) │ │
│ │ • Zustandによるステート管理 │ │
│ │ • 統一 host-api/api-client 呼び出し │ │
│ │ • 応答はMarkdown、ユーザー入力はプレーンテキスト │ │
│ │ • リッチなMarkdownレンダリング │ │
│ └──────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬─────────────────────────────────────┘
│ 型付き IPC リクエスト
┌─────────────────────────────────────────────────────────────────┐
│ Main Host Services と Gateway Manager │
│ Main Host Services と Runtime Manager │
│ │
│ • host:invoke 型付きサービスディスパッチ │
│ • 設定、ファイル、セッション、スキル、プロバイダー、診断サービス │
│ • Main が Gateway WebSocket とプロセス監視を所有 │
│ • Runtime 選択、transport、プロセス監視を所有
└──────────────────────────────┬──────────────────────────────────┘
│ Main 所有 WebSocket
┌─────────────────────────────────────────────────────────────────┐
│ OpenClaw ゲートウェイ
│ OpenClaw Gateway 経路(図示)
│ │
│ • AIエージェントランタイムとオーケストレーション │
│ • メッセージチャネル管理 │
@@ -292,7 +310,7 @@ ACP Chat は、runtime が画像生成メディアを信頼できる構造化メ
- **プロセス分離**: AIランタイムは別プロセスで動作し、重い計算処理中でもUIの応答性を確保します
- **フロントエンド呼び出しの単一入口**: Renderer は host-api/api-client を通じて呼び出し、下位プロトコルに依存しません
- **Mainによるトランスポート制御**: ACP Chat stdio bridge と Gateway トランスポートは Electron Main が所有し、Renderer は型付き IPC で Main と通信します
- **Mainによるトランスポート制御**: OpenClaw ACP/Gateway transport と cc-connect BridgePlatform dispatch は Electron Main が所有し、Renderer は型付き IPC で Main と通信します
- **拡張 IPC コントリビューション**: Main プロセス拡張は HTTP route ではなく、型付き IPC レジストリを通じて host-api action を提供します
- **グレースフルリカバリ**: 再接続・タイムアウト・バックオフで一時的障害を自動処理します
- **セキュアストレージ**: APIキーや機密データは、OSのネイティブセキュアストレージ機構を活用します
@@ -301,10 +319,10 @@ ACP Chat は、runtime が画像生成メディアを信頼できる構造化メ
### プロセスモデルと Gateway トラブルシューティング
- ClawX は Electron アプリのため、**1つのアプリインスタンスでも複数プロセス(main/renderer/zygote/utility)が表示される**のが正常です。
- 単一起動保護は Electron のロックに加え、ローカルのプロセスロックファイルも併用し、デスクトップ IPC / セッションバスが不安定な環境でも重複起動を防ぎます。
- 単一起動保護は Electron のロックに加え、`~/.clawx/locks` 配下のインストール横断 writer lock も使用します。ClawX は共有データ初期化、移行、runtime、scheduler の起動前にこのロックを取得し、所有権を確認できない場合は起動を拒否します。
- ローリングアップグレード中に旧版/新版が混在すると、単一起動保護の挙動が非対称になる場合があります。安定運用のため、デスクトップクライアントは可能な限り同一バージョンへ揃えてください。
- ただし OpenClaw Gateway の待受は常に**単一**であるべきです。`127.0.0.1:18789` を Listen しているプロセスは1つだけです。
- Gateway の readiness は `system-presence``health``status` などの OpenClaw コア信号を基準にし、memory またはチャネルの失敗はグローバルな Gateway 障害ではなく capability degradation として表示します。
- 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`
@@ -368,6 +386,8 @@ AI を開発ワークフローに統合できます。エージェントを使
```
### 利用可能なコマンド
cc-connect の実環境検証はローカル env ファイルを読み込めますが、リポジトリ内の認証情報ファイルは gitignore されている必要があります。リポジトリ外の `--env-file` パスは利用でき、レポートには書き込まれません。`.env.cc-connect.local.example` は `.env.cc-connect.local` のフィールドテンプレートです。
```bash
# 開発
pnpm run init # 依存関係のインストール + バンドルバイナリ(uv、agent-browser)のダウンロード
@@ -380,10 +400,39 @@ pnpm typecheck # TypeScriptの型チェック
# テスト
pnpm test # ユニットテストを実行
pnpm run test:e2e # Electron E2E スモークテストを実行
pnpm run test:e2e:cc-connect:codex-oauth-lifecycle # 実認証情報なしで cc-connect Codex OAuth Host API の status/import/logout を検証
CLAWX_REAL_OAUTH_E2E=1 CLAWX_REAL_CODEX_AUTH_JSON="$HOME/.codex/auth.json" pnpm run test:e2e:cc-connect:real-oauth # 実 OAuth tool execution と Chat execution graph を検証
pnpm run test:e2e:headed # 表示付きウィンドウで Electron E2E を実行
pnpm run comms:replay # 通信リプレイ指標を算出
pnpm run comms:baseline # 通信ベースラインを更新
pnpm run comms:compare # リプレイ指標をベースライン閾値と比較
pnpm run verify:cc-connect:local-real # ローカル cc-connect 実環境検証の事前レポートを書き出す
pnpm run verify:cc-connect:local-real:run # 安全なローカル cc-connect 実環境検証を実行してレポートを書き出す
pnpm run verify:cc-connect:local-real:oauth # CLAWX_REAL_CODEX_AUTH_JSON に完全な refresh token フィールドがある場合、開発版 cc-connect の実 OAuth 総合スモークも実行
pnpm run verify:cc-connect:local-real:oauth-all # CLAWX_REAL_CODEX_AUTH_JSON に完全な refresh token フィールドがある場合、開発版とパッケージ版 cc-connect の実 OAuth スモークも実行
pnpm run verify:cc-connect:local-real:api-key # ローカル OpenAI-compatible API-key chat/abort スモークを実行し、認証情報がある場合は実 OpenAI API-key スモークも実行
pnpm run verify:cc-connect:local-real:feishu # 認証情報と CLAWX_REAL_CODEX_AUTH_JSON がある場合に実 Feishu/Lark ライフサイクルスモークも実行
pnpm run verify:cc-connect:local-real:feishu-inbound # サンドボックス tenant fixture が有効な場合に実 Feishu/Lark inbound marker スモークも実行
pnpm run verify:cc-connect:local-real:scheduled-cron # 実 native exec cron を実行し、Codex auth がある場合は public cc-connect session history で native prompt scheduling も検証
pnpm run verify:cc-connect:local-real:all # 利用可能なローカル cc-connect 実環境検証をすべて実行し、外部 gate handoff を書き出す
pnpm run verify:cc-connect:local-real:all-strict # リリース候補検証では全実認証情報と runtime parity coverage の PASS を必須にし、失敗前にも handoff を書き出す
pnpm run verify:cc-connect:local-real:replacement-ready # replacement readiness を必須にし、不足認証情報を別の事前失敗にはしない。失敗前にも handoff を書き出す
pnpm run verify:cc-connect:local-real:replacement-ready:check # 同じ readiness gate を実行し、前回のレポート成果物は上書きしない
pnpm run verify:cc-connect:local-real:packaged-oauth # CLAWX_REAL_CODEX_AUTH_JSON に完全な refresh token フィールドがある場合、パッケージ版 cc-connect の実 OAuth スモークも実行
pnpm run verify:cc-connect:local-real:external-gates:check # 残りの required external gates を非破壊で確認し、レポート成果物は上書きしない
pnpm run verify:cc-connect:local-real:external-gates # 残りの required external gates のみを実行し、3件すべて PASS の場合だけ成功
pnpm run verify:cc-connect:local-real:handoff # 残りの外部 gate 向けに認証情報を含まない handoff checklist を生成
# レポートは artifacts/cc-connect/local-real-validation-report.{json,md} に出力されます。
# :all、:all-strict、:replacement-ready、:external-gates、または :handoff は artifacts/cc-connect/local-real-external-gates.{md,json} に外部 gate handoff を出力します。
# JSON handoff は machine-readable で、sanitize 済みの status、env var 名、command、安全メモのみを含みます。
# runtimeMatrixStatus は pass/partial/fail の coverage と hard gate の終了状態を分けて表示します。
# --no-write、replacement-ready:check、または external-gates:check は非破壊の gate check に使えます。不足 precondition と次の command は秘密値なしで表示されます。
# validationGaps はローカル hard gate の不足と full parity に必要な follow-up evidence gap を分けて記録します。
# partial レポートには秘密値を含まない後続コマンドの Next Actions が含まれます。
# 実認証情報は、未追跡かつ gitignore 済みの .env.cc-connect.local、--env-file=<path>、
# または CLAWX_REAL_ENV_FILE / CLAWX_REAL_ENV_FILES で渡せます。明示的な process env が優先されます。
# API-key スモークでは、デフォルトモデルが利用できない場合に CLAWX_REAL_OPENAI_MODEL を設定できます。
# ビルド&パッケージ
pnpm run build:vite # フロントエンドのみビルド
@@ -392,6 +441,9 @@ pnpm package # 現在のプラットフォーム向けにパッケ
pnpm package:mac # macOS向けにパッケージ化
pnpm package:win # Windows向けにパッケージ化
pnpm package:linux # Linux向けにパッケージ化
pnpm run verify:runtime-bundles # ダウンロード済み cc-connect/Codex bundle の manifest とバイナリを検証
pnpm run verify:packaged-runtime-resources -- --resources=<path> --platform=<darwin|win32|linux> --arch=<x64|arm64> # 最終 Electron runtime resources を検証
pnpm run smoke:cc-connect:packaged # ネイティブ unpacked app を起動し、cc-connect の起動/状態/Cron/Doctor/ロールバック/クリーンアップを検証
```
ヘッドレス Linux では Electron テストに表示サーバーが必要です。`xvfb-run -a pnpm run test:e2e` を利用してください。
+71 -19
View File
@@ -93,6 +93,18 @@ ClawX is built directly upon the official **OpenClaw** core. Instead of requirin
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.
When Developer Mode is enabled and OpenClaw is the active runtime, 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.
ClawX also includes a runtime abstraction layer. OpenClaw remains the default runtime and rollback path, while **Settings → Gateway → Runtime** can switch to an optional bundled `cc-connect` runtime. Packaged builds include both the cc-connect binary and the native OpenAI Codex CLI bundle in app resources; runtime startup does not depend on global installs, PATH binaries, or app-time downloads. ClawX keeps upgrade-stable app config, credentials, runtime data, skills, and workspaces under `~/.clawx` (or `CLAWX_DATA_HOME`) instead of modifying `~/.cc-connect`. GUI chat connects through cc-connect BridgePlatform with Codex as the project agent; managed projects use cc-connect's Codex app-server backend over stdio so live tool progress can drive the shared Chat execution graph directly. When public cc-connect history omits tool packets for a channel-originated session, ClawX supplements that history from matching local Codex transcripts constrained to the owning Agent's workspace. Approval buttons and cc-connect card choices are rendered in that graph, and responses return through cc-connect's public `card_action` protocol. Runtime-generated image, file, audio, and video packets also return through BridgePlatform and remain visible as Chat attachments. Each Agent defaults to Full Auto and can independently select Ask for approval (`suggest`) in Agent model/runtime settings. New agents use `~/.clawx/workspaces/agents/<id>`; existing OpenClaw workspaces can be reused by reference without being moved or owned by ClawX. Provider/model selections, native cron tasks, and enabled skills are synchronized into the managed cc-connect/Codex runtime.
Agent and channel settings are canonical under `~/.clawx`. While cc-connect is active, saving them does not rewrite `~/.openclaw/openclaw.json`; switching back to OpenClaw rebuilds that compatibility projection before the Gateway starts.
In cc-connect mode, Codex provider sync supports OpenAI API key, OpenAI OAuth/Codex, Ollama, and Custom OpenAI-compatible providers that expose the Responses API. Custom provider headers are written as environment-variable references so secrets and session headers are not persisted in managed config files. Custom providers configured for Chat Completions are reported as unsupported before chat delivery because Codex accepts the Responses wire API for this path.
Each OAuth provider account has an isolated managed `CODEX_HOME`. An existing user-global Codex login is never adopted during runtime startup; importing it requires the explicit Codex OAuth import action for the selected account.
cc-connect also owns messaging platform bridges. When cc-connect is the active runtime, channel status probes are routed through the runtime abstraction instead of the OpenClaw Gateway, configured channel accounts are mirrored into the cc-connect project that owns their bound agent, and channel saves/deletes reload the managed cc-connect config through its Management API so platform changes take effect without a full runtime restart when possible. The Developer Mode sidebar page shortcut opens cc-connect Web Admin, while the OpenClaw Dreams shortcut remains OpenClaw-only.
---
## Features
@@ -101,18 +113,22 @@ We are committed to maintaining strict alignment with the upstream OpenClaw proj
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, assistant replies rendered with Markdown (including GitHub-flavored tables and KaTeX-powered LaTeX math: `$inline$`, `$$block$$`, `\(inline\)`, and `\[block\]`) while user input remains literal text, and direct `@agent` routing in the main composer for multi-agent setups.
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. The Preview header can expand the selected file to the full ClawX viewport; use the same control or 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.
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.
### Local HTML Preview
The Chat right panel has Workspace, Preview, and Changes tabs; it no longer includes 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. Their 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.
### 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.
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.
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.
@@ -123,13 +139,14 @@ ClawX now also bundles Tencent's official personal WeChat channel plugin, so you
### ⏰ 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.
While a cron task is running, Chat shows its progress in a transient Gateway-backed overlay. Completed conversation content still comes from authoritative ACP replay or cron history, and external cron activity never becomes an ACP prompt that can be stopped or cancelled from Chat.
When a runtime accepts **Run Now** asynchronously, ClawX keeps the trigger acknowledgement non-blocking and refreshes the runtime-owned job in the background until its latest completion result appears on the Cron card or a bounded stop condition is reached.
### 🧩 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.
When cc-connect runtime is active, enabled local skills are mirrored into the managed Codex home under app user data so the bundled Codex agent can use the same skill set without reading global skill directories.
### 🔐 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.
@@ -138,7 +155,7 @@ For **Custom** providers used with OpenAI-compatible gateways, you can set a cus
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 using the configured model during API key validation.
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.
@@ -194,7 +211,7 @@ The wizard preselects your system language when it is supported, and falls back
### 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 environments where Electron, the OpenClaw Gateway, the optional cc-connect/Codex runtime, or channels such as Telegram need to reach the internet through a local proxy client.
Open **Settings → Gateway → Proxy** and configure:
@@ -215,10 +232,11 @@ 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.
- In cc-connect runtime mode, Codex child processes inherit the same `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, and bypass environment values.
- 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.
- In **Settings → Advanced → Developer**, Runtime Doctor runs `openclaw doctor --json` for OpenClaw. For cc-connect it combines bundled `cc-connect doctor user-isolation` with bundled `codex doctor --json` and stores a mode-0600 audit under the ClawX-managed runtime directory. Doctor Fix remains OpenClaw-only.
- On packaged Windows builds, the bundled `openclaw` CLI/TUI runs via the shipped `node.exe` entrypoint to keep terminal input behavior stable.
---
@@ -227,20 +245,20 @@ Notes:
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:
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.
Chat transport follows the active runtime while preserving one renderer boundary. OpenClaw Chat uses an ACP stdio bridge owned by Electron Main; the renderer receives typed host events and renders an in-memory ACP timeline. cc-connect Chat is dispatched by `RuntimeManager` through cc-connect BridgePlatform, including session history, progress, approvals, and generated media. The renderer uses the same Host API facade in both modes and never invokes Codex directly. Non-Chat capabilities are also dispatched through runtime providers; OpenClaw-specific operations remain behind the OpenClaw adapter.
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, 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 also 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 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 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 Renderer.
- 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.
@@ -266,24 +284,24 @@ ACP Chat can also display generated image previews when image-generation media i
│ │ • Modern component-based UI (React 19) │ │
│ │ • State management with Zustand │ │
│ │ • Unified host-api/api-client calls │ │
│ │ • Markdown assistant replies, literal user input │ │
│ │ • Rich Markdown rendering │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬───────────────────────────────────┘
│ Typed IPC requests
┌──────────────────────────────────────────────────────────────────┐
Main Host Services & Gateway Manager │
│ Main Host Services & Runtime Manager
│ │
│ • host:invoke typed service dispatcher │
│ • Settings, files, sessions, skills, providers, diagnostics │
│ • Main-owned Gateway WebSocket and process supervision
│ • Runtime selection, transport, and process supervision │
└──────────────────────────────┬───────────────────────────────────┘
│ Main-owned WebSocket
┌──────────────────────────────────────────────────────────────────┐
OpenClaw Gateway
│ OpenClaw Gateway path (shown)
│ │
│ • AI agent runtime and orchestration │
│ • Message channel management │
@@ -295,7 +313,7 @@ ACP Chat can also display generated image previews when image-generation media i
- **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
- **Main-Process Transport Ownership**: Electron Main owns OpenClaw ACP/Gateway transports and cc-connect BridgePlatform dispatch; 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
@@ -304,10 +322,10 @@ ACP Chat can also display generated image previews when image-generation media i
### 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.
- Single-instance protection uses Electron's lock plus a cross-install writer lock under `~/.clawx/locks`. ClawX acquires that file lock before shared data initialization, migration, runtime, or scheduler startup and refuses to start if ownership cannot be established.
- 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 or channel failures are shown as capability degradation instead of global Gateway failure.
- 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`
@@ -371,6 +389,8 @@ Chain multiple skills together to create sophisticated automation pipelines. Pro
```
### Available Commands
Real cc-connect verification can load local env files, but repo-local credential files must be gitignored; external `--env-file` paths are allowed without being written to reports. Use `.env.cc-connect.local.example` as the field template for `.env.cc-connect.local`.
```bash
# Development
pnpm run init # Install dependencies + download bundled binaries (uv, agent-browser)
@@ -383,10 +403,39 @@ 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:cc-connect:codex-oauth-lifecycle # Verify cc-connect Codex OAuth Host API status/import/logout without real credentials
CLAWX_REAL_OAUTH_E2E=1 CLAWX_REAL_CODEX_AUTH_JSON="$HOME/.codex/auth.json" pnpm run test:e2e:cc-connect:real-oauth # Verify real OAuth tool execution and the Chat execution graph
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
pnpm run verify:cc-connect:local-real # Write a local cc-connect real-validation preflight report
pnpm run verify:cc-connect:local-real:run # Run safe local cc-connect real-validation checks and write the report
pnpm run verify:cc-connect:local-real:oauth # Also run dev cc-connect real OAuth comprehensive smoke when CLAWX_REAL_CODEX_AUTH_JSON has a complete refresh-token set
pnpm run verify:cc-connect:local-real:oauth-all # Also run dev and packaged cc-connect real OAuth smokes when CLAWX_REAL_CODEX_AUTH_JSON has a complete refresh-token set
pnpm run verify:cc-connect:local-real:api-key # Run local OpenAI-compatible API-key chat/abort smokes; also run real OpenAI API-key smoke when credentials are available
pnpm run verify:cc-connect:local-real:feishu # Also run real Feishu/Lark lifecycle smoke when credentials and CLAWX_REAL_CODEX_AUTH_JSON are available
pnpm run verify:cc-connect:local-real:feishu-inbound # Also run the manual real Feishu/Lark inbound marker smoke when the sandbox tenant fixture is enabled
pnpm run verify:cc-connect:local-real:scheduled-cron # Also run real native exec cron; with Codex auth, verify native prompt scheduling through public cc-connect session history
pnpm run verify:cc-connect:local-real:all # Run every available local real cc-connect validation path and write the external gate handoff
pnpm run verify:cc-connect:local-real:all-strict # Require all real credentials and runtime parity coverage for release-candidate validation; writes the handoff before failing
pnpm run verify:cc-connect:local-real:replacement-ready # Require replacement readiness without making missing credentials a separate preflight failure; writes the handoff before failing
pnpm run verify:cc-connect:local-real:replacement-ready:check # Same readiness gate without overwriting the last report artifacts
pnpm run verify:cc-connect:local-real:packaged-oauth # Also run packaged cc-connect real OAuth smoke when CLAWX_REAL_CODEX_AUTH_JSON has a complete refresh-token set
pnpm run verify:cc-connect:local-real:external-gates:check # Check remaining required external gates without overwriting report artifacts
pnpm run verify:cc-connect:local-real:external-gates # Run only the remaining required external gates and fail unless all three pass
pnpm run verify:cc-connect:local-real:handoff # Generate a credential-free handoff checklist for remaining external gates
# The report is written to artifacts/cc-connect/local-real-validation-report.{json,md};
# The external gate handoff is written to artifacts/cc-connect/local-real-external-gates.{md,json} by :all, :all-strict, :replacement-ready, :external-gates, or :handoff.
# The JSON handoff is machine-readable and contains only sanitized status, env-var names, commands, and safety notes.
# runtimeMatrixStatus shows pass/partial/fail coverage separately from hard-gate exit status.
# Use --no-write, replacement-ready:check, or external-gates:check for non-destructive gate checks; missing preconditions and next commands are printed without secret values.
# validationGaps records required local gate gaps separately from follow-up full-parity evidence gaps.
# partial reports include Next Actions with follow-up commands and no secret values.
# Real credentials can be supplied through untracked/gitignored .env.cc-connect.local,
# --env-file=<path>, or CLAWX_REAL_ENV_FILE / CLAWX_REAL_ENV_FILES; process env values win.
# API-key smoke can set CLAWX_REAL_OPENAI_MODEL when the default model is not available.
# Build & Package
pnpm run build:vite # Build frontend only
@@ -395,6 +444,9 @@ pnpm package # Package for current platform (includes bundled prein
pnpm package:mac # Package for macOS
pnpm package:win # Package for Windows
pnpm package:linux # Package for Linux
pnpm run verify:runtime-bundles # Verify downloaded cc-connect/Codex bundle manifests and binaries
pnpm run verify:packaged-runtime-resources -- --resources=<path> --platform=<darwin|win32|linux> --arch=<x64|arm64> # Verify final Electron runtime resources
pnpm run smoke:cc-connect:packaged # Launch the native unpacked app and verify cc-connect start/status/Cron/Doctor/rollback/cleanup
```
On headless Linux, run Electron tests under a display server such as `xvfb-run -a pnpm run test:e2e`.
+9 -5
View File
@@ -101,15 +101,19 @@ ClawX построен непосредственно на официально
Весь процесс — от установки до первого взаимодействия с AI — выполняется через интуитивный графический интерфейс. Без терминальных команд, без YAML-файлов, без поиска переменных окружения.
### 💬 Интеллектуальный интерфейс чата
Общайтесь с AI-агентами через современный чат. Поддержка нескольких контекстов разговора, истории сообщений и рендеринга ответов агента в Markdown (включая таблицы GitHub-flavored и математические формулы LaTeX через KaTeX: `$строчные$`, `$$блочные$$`, `\(строчные\)` и `\[блочные\]`), при этом пользовательский ввод всегда отображается как обычный текст. Для мультиагентных конфигураций также доступна прямая маршрутизация через `@agent` в главном поле ввода.
Общайтесь с AI-агентами через современный чат. Поддержка нескольких контекстов разговора, истории сообщений, рендеринга Markdown (включая таблицы GitHub-flavored и математические формулы LaTeX через KaTeX: `$строчные$`, `$$блочные$$`, `\(строчные\)` и `\[блочные\]`) и прямая маршрутизация через `@agent` в главном поле ввода для мультиагентных конфигураций.
Навыки, вставляемые из поля ввода, отображаются как чипы `/skill-name`; нажмите на чип, чтобы открыть боковую панель предпросмотра и прочитать `SKILL.md` соответствующего навыка.
При выборе другого агента через `@agent` ClawX переключается непосредственно в контекст этого агента вместо ретрансляции через агента по умолчанию. Рабочие пространства агентов по умолчанию разделены, но более строгая изоляция зависит от настроек песочницы OpenClaw.
Каждый агент может переопределить свои настройки `provider/model`; агенты без переопределения продолжают наследовать глобальную модель по умолчанию.
### Предпросмотр локального HTML
На правой панели Chat остаются только вкладки «Рабочая область», «Просмотр» и «Изменения»; универсального веб-браузера, домашней страницы и адресной строки больше нет. Разрешённые локальные вложения `.html` / `.htm`, файловые операции и файлы рабочей области по умолчанию открываются в «Просмотре». В действиях файла можно выбрать встроенный просмотр ClawX или системное приложение, а кнопка в заголовке просмотра открывает текущий HTML-файл в системном браузере.
### Одностраничный веб-браузер
На правой панели Chat находятся четыре вкладки: «Рабочая область», «Просмотр», «Изменения» и «Веб-браузер». При первом использовании веб-браузер лениво создаёт одну активную страницу и не останавливает её при закрытии панели, выборе другой вкладки панели, переключении сессии чата или переходе на другой маршрут ClawX; скрытая страница может продолжать выполнять скрипты, обращаться к сети, воспроизводить звук и расходовать ресурсы. Выделенная постоянная сессия сохраняет cookie и хранилища сайтов после перезапуска приложения, но каждый новый запуск начинается с `about:blank` без восстановления предыдущего URL, состояния страницы или истории переходов. Если страница предоставляет favicon, он отображается рядом с заголовком; пока favicon недоступен, заполнитель того же размера сохраняет положение заголовка, а при редактировании адреса вся область значка скрывается. Дополнительных вкладок или окон браузера, закладок, сохраняемой истории, менеджера паролей и управления автозаполнением нет.
Все ссылки некликабельны. Ссылки, отображаемые ClawX, выглядят как обычный текст; в HTML-просмотре также удаляются оформление ссылок и взаимодействие указателем. Формы, переходы из скриптов, перенаправления, переходы внутри страницы, всплывающие окна, загрузки, сетевые запросы и разрешения устройств блокируются. Самодостаточный локальный HTML отображается, но не может покинуть выбранный документ.
Навигация верхнего уровня принимает 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-каналов одновременно. Каждый канал работает независимо, позволяя запускать специализированных агентов для разных задач.
@@ -233,7 +237,7 @@ ClawX использует **двухпроцессную архитектуру
│ │ • Современный UI на компонентах (React 19) │ │
│ │ • Управление состоянием с Zustand │ │
│ │ • Унифицированные вызовы host-api/api-client │ │
│ │ • Ответы в Markdown, ввод как обычный текст │ │
│ │ • Рендеринг Markdown │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬──────────────────────────────────┘
+71 -19
View File
@@ -94,6 +94,18 @@ ClawX 直接基于官方 **OpenClaw** 核心构建。无需单独安装,我们
我们致力于与上游 OpenClaw 项目保持严格同步,确保你始终可以使用官方发布的最新功能、稳定性改进和生态兼容性。
打开开发者模式且当前 runtime 为 OpenClaw 时,侧边栏还会提供原生 Dreams 页面,可在 ClawX 内查看 OpenClaw 记忆回顾、梦境日记,并执行基础维护操作;需要更深诊断时仍可从该页面打开完整 OpenClaw Dreams UI。
ClawX 现在也包含 runtime 抽象层。OpenClaw 仍是默认 runtime 和回滚路径,你可以在 **设置 → 网关 → Runtime** 切换到可选的内置 `cc-connect` runtime。打包产物会同时内置 cc-connect 二进制和 OpenAI Codex 原生 CLI bundleruntime 启动不依赖全局安装、PATH 二进制或运行时下载。ClawX 会把可跨升级复用的 app 配置、凭据、runtime 数据、skills 和 workspace 放在 `~/.clawx`(或 `CLAWX_DATA_HOME`),不会自动修改 `~/.cc-connect`。GUI chat 会通过 cc-connect BridgePlatform 连接到 Codex project agent;托管 project 固定使用 cc-connect 的 Codex app-server stdio backend,让实时工具进度可以直接驱动共用的 Chat execution graph。当 cc-connect 公共历史缺少频道会话的工具数据包时,ClawX 会从匹配的本地 Codex transcript 补全历史,并将匹配范围限制在该会话所属 Agent 的 workspace。审批按钮和 cc-connect card 选项都会显示在执行图中,响应统一通过 cc-connect 公共 `card_action` 协议返回。Runtime 生成的图片、文件、音频和视频包也通过 BridgePlatform 返回,并持续显示为 Chat 附件。每个 Agent 默认使用全自动模式,也可以在 Agent 的模型/runtime 设置中独立选择“需要审批”(`suggest`)。新 agent 使用 `~/.clawx/workspaces/agents/<id>`;已有 OpenClaw workspace 可以按原路径复用,ClawX 不移动也不接管它。Provider/model、原生 cron 任务和已启用 skills 会同步到托管的 cc-connect/Codex runtime。
Agent 和频道设置以 `~/.clawx` 为唯一 canonical 数据源。cc-connect 处于启用状态时,保存设置不会改写 `~/.openclaw/openclaw.json`;切回 OpenClaw 后,Gateway 启动前会重新生成这份兼容投影。
在 cc-connect 模式下,Codex provider 同步支持 OpenAI API Key、OpenAI OAuth/Codex、Ollama,以及暴露 Responses API 的 OpenAI-compatible Custom provider。Custom provider header 会以环境变量引用写入托管配置,避免持久化密钥或 session header。配置为 Chat Completions 的 Custom provider 会在 chat 投递前被明确标记为不支持,因为这条路径使用 Codex 的 Responses wire API。
每个 OAuth provider account 都有独立的托管 `CODEX_HOME`。runtime 启动不会自动采用用户全局 Codex 登录;必须对选中的 account 显式执行 Codex OAuth 导入。
cc-connect 也负责消息平台桥接。当 cc-connect 是当前 runtime 时,频道状态探测会通过 runtime 抽象层路由,而不是继续固定查询 OpenClaw Gateway;已配置的频道账号会同步到其绑定 agent 所属的 cc-connect project,频道保存/删除会通过 cc-connect Management API reload 托管配置,在可行时无需完整重启 runtime 就让 platform 变更生效;开发者模式侧边栏的页面入口会打开 cc-connect Web AdminOpenClaw Dreams 入口仍只在 OpenClaw runtime 下显示。
---
## 功能特性
@@ -102,18 +114,22 @@ ClawX 直接基于官方 **OpenClaw** 核心构建。无需单独安装,我们
从安装到第一次 AI 对话,全程通过直观的图形界面完成。无需终端命令,无需 YAML 文件,无需到处寻找环境变量。
### 💬 智能聊天界面
通过现代化的聊天体验与 AI 智能体交互。支持多会话上下文、消息历史记录、Markdown 渲染智能体回复(包括 GitHub 风格表格以及由 KaTeX 渲染的 LaTeX 数学公式:`$行内$``$$块级$$``\(行内\)``\[块级\]`),用户输入则始终按原始文本显示;同时支持在多 Agent 场景下通过主输入框中的 `@agent` 直接路由到目标智能体。
通过现代化的聊天体验与 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` 文件。预览栏顶部可将当前文件展开至 ClawX 的整个可视区域;再次点击该按钮或按 Esc 即可返回侧栏。旧版 `.doc``.ppt` 文件不会在应用内预览,而是继续通过操作系统打开。DOCX 的分页效果可能与 Microsoft Word 不同;PPTX 预览不支持动画、切换效果或媒体播放。超过 20 MB 的 Office 文件不会在应用内预览。
Chat 右侧面板的工作空间和预览选项卡支持以只读方式预览 `.docx``.pptx` 文件。旧版 `.doc``.ppt` 文件不会在应用内预览,而是继续通过操作系统打开。DOCX 的分页效果可能与 Microsoft Word 不同;PPTX 预览不支持动画、切换效果或媒体播放。超过 20 MB 的 Office 文件不会在应用内预览。
### 本地 HTML 预览
Chat 右侧面板包含工作空间、预览变更,不再提供通用网页浏览器、主页或地址栏。已授权的本地 `.html``.htm` 附件、文件活动及工作空间文件默认在预览中打开。文件操作可以选择 ClawX 内置预览或系统应用,预览标题栏也可将当前 HTML 文件交给系统浏览器打开
### 单页面 Web 浏览器
Chat 右侧面板包含四个选项卡:工作空间、预览变更和网页浏览器。网页浏览器会在首次使用时延迟创建一个实时页面;关闭面板、切换面板选项卡、切换聊天会话或前往 ClawX 的其它路由时,页面只会隐藏并继续运行,因此脚本、网络活动、音频和资源占用都可能持续。专用持久会话会在应用重启后保留 Cookie 和站点存储,但每次启动都从 `about:blank` 开始,不恢复上次的 URL、页面状态或导航历史。页面提供网站图标时,图标会显示在标题左侧;没有图标时,同尺寸占位图标会保持标题对齐,编辑地址时则隐藏整个图标位。该功能不提供额外浏览器标签页或窗口、书签、持久化历史、密码管理器或自动填充管理
所有链接都不可点击。ClawX 渲染的链接显示为普通文本,HTML 预览中的链接也会移除链接样式和指针交互。HTML 预览同时阻止表单、脚本跳转、重定向、页内跳转、弹窗、下载、网络请求和设备权限;它可以显示自包含的本地 HTML,但无法离开当前选中的文档
顶层导航支持 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 频道。每个频道独立运行,允许你为不同任务运行专门的智能体。
@@ -124,13 +140,14 @@ ClawX 现在还内置了腾讯官方个人微信渠道插件,可直接在 Chan
### ⏰ 定时任务自动化
调度 AI 任务自动执行。定义触发器、设置时间间隔,让 AI 智能体 7×24 小时不间断工作。
现在定时任务页面已经可以直接配置外部投递,统一拆成“发送账号”和“接收目标”两个下拉选择。对于已支持的通道,接收目标会从通道目录能力或已知会话历史中自动发现,不需要再手动修改 `jobs.json`。任务的消息输入框也支持像主对话框那样以内联 `/skill` 令牌的方式插入技能(按所选智能体范围加载),让定时提示词可以直接触发技能。调度选择器现在分为**周期**和**单次**两个选项卡:周期支持每小时、每天、工作日、每周、自定义(原始 cron)等频率,并内置时间/星期选择;单次则在所选日期(显示星期)和时间执行一次。单次任务必须设置为未来时间,并会在执行完成后由运行时自动清除。
定时任务运行时,Chat 会通过由 Gateway 支持的临时浮层显示进度。已完成的对话内容仍以 ACP 重放或定时任务历史为权威来源,外部定时任务活动不会变成可在 Chat 中停止或取消的 ACP 提示词
当 runtime 异步接受**立即运行**时,ClawX 会保持触发确认非阻塞,并在后台刷新 runtime 自己管理的任务,直到 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` 中残留的旧配置一并移除。
当 cc-connect runtime 处于启用状态时,ClawX 会把已启用的本地 skills 镜像到 app userData 下托管的 Codex home 中,让内置 Codex agent 使用同一套技能,而不读取全局 skill 目录。
### 🔐 安全的供应商集成
连接多个 AI 供应商(OpenAI、Anthropic、Z.AI / GLM 等),凭证安全存储在系统原生密钥链中。OpenAI 同时支持 API Key 与浏览器 OAuthCodex 订阅)登录。
@@ -139,7 +156,7 @@ Skills 页面可展示来自多个 OpenClaw 来源的技能(托管目录、wor
编辑或切换 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` 探测。
如果兼容网关的 `/models` 因非鉴权原因不可用,ClawX 会在校验 API Key 时自动降级为轻量的 `/chat/completions``/responses` 探测。
### 🌙 自适应主题
支持浅色模式、深色模式或跟随系统主题。ClawX 自动适应你的偏好设置。
@@ -195,7 +212,7 @@ pnpm dev
### 代理设置
ClawX 内置了代理设置,适用于需要通过本地代理客户端访问外网的场景,包括 Electron 本身、OpenClaw Gateway,以及 Telegram 这类频道的联网请求。
ClawX 内置了代理设置,适用于需要通过本地代理客户端访问外网的场景,包括 Electron 本身、OpenClaw Gateway、可选的 cc-connect/Codex runtime,以及 Telegram 这类频道的联网请求。
打开 **设置 → 网关 → 代理**,配置以下内容:
@@ -216,10 +233,11 @@ ClawX 内置了代理设置,适用于需要通过本地代理客户端访问
- 只填写 `host:port` 时,会按 HTTP 代理处理。
- 高级代理项留空时,会自动回退到“代理服务器”。
- 保存代理设置后,Electron 网络层会立即重新应用代理,并自动重启 Gateway。
- 在 cc-connect runtime 模式下,Codex 子进程会继承同一组 `HTTP_PROXY``HTTPS_PROXY``ALL_PROXY` 和绕过规则环境变量。
- 如果启用了 TelegramClawX 还会把代理同步到 OpenClaw 的 Telegram 频道配置中。
- 当 ClawX 代理处于关闭状态时,Gateway 的常规重启会保留已有的 Telegram 频道代理配置。
- 如果你要明确清空 OpenClaw 中的 Telegram 代理,请在关闭代理后点一次“保存代理设置”。
-**设置 → 高级 → 开发者** 中,可以直接运行 **OpenClaw Doctor**,执行 `openclaw doctor --json` 并在应用内查看诊断输出
-**设置 → 高级 → 开发者** 中,Runtime Doctor 会在 OpenClaw 模式执行 `openclaw doctor --json`;在 cc-connect 模式组合执行内置的 `cc-connect doctor user-isolation``codex doctor --json`,并把权限为 0600 的审计报告写入 ClawX 托管 runtime 目录。Doctor Fix 仍只支持 OpenClaw
- 在 Windows 打包版本中,内置的 `openclaw` CLI/TUI 会通过随包分发的 `node.exe` 入口运行,以保证终端输入行为稳定。
---
@@ -228,20 +246,20 @@ ClawX 内置了代理设置,适用于需要通过本地代理客户端访问
ClawX 采用 **双进程 + Host API 统一接入架构**。渲染进程只调用统一客户端抽象,协议选择与进程生命周期由 Electron 主进程统一管理:
Chat 使用由 Electron Main 持有的 ACP stdio bridgeRenderer 接收类型化 host events并渲染内存中的 ACP timeline。Gateway 仍负责 providers、models、skills、workspace、settings、diagnostics 和 media configuration 等非 Chat 能力
Chat 传输会随当前 runtime 切换,但 Renderer 始终只经过同一个边界。OpenClaw Chat 使用由 Electron Main 持有的 ACP stdio bridgeRenderer 接收类型化 host events 并渲染内存中的 ACP timelinecc-connect Chat 则由 `RuntimeManager` 通过 cc-connect BridgePlatform 分派,包括 session history、progress、approval 与 generated media。两种模式都使用同一套 Host API facadeRenderer 不会直接调用 Codex。非 Chat 能力也通过 runtime provider 分派,OpenClaw 专属操作只保留在 OpenClaw adapter 内
打开其它会话或页面时,尚未完成的 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 会将标准 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 文件,菜单第一项会在右侧**预览**中打开文件;已删除的活动行只保留 **Changes** 操作。应用列表、指定应用打开和显示文件位置都会由 Electron Main 根据 workspace 根目录与相对路径分别重新验证;工具路径不会因此变成附件,Renderer 也不会获得规范化系统路径。
- 已创建和已修改的活动行与可预览的 assistant 附件共用同一种文件卡片外壳和**打开方式**菜单,同时保留状态文字及可用的 `+/-` 统计。对于 HTML 文件,菜单第一项会在右侧**网页浏览器**中打开本地文件 URL 并激活该选项卡;已删除的活动行只保留 **Changes** 操作。应用列表、指定应用打开和显示文件位置都会由 Electron Main 根据 workspace 根目录与相对路径分别重新验证;工具路径不会因此变成附件,Renderer 也不会获得规范化系统路径。
- `write` 按工具声明的语义显示:视为创建,并展示为全部新增的差异,即使该路径可能已经存在。
- **Changes** 是按时间顺序记录工具声明活动的会话级记录,不是 Git 输出,也不是相对于已验证源码基线的差异。
- 对每个文件,Changes 在每轮助手回复中最多展示一个 diff 编辑器。可安全串联的片段会合并,独立片段会拼接到同一个编辑器中,但不会被描述为基于完整文件基线的差异。
@@ -267,24 +285,24 @@ ACP Chat 也可在 runtime 以可信结构化媒体投递图像生成结果时
│ │ • 现代组件化 UI(React 19 │ │
│ │ • Zustand 状态管理 │ │
│ │ • 统一 host-api/api-client 调用 │ │
│ │ • 回复使用 Markdown,用户输入按原文显示 │ │
│ │ • Markdown 富文本渲染 │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────┬───────────────────────────────────┘
│ 类型化 IPC 请求
┌─────────────────────────────────────────────────────────────────┐
│ 主进程 Host Services 与 Gateway Manager │
│ 主进程 Host Services 与 Runtime Manager │
│ │
│ • host:invoke 类型化服务分发 │
│ • 设置、文件、会话、技能、供应商、诊断服务 │
│ • 主进程持有 Gateway WebSocket 并负责进程监控
│ • Runtime 选择、传输与进程监控
└──────────────────────────────┬──────────────────────────────────┘
│ 主进程持有 WebSocket
┌─────────────────────────────────────────────────────────────────┐
│ OpenClaw 网关
│ OpenClaw 网关路径(图示)
│ │
│ • AI 智能体运行时与编排 │
│ • 消息频道管理 │
@@ -296,7 +314,7 @@ ACP Chat 也可在 runtime 以可信结构化媒体投递图像生成结果时
- **进程隔离**:AI 运行时在独立进程中运行,确保即使在高负载计算期间 UI 也能保持响应
- **前端调用单一入口**:渲染层统一走 host-api/api-client,不感知底层协议细节
- **主进程掌控传输策略**ACP Chat stdio bridge 与 Gateway 传输都由 Electron Main 持有,渲染进程通过类型化 IPC 调用 Main
- **主进程掌控传输策略**OpenClaw ACP/Gateway 传输与 cc-connect BridgePlatform 分派都由 Electron Main 持有,渲染进程通过类型化 IPC 调用 Main
- **扩展 IPC 贡献点**:主进程扩展通过类型化 IPC 注册表贡献 host-api action,而不是挂载 HTTP route
- **优雅恢复**:内置重连、超时、退避逻辑,自动处理瞬时故障
- **安全存储**:API 密钥和敏感数据利用操作系统原生的安全存储机制
@@ -305,10 +323,10 @@ ACP Chat 也可在 runtime 以可信结构化媒体投递图像生成结果时
### 进程模型与 Gateway 排障
- ClawX 基于 Electron,**单个应用实例出现多个系统进程是正常现象**main/renderer/zygote/utility)。
- 单实例保护同时使用 Electron 自带锁与本地进程文件锁回退机制,可在桌面会话总线异常时避免重复启动。
- 单实例保护同时使用 Electron 自带锁`~/.clawx/locks` 下的跨安装 writer lock。ClawX 会在共享数据初始化、迁移、runtime 或 scheduler 启动前取得文件锁;无法确认所有权时会拒绝启动。
- 滚动升级期间若新旧版本混跑,单实例保护仍可能出现不对称行为。为保证稳定性,建议桌面客户端尽量统一升级到同一版本。
- 但 OpenClaw Gateway 监听应始终保持**单实例**:`127.0.0.1:18789` 只能有一个监听者。
- Gateway readiness 以 OpenClaw 的 `system-presence``health``status` 等核心信号为准;memory 或频道失败会显示为能力降级,而不是全局 Gateway 故障。
- Gateway readiness 以 OpenClaw 的 `system-presence``health``status` 等核心信号为准;memory、Dreams 或频道失败会显示为能力降级,而不是全局 Gateway 故障。
- 可用以下命令确认监听进程:
- macOS/Linux`lsof -nP -iTCP:18789 -sTCP:LISTEN`
- WindowsPowerShell):`Get-NetTCPConnection -LocalPort 18789 -State Listen`
@@ -372,6 +390,8 @@ ACP Chat 也可在 runtime 以可信结构化媒体投递图像生成结果时
```
### 常用命令
cc-connect 真实验证可以加载本地 env 文件,但仓库内的凭据文件必须被 gitignore;仓库外 `--env-file` 路径可以使用且不会写入报告。`.env.cc-connect.local.example` 是 `.env.cc-connect.local` 的字段模板。
```bash
# 开发
pnpm run init # 安装依赖并下载捆绑二进制(uv、agent-browser
@@ -384,10 +404,39 @@ pnpm typecheck # TypeScript 类型检查
# 测试
pnpm test # 运行单元测试
pnpm run test:e2e # 运行 Electron E2E 冒烟测试
pnpm run test:e2e:cc-connect:codex-oauth-lifecycle # 无需真实凭证验证 cc-connect Codex OAuth Host API 状态/导入/登出
CLAWX_REAL_OAUTH_E2E=1 CLAWX_REAL_CODEX_AUTH_JSON="$HOME/.codex/auth.json" pnpm run test:e2e:cc-connect:real-oauth # 验证真实 OAuth 工具执行和 Chat execution graph
pnpm run test:e2e:headed # 以可见窗口运行 Electron E2E 测试
pnpm run comms:replay # 计算通信回放指标
pnpm run comms:baseline # 刷新通信基线快照
pnpm run comms:compare # 将回放指标与基线阈值对比
pnpm run verify:cc-connect:local-real # 写入本地 cc-connect 真实验证前置报告
pnpm run verify:cc-connect:local-real:run # 执行安全的本地 cc-connect 真实验证检查并写入报告
pnpm run verify:cc-connect:local-real:oauth # CLAWX_REAL_CODEX_AUTH_JSON 包含完整 refresh token 字段时额外执行开发版 cc-connect 真实 OAuth 综合冒烟
pnpm run verify:cc-connect:local-real:oauth-all # CLAWX_REAL_CODEX_AUTH_JSON 包含完整 refresh token 字段时额外执行开发版和打包版 cc-connect 真实 OAuth 冒烟
pnpm run verify:cc-connect:local-real:api-key # 执行本地 OpenAI-compatible API-key chat/abort 冒烟;有真实凭证时额外执行真实 OpenAI API-key 冒烟
pnpm run verify:cc-connect:local-real:feishu # 有凭证和 CLAWX_REAL_CODEX_AUTH_JSON 时额外执行真实飞书/Lark 生命周期冒烟
pnpm run verify:cc-connect:local-real:feishu-inbound # 沙箱租户入站 fixture 启用时额外执行真实飞书/Lark inbound marker 冒烟
pnpm run verify:cc-connect:local-real:scheduled-cron # 执行真实原生 exec cron;有 Codex auth 时通过 cc-connect public session history 验证原生 prompt 调度
pnpm run verify:cc-connect:local-real:all # 执行所有可用的本地 cc-connect 真实验证路径,并写入外部门禁交接清单
pnpm run verify:cc-connect:local-real:all-strict # 发布候选验证要求所有真实凭证和 runtime parity 覆盖都通过;失败前也会写入交接清单
pnpm run verify:cc-connect:local-real:replacement-ready # 要求 replacement readiness 通过,但不把缺失凭证单独作为前置失败;失败前也会写入交接清单
pnpm run verify:cc-connect:local-real:replacement-ready:check # 同样检查 readiness,但不覆盖上一次报告产物
pnpm run verify:cc-connect:local-real:packaged-oauth # CLAWX_REAL_CODEX_AUTH_JSON 包含完整 refresh token 字段时额外执行打包版 cc-connect 真实 OAuth 冒烟
pnpm run verify:cc-connect:local-real:external-gates:check # 非破坏性检查剩余 required external gates,不覆盖报告产物
pnpm run verify:cc-connect:local-real:external-gates # 只运行剩余 required external gates,三项全部通过才成功
pnpm run verify:cc-connect:local-real:handoff # 生成不含凭证的剩余外部门禁交接清单
# 报告写入 artifacts/cc-connect/local-real-validation-report.{json,md}
# :all、:all-strict、:replacement-ready、:external-gates 或 :handoff 会把外部门禁交接清单写入 artifacts/cc-connect/local-real-external-gates.{md,json}。
# JSON 交接清单可供机器读取,只包含清洗后的状态、环境变量名、命令和安全说明。
# runtimeMatrixStatus 会把 pass/partial/fail 覆盖状态和硬门禁退出状态分开展示。
# 使用 --no-write、replacement-ready:check 或 external-gates:check 做非破坏性门禁检查;缺失前置条件和下一步命令会以不含密钥值的形式打印。
# validationGaps 会区分本地硬门禁缺口和完整替代所需的 follow-up 证据缺口。
# partial 报告会包含 Next Actions,列出后续命令且不写入密钥值。
# 真实凭证可通过未跟踪且已 gitignore 的 .env.cc-connect.local、--env-file=<path>、
# 或 CLAWX_REAL_ENV_FILE / CLAWX_REAL_ENV_FILES 提供;显式进程环境变量优先。
# API-key 冒烟在默认模型不可用时可设置 CLAWX_REAL_OPENAI_MODEL。
# 构建与打包
pnpm run build:vite # 仅构建前端
@@ -396,6 +445,9 @@ pnpm package # 为当前平台打包(包含预装技能资源)
pnpm package:mac # 为 macOS 打包
pnpm package:win # 为 Windows 打包
pnpm package:linux # 为 Linux 打包
pnpm run verify:runtime-bundles # 校验下载的 cc-connect/Codex bundle manifest 与二进制
pnpm run verify:packaged-runtime-resources -- --resources=<路径> --platform=<darwin|win32|linux> --arch=<x64|arm64> # 校验最终 Electron runtime resources
pnpm run smoke:cc-connect:packaged # 启动当前平台 unpacked app,验证 cc-connect 启动/状态/Cron/Doctor/回滚/清理
```
在无头 Linux 环境下,Electron 测试需要显示服务;可使用 `xvfb-run -a pnpm run test:e2e`。
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

@@ -1,578 +0,0 @@
# Cron Live Run Overlay Implementation Plan
> **For agentic workers:** Use `subagent-driven-development` to implement this plan task-by-task. Use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Render live cron-run progress in ACP Chat without converting Gateway runtime events into ACP notifications or persisting them in the ACP timeline.
**Architecture:** Electron Main owns a bounded, memory-only cron live-run broker. It canonicalizes run-scoped cron keys, deduplicates and reduces Gateway runtime events into an explicit non-ACP overlay snapshot, publishes typed host events, and serves a race-safe snapshot for late subscribers. Renderer keeps that overlay separate from `AcpTimelineSnapshot`; when a visible run terminates, it removes the overlay and reloads the authoritative ACP/cron history exactly once.
**Tech Stack:** Electron Main, TypeScript, Zustand, React 19, typed host-api/host-events, Vitest, Playwright, react-i18next, Harness communication specs.
## Global Constraints
- Gateway runtime events must never be converted into `SessionNotification`, `AcpSessionUpdateEnvelope`, or `TimelineItem` objects.
- `src/lib/acp/reducer.ts`, `src/lib/acp/timeline-types.ts`, and ACP replay semantics remain unchanged.
- ACP `sending`, `cancelling`, Stop behavior, and `cancelAcpSession` remain owned exclusively by ACP prompts initiated by ClawX.
- The overlay accepts only strict run-scoped cron keys shaped as `agent:<agentId>:cron:<jobId>:run:<runSessionId>`; ordinary sessions, base-only cron keys, channel sessions, and heartbeat `:main` events are rejected.
- Main is the sole owner of cron key canonicalization, runtime-event deduplication, memory bounds, and active-run snapshots. Renderer must not reimplement protocol switching or Gateway event reduction.
- Keep raw `chat:runtime-event` forwarding unchanged for the existing legacy runtime graph and image-generation compatibility consumers.
- Display assistant text, but do not display raw `thinking.delta` text. The overlay exposes only a localized running/thinking indicator.
- Runtime approval events are read-only status rows. They must not call ACP permission response APIs.
- A terminal overlay is never treated as history. Completed content appears only after normal `loadAcpSession` replay or the existing typed cron-history fallback.
- Use these exact broker bounds:
- `MAX_ACTIVE_CRON_LIVE_RUNS = 32`
- `MAX_CRON_LIVE_ITEMS_PER_RUN = 128`
- `MAX_CRON_LIVE_ASSISTANT_CHARS = 500_000`
- `MAX_CRON_LIVE_ITEM_DETAIL_CHARS = 100_000`
- `MAX_CRON_LIVE_EVENT_FINGERPRINTS = 256` per run
- `MAX_CRON_LIVE_TERMINAL_TOMBSTONES = 128`
- Numeric sequence values are monotonic per run: reject `seq <= lastSeq`. Sequence-less events use bounded type-specific fingerprints; reject exact repeats but retain distinct incremental chunks.
- Namespace every process item identity by `runId` so repeated `toolCallId`, `itemId`, command names, or approval fallbacks cannot collide across runs.
- Main emits a monotonically increasing broker `revision`. Renderer subscribes before fetching the snapshot and ignores snapshots or changes older than its current revision.
- All new display text must be translated in `en`, `zh`, `ja`, and `ru` and use existing design tokens from `src/styles/globals.css`.
- Update the checked-in task spec before implementation. Because this changes backend communication, run Harness validation, communication replay/compare, and Electron E2E before completion.
- Do not commit unless the user explicitly requests it. Each task lists a commit point only for a later explicitly requested commit workflow.
---
### Task 1: Update the architecture contract before code
**Files:**
- Modify: `harness/specs/tasks/render-cron-run-live-status.md`
- Modify: `harness/specs/scenarios/gateway-backend-communication.md`
- Modify: `harness/specs/scenarios/acp-chat-experience.md`
- Modify: `harness/specs/rules/acp-chat-state-and-history.md`
- Modify: `harness/specs/rules/acp-compatibility-content-safety.md`
- Create: `harness/reference/acp-cron-live-overlay.md`
- Test: `tests/unit/harness-specs.test.ts`
**Interfaces:**
- Consumes: Existing `gateway-backend-communication` and `acp-chat-experience` scenario contracts.
- Produces: A durable rule that permits one bounded, running-only Gateway overlay while preserving ACP replay as the sole history authority.
- [ ] **Step 1: Write the failing Harness assertion**
Extend `tests/unit/harness-specs.test.ts` to require `render-cron-run-live-status` to declare `fast`, `comms`, and `e2e`; reference `acp-cron-live-overlay.md`; require ACP authority, compatibility safety, renderer/Main boundary, host-api/host-events, i18n/design-token, communication regression, and docs-sync rules.
- [ ] **Step 2: Run the focused test and verify the expected failure**
Run `pnpm exec vitest run tests/unit/harness-specs.test.ts`. Expect failure because the current task spec still describes the legacy Execution Graph and omits the overlay reference and E2E profile.
- [ ] **Step 3: Rewrite the task and reference contract**
Change the expected behavior from “Gateway events become ACP/tool timeline updates” to:
```text
Gateway runtime event -> Main bounded cron broker -> explicit live overlay
terminal event -> overlay removal -> authoritative ACP/cron-history reload
```
State explicitly that the overlay is non-historical, memory-only, run-scoped, read-only, and excluded from sidebar unread/busy authority. Set `docs.required: true`, list all touched areas from this plan, and include the focused/unit/E2E/comms commands used below.
- [ ] **Step 4: Validate the real task spec**
Run:
```bash
pnpm exec vitest run tests/unit/harness-specs.test.ts
pnpm harness validate --spec harness/specs/tasks/render-cron-run-live-status.md
pnpm harness run --spec harness/specs/tasks/render-cron-run-live-status.md --dry-run
```
Expect all structural validation to pass without `--no-diff`.
- [ ] **Step 5: Commit point**
If explicitly requested, commit as `docs: define bounded cron live overlay architecture`.
---
### Task 2: Establish shared cron identity and correct lifecycle normalization
**Files:**
- Create: `shared/chat/cron-session.ts`
- Delete: `src/stores/chat/cron-session-utils.ts`
- Modify: `src/stores/acp-chat-session.ts`
- Modify: `src/stores/chat.ts`
- Modify: `src/stores/gateway.ts`
- Modify: `src/stores/session-attention.ts`
- Modify: `src/stores/chat/history-actions.ts`
- Modify: `src/stores/chat/session-selection.ts`
- Modify: `src/stores/chat/session-catalog.ts`
- Modify: `src/stores/chat/session-key-utils.ts`
- Modify: `electron/services/cron-api.ts`
- Modify: `electron/gateway/chat-runtime-events.ts`
- Test: `tests/unit/cron-session-utils.test.ts`
- Test: `tests/unit/gateway-event-dispatch.test.ts`
**Interfaces:**
- Consumes: Raw OpenClaw `sessionKey`, lifecycle `phase`, and `data.aborted` values.
- Produces: `parseCronSessionKey`, `getCronSessionBaseKey`, `isCronSessionKey`, `isRunScopedCronSessionKey`, and `sessionKeysAreEquivalent` as one shared authority; normalized terminal `ChatRuntimeEvent` values.
- [ ] **Step 1: Write failing identity and terminal tests**
Update `cron-session-utils.test.ts` to import from `@shared/chat/cron-session` and cover strict base/run parsing, empty or whitespace-only agent/job/run segment rejection, malformed suffix rejection, and run-scoped detection. Replace the current test that treats lifecycle `phase: 'end'` as non-terminal with expectations that:
```ts
{ phase: 'end' } -> { type: 'run.ended', status: 'completed' }
{ phase: 'end', aborted: true } -> { type: 'run.ended', status: 'aborted' }
{ phase: 'error' } -> { type: 'run.ended', status: 'error' }
```
- [ ] **Step 2: Run tests and verify failures**
Run `pnpm exec vitest run tests/unit/cron-session-utils.test.ts tests/unit/gateway-event-dispatch.test.ts`. Expect missing shared imports and incorrect `phase: 'end'` normalization.
- [ ] **Step 3: Centralize and tighten key parsing, then update all callers**
Move the parser into `shared/chat/cron-session.ts`, reject empty or whitespace-only `agentId`, `jobId`, and `runSessionId` segments, require exactly four segments for a base key or exactly six segments with literal `run` for a run key, and add `isRunScopedCronSessionKey`. Migrate all eight Renderer callers listed in the Files section plus Main `cron-api.ts`, delete the duplicate Main parser, and delete the old Renderer-owned utility file. Do not leave a compatibility re-export.
- [ ] **Step 4: Normalize OpenClaw terminal lifecycle correctly**
In `normalizeGatewayChatRuntimeEvent`, accept `end`, `completed`, `done`, and `finished` as terminal. For `phase: 'end'`, map `data.aborted === true` to `aborted`; otherwise map to `completed`. Preserve `endedAt`, `livenessState`, `replayInvalid`, and `stopReason`.
- [ ] **Step 5: Run focused regressions**
Run:
```bash
pnpm exec vitest run \
tests/unit/cron-session-utils.test.ts \
tests/unit/gateway-event-dispatch.test.ts \
tests/unit/gateway-events.test.ts \
tests/unit/cron-schedule.test.ts
```
Expect all tests to pass and no imports of `src/stores/chat/cron-session-utils.ts` to remain.
- [ ] **Step 6: Commit point**
If explicitly requested, commit as `fix: share cron identity and normalize run terminals`.
---
### Task 3: Build the bounded Main-process cron live-run broker
**Files:**
- Create: `shared/chat/cron-live-run.ts`
- Create: `electron/services/cron-live-run-broker.ts`
- Create: `tests/unit/cron-live-run-broker.test.ts`
**Interfaces:**
- Consumes: `ChatRuntimeEvent` and shared cron-session parsing.
- Produces: `CronLiveRunOverlaySnapshot`, `CronLiveRunItem`, `CronLiveRunOverlayChange`, `CronLiveRunOverlaySnapshotSet`, and `CronLiveRunBroker`.
- [ ] **Step 1: Define the explicit non-ACP view model in the test**
Write broker tests against this discriminated model:
```ts
type CronLiveRunStatus = 'running';
type CronLiveRunItem =
| { kind: 'tool'; id: string; toolCallId: string; title: string; status: 'running' | 'completed' | 'failed'; inputText?: string; outputText?: string; error?: string }
| { kind: 'command'; id: string; title: string; status: 'running' | 'completed' | 'failed'; output: string; exitCode?: number }
| { kind: 'patch'; id: string; title: string; summary?: string; added?: number; modified?: number; deleted?: number }
| { kind: 'approval'; id: string; title: string; status: 'running' | 'completed' | 'failed'; message?: string };
interface CronLiveRunOverlaySnapshot {
canonicalSessionKey: string;
sourceSessionKey: string;
runSessionId: string;
runId: string;
revision: number;
status: CronLiveRunStatus;
startedAt?: number;
updatedAt: number;
lastSeq?: number;
assistantText: string;
thinking: boolean;
items: CronLiveRunItem[];
}
interface CronLiveRunOverlaySnapshotSet {
revision: number;
snapshots: CronLiveRunOverlaySnapshot[];
}
type CronLiveRunOverlayChange =
| {
kind: 'upsert';
revision: number;
snapshot: CronLiveRunOverlaySnapshot;
}
| {
kind: 'remove';
revision: number;
canonicalSessionKey: string;
sourceSessionKey: string;
runId: string;
reason: 'ended' | 'evicted' | 'gateway-reset';
terminalStatus?: 'completed' | 'error' | 'aborted';
terminalError?: string;
};
```
The broker-level `revision` increments once for every emitted change, including removals and clears. Every upsert snapshot carries that same revision. `getSnapshotSet()` returns the current broker revision even when `snapshots` is empty, so Renderer can reject a stale empty/non-empty hydration response deterministically.
- [ ] **Step 2: Write failing broker scenarios**
Cover strict run-key admission, mid-flight adoption without `run.started`, text snapshot/replace/delta convergence, thinking boolean without retained thought text, tool updates, command output, patch and approval ordering, run-namespaced identities, numeric sequence rejection, sequence-less fingerprint dedupe, deterministic active-run eviction, text/item bounds, terminal removal, terminal tombstone suppression, gateway reset, and monotonic revisions.
- [ ] **Step 3: Run the broker test and verify failure**
Run `pnpm exec vitest run tests/unit/cron-live-run-broker.test.ts`. Expect module-not-found failures.
- [ ] **Step 4: Implement the minimum reducer and broker**
Implement one pure `reduceCronLiveRunEvent(snapshot, event)` and one stateful `CronLiveRunBroker`. Use type-specific stable fingerprints instead of generic unbounded serialization. Serialize structured input/output with stable key ordering, catch cycles, and truncate to `MAX_CRON_LIVE_ITEM_DETAIL_CHARS`. Preserve first-occurrence item ordering and update existing items in place.
On terminal events, emit `remove` before deleting active state, then add a bounded run tombstone so delayed duplicate/non-terminal events cannot recreate the run. `getSnapshotSet()` returns immutable clones sorted by `updatedAt`, then `runId` for deterministic hydration.
- [ ] **Step 5: Run focused tests and static checks**
Run:
```bash
pnpm exec vitest run tests/unit/cron-live-run-broker.test.ts
pnpm run typecheck:node
```
Expect broker tests and Node type checking to pass.
- [ ] **Step 6: Commit point**
If explicitly requested, commit as `feat: add bounded cron live-run broker`.
---
### Task 4: Expose broker snapshots and changes through typed Main boundaries
**Files:**
- Modify: `shared/host-events/contract.ts`
- Modify: `shared/host-api/contract.ts`
- Modify: `electron/services/cron-live-run-broker.ts`
- Modify: `electron/services/cron-api.ts`
- Modify: `electron/main/ipc-handlers.ts`
- Modify: `electron/main/index.ts`
- Modify: `src/lib/host-events.ts`
- Modify: `src/lib/host-api.ts`
- Test: `tests/unit/cron-live-run-broker.test.ts`
- Test: `tests/unit/cron-schedule.test.ts`
- Test: `tests/unit/host-events.test.ts`
- Test: `tests/unit/host-api-facade.test.ts`
- Test: `tests/unit/host-services.test.ts`
**Interfaces:**
- Consumes: `CronLiveRunBroker` from Task 3 and `GatewayManager` runtime/status/exit events.
- Produces: `hostApi.cron.liveRunOverlays()` and `hostEvents.onCronLiveRunOverlayChanged()`.
- [ ] **Step 1: Write failing host-boundary tests**
Add expectations for:
```ts
HOST_EVENT_CHANNELS.cron.liveRunOverlayChanged === 'cron:live-run-overlay-changed'
hostEvents.onCronLiveRunOverlayChanged(handler)
hostApi.cron.liveRunOverlays()
```
Extend broker tests for a `bindCronLiveRunBroker` helper that is the sole broker-ingestion owner: it listens to GatewayManager `chat:runtime-event`, publishes resulting broker changes, and clears on non-running Gateway status or `exit`. Existing raw runtime forwarding remains a separate listener and must not call `broker.ingestRuntimeEvent`.
- [ ] **Step 2: Run tests and verify missing contracts**
Run:
```bash
pnpm exec vitest run \
tests/unit/cron-live-run-broker.test.ts \
tests/unit/cron-schedule.test.ts \
tests/unit/host-events.test.ts \
tests/unit/host-api-facade.test.ts \
tests/unit/host-services.test.ts
```
Expect failures for the new API/event surface and dependency injection.
- [ ] **Step 3: Add typed contracts and facades**
Add a static `cron` host-event module with `liveRunOverlayChanged`, and add `cron.liveRunOverlays` to `HostApiContract`. The preload channel allowlist is contract-derived, so do not add a direct IPC allowlist or renderer `window.electron.ipcRenderer.invoke` call.
- [ ] **Step 4: Wire one broker instance in Main**
Instantiate `CronLiveRunBroker` next to `GatewayManager` in `electron/main/index.ts`, pass it through `registerIpcHandlers` to `createCronApi`, and call `bindCronLiveRunBroker` before Gateway auto-start. The binding publishes changes with `sendMainWindowEvent(HOST_EVENT_CHANNELS.cron.liveRunOverlayChanged, change)` and is the only code that calls `broker.ingestRuntimeEvent`. Keep the existing raw `chat:runtime-event` listener unchanged so legacy and image-generation consumers still receive the original event exactly once.
`createCronApi({ gatewayManager, cronLiveRunBroker })` must return `liveRunOverlays: () => cronLiveRunBroker.getSnapshotSet()` for late join/reload hydration.
- [ ] **Step 5: Run boundary regressions**
Run the focused tests from Step 2 plus:
```bash
pnpm run typecheck:node
pnpm run typecheck:web
```
Expect all tests and both type-check lanes to pass.
- [ ] **Step 6: Commit point**
If explicitly requested, commit as `feat: expose cron live overlays through host boundaries`.
---
### Task 5: Add the revision-safe Renderer overlay store
**Files:**
- Create: `src/stores/cron-live-run-overlay.ts`
- Create: `tests/unit/cron-live-run-overlay-store.test.ts`
- Modify: `tests/unit/host-events.test.ts`
**Interfaces:**
- Consumes: `hostApi.cron.liveRunOverlays()` and `hostEvents.onCronLiveRunOverlayChanged()`.
- Produces: `useCronLiveRunOverlayStore`, `ensureCronLiveRunOverlaySubscriptions`, `selectCronLiveRunsForSession`, and terminal-removal acknowledgement state.
- [ ] **Step 1: Write failing store tests**
Mock host-api and host-events and cover:
- subscribe-before-snapshot ordering;
- ignoring an older snapshot after a newer change;
- upsert by `canonicalSessionKey + runId`;
- remove without retaining content as history;
- bounded pending removals keyed by `canonicalSessionKey + runId + revision` so bursts cannot overwrite one another;
- explicit `acknowledgeRemoval(revision)` that removes only the acknowledged change;
- a burst where visible run A and inactive run B terminate before React processes either event;
- selection by exact base cron key only;
- gateway-reset and eviction removals never marked as terminal refreshes.
- [ ] **Step 2: Run and verify module-not-found failure**
Run `pnpm exec vitest run tests/unit/cron-live-run-overlay-store.test.ts`.
- [ ] **Step 3: Implement the store**
Keep only normalized snapshots and at most 128 pending removal changes ordered by revision. Key removals by `canonicalSessionKey + runId + revision`; never overwrite another run's terminal signal. Do not import ACP reducer/timeline modules or `ChatRuntimeEvent`. `ensureCronLiveRunOverlaySubscriptions` must be idempotent, register the event listener first, then request the Main snapshot, and compare revisions before applying either source.
- [ ] **Step 4: Run focused tests and Web type checking**
Run:
```bash
pnpm exec vitest run \
tests/unit/cron-live-run-overlay-store.test.ts \
tests/unit/host-events.test.ts
pnpm run typecheck:web
```
Expect all tests to pass with no ACP imports in the new store.
- [ ] **Step 5: Commit point**
If explicitly requested, commit as `feat: add cron live overlay renderer store`.
---
### Task 6: Build the explicit, read-only live overlay UI
**Files:**
- Create: `src/pages/Chat/CronLiveRunOverlay.tsx`
- Create: `tests/unit/cron-live-run-overlay.test.tsx`
- Modify: `shared/i18n/locales/en/chat.json`
- Modify: `shared/i18n/locales/zh/chat.json`
- Modify: `shared/i18n/locales/ja/chat.json`
- Modify: `shared/i18n/locales/ru/chat.json`
**Interfaces:**
- Consumes: One `CronLiveRunOverlaySnapshot`.
- Produces: A clearly labeled transient panel with `data-testid="cron-live-run-overlay"` and item-specific test IDs.
- [ ] **Step 1: Write failing component tests**
Cover the localized “Live scheduled run” header, running pulse, assistant Markdown, thinking indicator without raw thought text, tool status progression, whitespace-preserving command output, patch counts, read-only approval status, and distinct test IDs (`cron-live-tool`, `cron-live-command`, `cron-live-patch`, `cron-live-approval`).
- [ ] **Step 2: Run and verify failure**
Run `pnpm exec vitest run tests/unit/cron-live-run-overlay.test.tsx`.
- [ ] **Step 3: Implement the presentation component**
Reuse `AcpRenderPart` only as a Markdown renderer for assistant text; do not create ACP message/tool items. Implement dedicated cron item rows so they cannot be mistaken for native ACP cards or interactive ACP permissions. Use `bg-surface-modal`, `bg-surface-input`, selected/status token substitutions, and `text-X-700 dark:text-X-400` status colors from `globals.css`.
- [ ] **Step 4: Add complete locale coverage and regressions**
Add labels for the panel, running/thinking, tool/command/patch/approval status, completion/failure wording, and read-only approval explanation in all four locale files. Run:
```bash
pnpm exec vitest run tests/unit/cron-live-run-overlay.test.tsx
pnpm run typecheck:web
pnpm run lint:check
```
Expect the component test, type check, and lint check to pass.
- [ ] **Step 5: Commit point**
If explicitly requested, commit as `feat: render transient cron run progress`.
---
### Task 7: Compose the overlay with ACP Chat and refresh authoritative history
**Files:**
- Modify: `src/pages/Chat/index.tsx`
- Modify: `tests/unit/chat-acp-page.test.tsx`
- Modify: `tests/unit/cron-live-run-overlay-store.test.ts`
**Interfaces:**
- Consumes: Current base session key, overlay snapshots/removal markers, ACP `loadSession`, and workspace context.
- Produces: ACP timeline plus separate live panels; one authoritative reload for a visible terminal run.
- [ ] **Step 1: Write failing page integration tests**
Cover:
- overlay replaces `AcpEmptyState` while history is empty;
- ACP timeline and overlay coexist as sibling DOM regions;
- overlay content never appears under `data-testid="acp-chat-timeline"`;
- another cron job or ordinary session does not render the overlay;
- multiple active snapshots render in deterministic order;
- switching away hides the overlay and switching back restores the Main snapshot;
- external cron activity does not set `ChatInput.sending`, show ACP Stop, or call `cancelAcpSession`;
- a terminal `remove` for a run that was visible triggers exactly one `loadAcpSession`;
- a burst of removals for two runs preserves and acknowledges both revisions while refreshing only runs visible in the current session;
- terminal removal while another session is selected does not trigger a delayed duplicate reload when returning later;
- `evicted` and `gateway-reset` removals do not trigger authoritative reloads.
- [ ] **Step 2: Run and verify integration failures**
Run:
```bash
pnpm exec vitest run \
tests/unit/chat-acp-page.test.tsx \
tests/unit/cron-live-run-overlay-store.test.ts
```
- [ ] **Step 3: Integrate subscriptions and rendering**
Initialize the overlay subscription alongside `ensureAcpChatSubscriptions`. Select snapshots for `currentSessionKey`, render them after the authoritative `AcpTimeline`, and suppress `AcpEmptyState` while at least one overlay is visible. Include overlay presence in scroll-to-latest calculations.
- [ ] **Step 4: Implement visible-run terminal refresh**
Track run IDs actually rendered for the current session in a ref that resets on session switch. Process pending removals in revision order. When an unacknowledged removal has `reason: 'ended'`, matches the current base session, and its run ID was rendered there, acknowledge that exact revision and call normal `loadAcpSession({ sessionKey, workspaceRoot: cwd, cwd })` once. Acknowledge non-visible/stale removals without reload. Do not collapse multiple removals into one marker, call legacy `loadHistory`, mutate the ACP snapshot, or synthesize a generation.
- [ ] **Step 5: Run focused UI and state regressions**
Run:
```bash
pnpm exec vitest run \
tests/unit/chat-acp-page.test.tsx \
tests/unit/cron-live-run-overlay.test.tsx \
tests/unit/cron-live-run-overlay-store.test.ts \
tests/unit/acp-chat-store.test.ts \
tests/unit/gateway-events.test.ts
pnpm run typecheck
```
Expect all existing ACP prompt, image-generation, cancellation, and runtime retention tests to remain green.
- [ ] **Step 6: Commit point**
If explicitly requested, commit as `feat: compose cron live overlay with ACP Chat`.
---
### Task 8: Replace synthetic-ACP E2E coverage, update docs, and run communication proof
**Files:**
- Modify: `tests/e2e/cron-run-live-status.spec.ts`
- Modify: `README.md`
- Modify: `README.zh-CN.md`
- Modify: `README.ja-JP.md`
- Modify: `harness/specs/tasks/render-cron-run-live-status.md`
- Modify: `harness/reference/acp-cron-live-overlay.md`
- Modify: `harness/reference/acp-chat.md`
**Interfaces:**
- Consumes: The completed Main broker, typed host event, snapshot API, Renderer store, and overlay UI.
- Produces: User-visible regression proof and synchronized architecture documentation.
- [ ] **Step 1: Rewrite E2E helpers and expectations**
Remove fake `chat:acp-session-update` tool calls from the live cron scenarios. Add a helper that emits typed `cron:live-run-overlay-changed` upsert/remove changes and mock `cron.liveRunOverlays` for late join. Main broker reduction is covered by `cron-live-run-broker.test.ts`; E2E covers the real preload/host-event/Renderer/UI contract.
Verify assistant text, thinking status, tool, command, patch, and approval rows; no legacy execution graph; no runtime content inside ACP timeline; no invalid Stop state; hide/restore across session switches; mid-flight overlay hydration; terminal removal; and one authoritative `loadAcpSession` invocation.
- [ ] **Step 2: Run the focused Electron E2E**
Run:
```bash
pnpm run build:vite
pnpm exec playwright test tests/e2e/cron-run-live-status.spec.ts
```
Expect the spec to pass on the local platform.
- [ ] **Step 3: Update user and architecture documentation**
In all three required READMEs, state that running cron progress is a transient Gateway-backed overlay, completed conversation content remains ACP/cron-history authoritative, and external cron activity does not become an ACP-cancellable prompt. Keep the explanation concise and localized.
Update Harness references to document the exact bounds, revision race handling, no-CoT rule, terminal reload semantics, OpenClaw upgrade removal condition, and the prohibition against extending this exception to ordinary non-cron messages.
- [ ] **Step 4: Run the focused and project-wide safe validation suite**
Run:
```bash
pnpm exec vitest run \
tests/unit/harness-specs.test.ts \
tests/unit/cron-session-utils.test.ts \
tests/unit/gateway-event-dispatch.test.ts \
tests/unit/cron-live-run-broker.test.ts \
tests/unit/cron-live-run-overlay-store.test.ts \
tests/unit/cron-live-run-overlay.test.tsx \
tests/unit/cron-schedule.test.ts \
tests/unit/host-events.test.ts \
tests/unit/host-api-facade.test.ts \
tests/unit/host-services.test.ts \
tests/unit/chat-acp-page.test.tsx \
tests/unit/acp-chat-store.test.ts \
tests/unit/acp-image-generation-compat.test.ts \
tests/unit/gateway-events.test.ts
pnpm run typecheck
pnpm run lint:check
pnpm run build:vite
pnpm exec playwright test tests/e2e/cron-run-live-status.spec.ts
pnpm run comms:replay
pnpm run comms:compare
pnpm harness validate --spec harness/specs/tasks/render-cron-run-live-status.md
pnpm harness run --spec harness/specs/tasks/render-cron-run-live-status.md
pnpm run harness:ci
```
Expected result: all focused tests, type checking, lint, build, E2E, communication regression comparison, task Harness run, and Harness CI pass. Re-run `pnpm run lint:check` only after any concurrent uv download has completed if the documented temporary-directory race occurs.
- [ ] **Step 5: Review the removal condition**
Record in `acp-cron-live-overlay.md` that the overlay can be deleted only after a distributed OpenClaw package proves all of these through integration tests: loaded ACP sessions receive autonomous cron assistant/thought/tool updates, generated media arrives as standard ACP content blocks, replay is complete and deduplicated, and external-run lifecycle/cancel semantics are explicitly exposed.
- [ ] **Step 6: Commit point**
If explicitly requested, commit as `test: cover authoritative cron live overlay flow`.
---
## Final Self-Review Checklist
- [ ] No Gateway runtime event is converted to an ACP update or inserted into `AcpTimelineSnapshot`.
- [ ] Main owns strict cron identity, event reduction, deduplication, bounds, snapshots, and revisions.
- [ ] Sequence-less and repeated terminal events cannot duplicate or resurrect runs.
- [ ] Renderer shows only current base-cron overlays and never raw chain-of-thought.
- [ ] ACP prompt sending, Stop, cancellation, permission response, replay, and image compatibility behavior remain unchanged.
- [ ] Terminal refresh occurs once only for a run that was visible in the currently selected session.
- [ ] E2E no longer claims live behavior by injecting synthetic ACP tool notifications.
- [ ] Harness specs and all required README translations describe the same authority boundary.
- [ ] No placeholders, compatibility re-exports, direct IPC invokes, Gateway HTTP calls, or undocumented protocol fallbacks remain.
+865
View File
@@ -0,0 +1,865 @@
# ClawX Runtime Abstraction and cc-connect Replacement Specification
Status: implementation contract
Updated: 2026-07-12
Default runtime: `openclaw`
Optional runtime: `cc-connect` behind Developer Mode
## 1. Objective
ClawX must expose one runtime layer whose OpenClaw and cc-connect providers
support the same product surfaces. OpenClaw remains the default and rollback
path. cc-connect is accepted as a replacement only when chat, sessions,
history, tools, provider credentials, Feishu/Lark, native cron, usage,
skills, diagnostics, and packaged startup are proven through the cc-connect
process rather than through ClawX-to-Codex shortcuts.
The non-negotiable execution boundary is:
```text
Renderer -> Host API -> RuntimeManager -> CcConnectRuntimeProvider
-> cc-connect Bridge/Management API -> cc-connect -> Codex
```
ClawX may supply the Codex binary path, provider environment, `CODEX_HOME`,
workspace, skills, and credentials to cc-connect. It must not spawn Codex for
chat, parse Codex files as the production real-time event transport, or invoke
Codex session commands directly.
## 2. Version and packaging decision
The original prototype pinned `cc-connect@1.3.2`. That package contains only a
CLI wrapper, install script, and documentation; its postinstall downloads a
release binary into `node_modules/cc-connect/bin`. Declaring the dependency is
therefore insufficient for Electron packaging.
The replacement implementation targets stable `cc-connect@1.4.1` because its
published runtime surface includes Bridge REST session management and a broader
Management API. The exact binary, not upstream `main`, is the release contract.
Every upgrade must run the contract probe before application code adopts a new
endpoint.
Packaging requirements:
- Pin `cc-connect` exactly in `devDependencies`.
- `scripts/bundle-cc-connect.mjs` downloads release assets for macOS x64/arm64,
Linux x64/arm64, and Windows x64.
- Verify `--version`, executable permission, SHA-256, platform, architecture,
source URL, and package version in `manifest.json`.
- Copy the verified binary to `process.resourcesPath/cc-connect/`; never run
postinstall or download a binary at application runtime.
- Bundle the pinned Codex CLI in `process.resourcesPath/codex/`; cc-connect is
the only process allowed to launch it for runtime work.
- `afterPack` must reject a target whose copied cc-connect or Codex resource is
missing, stale, corrupted, non-executable, or inconsistent with its manifest.
- Final unpacked artifacts must pass
`pnpm run verify:packaged-runtime-resources -- --resources=<resources> --platform=<platform> --arch=<arch>`.
Windows and Linux require exact packaged-binary SHA equality. macOS also
requires exact SHA before signing; when `codesign` rewrites Mach-O metadata,
the final verifier requires the source bundle SHA, all Mach-O section
payloads, architecture/version, and `codesign --verify --strict` to agree.
- macOS, Windows, and Linux packaged jobs must run a resource/startup/cleanup
smoke before release readiness can be claimed.
- `.github/workflows/release.yml` runs the final resource verifier for macOS
x64/arm64, Windows x64, and Linux x64/arm64 before uploading release
artifacts. The same release gate runs the full packaged smoke natively on
macOS arm64, Windows x64, and Linux x64, with dedicated `macos-15-intel` and
`ubuntu-24.04-arm` jobs for macOS x64 and Linux arm64. Publishing depends on
all five jobs. A local run cannot replace observed CI evidence. Runner labels
follow the [GitHub-hosted runners reference](https://docs.github.com/en/actions/reference/runners/github-hosted-runners).
- A manual `Release` workflow dispatch is evidence-only: it disables macOS
signing discovery and never creates a GitHub Release, uploads to OSS, or runs
final promotion. Publishing remains tag-only. Use an alpha/beta version label
for manual smoke so Windows also skips SignPath. Manual macOS smoke explicitly
records that signature validation was skipped; tag builds still require strict
signature verification before publishing.
Primary upstream contracts:
- [cc-connect usage](https://github.com/chenhg5/cc-connect/blob/v1.4.1/docs/usage.md)
- [Management API](https://github.com/chenhg5/cc-connect/blob/v1.4.1/docs/management-api.md)
- [Bridge protocol](https://github.com/chenhg5/cc-connect/blob/v1.4.1/docs/bridge-protocol.md)
## 3. Durable data and locking
All ClawX-owned persistent state uses one upgrade-stable root. Stable, beta,
dev, and multiple installations may share it, but only one writer may run at a
time.
```text
~/.clawx/
state/
data-version.json
migration-journal.jsonl
locks/
writer.lock
app/
settings.json
clawx-providers.json
runtime-config.json
cc-connect-agent-bindings.json
cc-connect-session-metadata.json
credentials/
index.json
secrets.enc
oauth/<provider-account-id>/codex-home/
skills/
installed/
configs.json
workspaces/
agents/<agent-id>/
runtimes/
cc-connect/{config,data,media,events,logs}
openclaw/projection-state.json
system/electron/
logs/
backups/
cache/
```
`resolveClawXDataRoot()` and `getClawXDataLayout()` are the only path-building
entry points. Production defaults to `~/.clawx`; `CLAWX_DATA_HOME` is the
supported override. Electron `userData` becomes `~/.clawx/system/electron` and
application logs use `~/.clawx/logs`.
`writer.lock` is created atomically and contains pid, owner token, app version,
channel, executable, start time, and heartbeat time. A second installation
shows the current owner and exits before the data layout, migrations, runtime
manager, or scheduler can start. Failure to acquire or inspect the lock is
fail-closed; ClawX never falls back to an uncoordinated shared-root writer.
Stale lock recovery requires both a dead pid and an expired heartbeat;
`force: true` deletion is forbidden.
Migrations are version-gated, journaled, additive, backed up, and atomic. An
older application that cannot understand the current data version refuses to
write. Existing Electron data is imported into `~/.clawx`; existing
`~/.openclaw` remains external compatibility data and is never moved or
deleted.
`tests/e2e/clawx-data-layout-migration.spec.ts` exercises this production
startup order without the flat `CLAWX_USER_DATA_DIR` test compatibility
override. It supplies an isolated legacy `--user-data-dir` before Main startup,
uses an isolated `CLAWX_DATA_HOME`, launches Electron, and verifies `app/`,
`system/electron`, the data version, migration journal, and retained legacy
source on every CI platform without reading the developer's real userData. It
then changes the legacy settings and launches again to prove the canonical
`app/` state wins across upgrades and repeated migration attempts.
`tests/e2e/clawx-shared-root-single-writer.spec.ts` launches two real Electron
processes against the same root, proves the duplicate cannot replace the live
owner or create a window, captures first-writer UI evidence, then closes the
owner and proves a successor process acquires the released lock.
`app/runtime-config.json` is the canonical Agent, binding, channel-account, and
OpenClaw-compatible runtime metadata document. Sensitive channel fields are
removed before this file is written and are hydrated from
`credentials/secrets.enc` only in Main-process memory. `~/.openclaw/openclaw.json`
is an import/export compatibility projection, not the cc-connect state owner.
The compatibility file is imported only when canonical state does not yet
exist. Shared saves never use its mtime to overwrite canonical state. While
cc-connect is active they do not write the projection; the OpenClaw adapter
rebuilds it, including vault-backed channel secrets, immediately before
OpenClaw start or restart.
## 4. Runtime contracts
```ts
type RuntimeKind = 'openclaw' | 'cc-connect'
interface RuntimeProvider {
kind: RuntimeKind
start(): Promise<void>
stop(): Promise<void>
restart(): Promise<void>
getStatus(): RuntimeStatus
checkHealth(options?: RuntimeHealthOptions): Promise<RuntimeHealth>
rpc<T>(method: string, params?: unknown): Promise<T>
sendMessageWithMedia(payload: RuntimeSendPayload): Promise<RuntimeSendResult>
abortRun(payload: RuntimeAbortPayload): Promise<RuntimeAbortResult>
resolveApproval(payload: RuntimeApprovalResponse): Promise<void>
listSessions(query?: RuntimeSessionQuery): Promise<RuntimeSessionPage>
loadHistory(query: RuntimeHistoryQuery): Promise<RuntimeHistoryPage>
deleteSession(payload: RuntimeSessionMutation): Promise<void>
listUsage(query?: RuntimeUsageQuery): Promise<RuntimeUsagePage>
listLogs(query?: RuntimeLogQuery): Promise<RuntimeLogPage>
runDoctor(mode: 'diagnose' | 'fix'): Promise<RuntimeDoctorResult>
listCapabilities(): RuntimeCapabilities
listOperationCapabilities(): RuntimeOperationCapabilities
}
```
`RuntimeStatus` retains Gateway-compatible process states and adds
`runtimeKind`, version, config directory, capabilities, operation capabilities,
and scoped health. `gateway:*` IPC/event names remain compatibility aliases,
but their data is always supplied by the active provider.
Operation support is `native`, `proxy`, `degraded`, or `unsupported`.
`degraded` means the command remains callable but has a documented parity or
blast-radius limitation. For cc-connect v1.4.1, `chat.abort` is native: ClawX
sends the public `/stop` command over BridgePlatform for the selected session.
The whole runtime is restarted only as a disconnected-Bridge fallback when the
stop command cannot be delivered. Settings displays degraded and unsupported
operations separately from top-level capability availability.
Before a runtime status has published operation capabilities, renderer helpers
retain compatibility with legacy Gateway status. Once the operation map is
present, any undeclared method is treated as unsupported; this makes contract
drift visible instead of allowing an unreviewed runtime call to pass through.
OpenClaw-specific auth, proxy mutation, Doctor Fix, Skills implementation,
Dreams, memory repair, and Control UI remain inside the OpenClaw adapter.
Shared services must not call `GatewayManager` or write `~/.openclaw` when
cc-connect is active.
## 5. Agent, provider, model, and credential ownership
Provider Account is the stable credential identity. Agent bindings reference an
account explicitly instead of encoding identity in `provider/model` strings.
```ts
interface AgentRuntimeBinding {
agentId: string
providerAccountId: string
model: string
workspaceId: string
}
```
`agents.updateRuntimeBinding({ id, providerAccountId, model })` is the canonical
Host API. The old model-only method is a compatibility adapter and fails when
multiple accounts make the reference ambiguous.
Each cc-connect project resolves credential identity from the Agent's provider
account binding and resolves model independently from that Agent's explicit
`provider/model` override or the canonical default. Project model overrides
replace only cc-connect/Codex model arguments; they never replace or merge the
bound account's OAuth home or API-key environment.
Credential rules:
- Browser OAuth acquisition writes only the ClawX-owned provider account and
encrypted secret. Runtime projection is dispatched through the active
`RuntimeProvider`: cc-connect materializes its account-scoped managed
`CODEX_HOME`, while OpenClaw retains its existing auth/config projection. A
cc-connect OAuth success must never write OpenClaw config or schedule an
OpenClaw Gateway restart.
- A successful cc-connect browser re-login (`reason=oauth`) replaces that
account's managed Codex auth with the newly acquired vault secret. Ordinary
runtime startup keeps managed auth first so Codex refresh-token rotation is
not rolled back by an older vault snapshot.
- API keys and reusable OAuth recovery material are encrypted with Electron
`safeStorage` in `credentials/secrets.enc`.
- Channel account secrets share the encrypted vault under account-scoped IDs;
`credentials/index.json` contains IDs only, never secret values.
- Every OpenAI OAuth account owns a complete account-level `CODEX_HOME` under
`credentials/oauth/<account-id>/codex-home`; auth files are mode `0600`.
- OAuth homes are not symlinked or copied between accounts. Agents may share an
account by binding to the same account-level home.
- A pre-account shared managed Codex home is moved once to the selected default
OAuth account and then removed; it is never copied to a second account.
- Runtime profile construction never consumes user-global `~/.codex/auth.json`.
That file is inspected only for redacted status and copied only after the user
explicitly invokes `importCodexOAuth` for a matching account.
- API-key projects receive account-specific environment variables. Secrets are
never written literally to generated TOML or exposed to Renderer.
- Provider/model/account changes detach the old runtime session and create a
new cc-connect/Codex session on the next turn while preserving visible ClawX
history.
- Missing or incomplete credentials block only bound Agents. Access-token
expiry does not invalidate a complete managed OAuth home because
cc-connect/Codex owns refresh-token rotation there; a failed refresh is
surfaced on that Agent's runtime turn and can be recovered with browser
re-login, without changing another Agent's credentials.
- Validation may import a complete token set with an expired access or ID token
into an isolated managed `CODEX_HOME`. The verifier records only sanitized JWT
expiry metadata; only a successful real cc-connect -> Codex turn proves that
refresh-token rotation worked. Passing the static precondition alone is not
refresh evidence.
- Proxy variables are supplied to cc-connect and inherited by its children;
localhost, `127.0.0.1`, and `::1` are always added to `NO_PROXY`.
Initial verified matrix: OpenAI API key, OpenAI Codex OAuth, OpenAI-compatible
Responses, and Ollama. Unsupported providers return a stable capability error
without mutating OpenClaw config.
`providers.profile` and `models.profile` are read-only runtime operations. While
cc-connect is running they return the ClawX-managed public profile together
with each managed project's public Management API `/providers` and `/models`
state. They never reuse the sync path and therefore never restart cc-connect.
The adapter maps only provider name, active state, model, base URL, model list,
and current model; unknown Management fields and secret-like fields never cross
the Host API.
Provider/model writes remain ClawX-owned: ClawX updates the account-scoped
Codex profile and cc-connect project config, then reloads or restarts through
the runtime provider.
## 6. Workspace, skills, and plugins
New Agents use `~/.clawx/workspaces/agents/<agent-id>`. If an existing OpenClaw
Agent has a valid configured workspace, ClawX records that path as
`external-openclaw` and reuses it without copying or moving data.
Each cc-connect project receives exactly that Agent workspace as `work_dir`.
No code path may default to `process.cwd()`, the ClawX source checkout, or app
resources. Agent deletion removes only `clawx-managed` workspaces.
When a new Agent requests workspace inheritance, ClawX may read bootstrap files
from the existing OpenClaw main workspace, but writes the new Agent under the
ClawX-managed root. It never changes or assumes ownership of the source path.
ClawX owns one Skill Registry. OpenClaw receives its normal skills projection;
cc-connect receives the same enabled skills through its project/Codex skills
surface. The acceptance test must invoke a real installed skill through chat,
not only compare copied files.
Plugin reuse means shared ClawX capability, account, binding, and UI metadata.
OpenClaw JS plugins remain OpenClaw-specific. cc-connect channels are generated
as native `projects.platforms` entries and do not load OpenClaw plugins.
## 7. Chat, events, tools, approvals, and cancellation
GUI Chat registers as a cc-connect Bridge adapter. cc-connect invokes Codex and
emits all run activity over Bridge. The normalized envelope is:
OpenClaw and cc-connect intentionally use different provider-owned Chat
transports behind the same ClawX route. OpenClaw uses the Main-owned ACP
session transport introduced by the OpenClaw runtime. cc-connect renders the
Runtime Chat implementation and sends through `RuntimeManager` -> active
`RuntimeProvider` -> BridgePlatform. Renderer routing follows the active
runtime status, not only the pending Settings selection. As defense in depth,
Main rejects ACP load, prompt, cancel, and permission requests whenever
cc-connect is active; typed media sends remain dispatched through the active
runtime provider.
The adapter follows the pinned cc-connect Web Admin client lifecycle: after
`register_ack` it sends a JSON `ping` every 25 seconds, reconnects after 3
seconds when the socket drops, and stops both timers during an intentional
runtime stop. This is required for scheduler and long-running Agent replies
that cross cc-connect's approximately 90-second idle disconnect window.
```ts
interface RuntimeEventEnvelope {
schemaVersion: 1
eventId: string
runtimeKind: RuntimeKind
project: string
sessionKey: string
runtimeSessionId: string
runId: string
turnId: string
seq: number
timestamp: string
type: RuntimeEventType
payload: unknown
}
```
Required event types are `run.started`, `assistant.delta`,
`reasoning.summary.delta`, `tool.started`, `tool.updated`, `tool.completed`,
`command.output`, `patch.completed`, `approval.requested`,
`approval.resolved`, `usage.recorded`, and `run.ended`.
Pinned cc-connect v1.4.1 has two materially different Codex backends. Its
default `exec` backend does not map Codex 0.137 `custom_tool_call` records such
as `apply_patch` to `EventToolUse`; a real OAuth probe created the requested
file while cc-connect reported `tools=0`. ClawX therefore configures every
managed Codex project with `backend = "app_server"` and
`app_server_url = "stdio://"`. cc-connect remains the process owner and starts
the bundled Codex app-server inside the Agent workspace.
The Bridge adapter registers `progress_style = "card"` and
`supports_progress_card_payload = true`. cc-connect then sends the public
`__cc_connect_progress_card_v1__:` payload through `preview_start` and
`update_message`; ClawX maps typed `thinking`, `tool_use`, `tool_result`, and
`error` entries to the shared runtime graph. cc-connect v1.4.1 emits a
`fileChange` start but no corresponding result, so a successful or failed final
Bridge reply closes any still-open tool with
`meta.inferredFromRunCompletion = true`. Explicit tool results always win and
are never replaced by the inferred terminal event.
Plain-text previews use the same normalized `assistant.delta` contract. ClawX
emits the initial `preview_start` immediately, applies each `update_message` as
an in-place replacement, and clears only that transient assistant text when
cc-connect sends `delete_message`. Structured progress is intentionally kept as
semantic thinking/tool lifecycle in the execution graph; deleting cc-connect's
temporary platform message must not erase the completed tool relationship.
The opt-in real OAuth E2E proves the full path: GUI send -> RuntimeManager ->
cc-connect Bridge -> cc-connect-owned Codex app-server -> Patch -> progress
payload -> Main runtime event -> Renderer execution graph. It asserts
`transport=stdio`, cc-connect `tools=1`, the managed workspace file, both tool
lifecycle events, real approval request/resolution, and the visible graph. It
writes sanitized evidence under
`artifacts/cc-connect/real-oauth-tool-events.{png,json}` plus
`artifacts/cc-connect/real-oauth-approval-request.png`. These screenshots keep
the tool type, approval controls, lifecycle state, generated filename, and
assistant result visible while masking the isolated managed workspace path.
Reading Codex JSONL as a real-time event source, wrapping Codex stdout, or
spawning a second Codex bridge remains forbidden. Section 8 documents the sole
bounded historical exception for Channel tool packets omitted by public
cc-connect history.
The local-real verifier performs runtime checks with real filesystem paths but
replaces repository, home, and temporary roots with `<repo>`, `<home>`, and
`<tmp>` before persisting JSON or Markdown. A passing evidence row must not
publish a developer's worktree, credential-home, or isolated runtime path.
Only Codex-provided reasoning summaries are shown. Hidden chain-of-thought is
never requested or inferred. `eventId` deduplicates; `runId + seq` orders and
detects gaps. Bridge reconnect must replay missing events through
cc-connect-owned history once the upstream protocol exposes them. ClawX must
not scan Codex transcript files to reconstruct real-time tool activity.
The app-server backend surfaces approval requests as Bridge `buttons`. ClawX
stores the run-correlated `session_key`, `reply_ctx`, project, and only the
actions offered by cc-connect. `chat.approval.respond` validates the requested
action against that pending set and sends cc-connect's public `card_action`
packet; Renderer never talks to Codex and cannot inject an arbitrary action.
Deterministic Electron E2E proves request rendering, GUI click, Host API/runtime
RPC dispatch, the exact Bridge packet, and resumed assistant delivery. The
opt-in real OAuth E2E additionally runs the Main Agent in `suggest` mode and
proves the same flow through bundled cc-connect 1.4.1 and bundled Codex: a real
Patch approval is rendered, allowed, resolved by cc-connect, and followed by a
workspace write and final assistant response.
The same validated path handles non-approval runtime choices from cc-connect
cards. Action rows, list buttons, and select options are parsed from the public
card schema; only `perm:`, `askq:`, `cmd:`, `nav:`, and `act:` values are
eligible. Select options complete the current Chat run when cc-connect returns
the updated state card, while navigation/button cards can continue the same
interaction until cc-connect emits a reply or the user aborts. The real bundled
`/lang -> card -> card_action -> card` E2E verifies the live language through
the public Management project API and preserves the runtime PID. Pinned v1.4.1
does not persist manual `/lang` selections to `config.toml`: its save callback
is registered only for automatic language detection, so ClawX does not infer a
durable write that the runtime did not perform.
Permission mode is Agent-owned runtime metadata in
`~/.clawx/app/agent-bindings.json`, alongside but independent from the Agent's
provider-account binding. `full-auto` remains the default; `suggest` selects
cc-connect app-server's `on-request` approval policy and read-only sandbox.
Saving the mode refreshes the managed project config without writing OpenClaw
configuration. Only these two safe product modes are exposed; ClawX does not
offer cc-connect's sandbox-bypassing mode.
Pinned cc-connect v1.4.1 has no dedicated incoming Bridge cancellation packet
or per-run cancellation Management endpoint, but its public `/stop` command is
session-scoped. `chat.abort` immediately ends the correlated ClawX run, sends
`/stop` through BridgePlatform for that session, and suppresses replies correlated
to the aborted run. Codex app-server does not implement cc-connect's graceful
`CancelTurn` interface, so cc-connect closes only that session's Codex child
while preserving its stored AgentSessionID for resume; the cc-connect process
and other Agent sessions remain running. If Bridge is disconnected and `/stop`
cannot be delivered, ClawX restarts the owned runtime as an explicit fallback.
The real local OpenAI-compatible E2E proves upstream stream closure, no late
assistant rendering, and an unchanged cc-connect PID.
## 8. Sessions and history
Session inventory, ordinary user/assistant history, and deletion use
cc-connect's public Management/Bridge session endpoints. ClawX does not read or
mutate cc-connect session JSON files. User-assigned titles are ClawX UI metadata
stored atomically in `app/cc-connect-session-metadata.json`; deleting a public
session deletes its title in the same Host API operation. On first use, labels
from the old ClawX-owned `.clawx-supplemental-history.json` are imported without
copying its history payload.
The production Bridge adapter contains no parser for cc-connect session JSON or
Codex transcripts. It retains only messages observed on the current public
Bridge connection for immediate event delivery; durable list/delete and
authoritative ordinary messages always come from the provider's public
Management session client.
Pinned cc-connect can omit historical tool packets from public history for
Channel-originated sessions even though Codex recorded and executed those
tools. After public history has loaded, the provider may apply one degraded,
best-effort compatibility supplement that contributes only tool calls and
their results. It cannot create or replace user, assistant, system, attachment,
approval, real-time event, or usage records.
Candidate Codex JSONL files must match the owning Agent workspace. A stale or
exact `agent_session_id` does not bypass that check. Fallback discovery is
bounded to recent public user-turn text and the timestamp of that exact user
record, nearby transcript date directories, bounded path/file caches, and
truncated tool output. Missing, stale, cross-workspace, or ambiguous evidence
leaves public history unchanged. This exception does not satisfy replacement
readiness and must be removed when the pinned cc-connect runtime exposes
durable public Channel tool history.
ClawX owns logical session identity and display metadata; cc-connect owns
runtime sessions and message history. Public session responses carry the
logical/runtime binding, while `cc-connect-session-metadata.json` stores only
optional display labels and never copies runtime credentials or message
history.
cc-connect Session REST/Management APIs are the only production source for
list, create, ordinary message history, switch, and delete. The bounded
Channel tool supplement above is the only historical content exception. Rename
uses an official endpoint if the pinned binary exposes it; otherwise ClawX
stores only the display label in its logical index and does not rewrite
cc-connect private JSON. Hard delete is reported successful only after the
runtime API confirms deletion.
Runtime or provider switching preserves visible historical turns and detaches
the old backend binding. The first subsequent message creates a new runtime
session and includes a clearly identified continuation context once. OpenClaw
internal session ids are never passed to cc-connect.
Required cases include active, named, cross-Agent, Channel, Cron, restart,
rename, hard delete, and pagination. Session ids must not collide across
projects or provider accounts.
## 9. Token usage
Usage is a runtime contract, not a dashboard file scan.
```ts
interface RuntimeUsageRecord {
id: string
runtimeKind: RuntimeKind
logicalSessionId: string
runtimeSessionId: string
turnId: string
agentId: string
providerAccountId?: string
provider: string
model: string
timestamp: string
status: 'available' | 'missing' | 'error'
inputTokens: number
cachedInputTokens: number
outputTokens: number
reasoningTokens: number
totalTokens: number
costUsd?: number
}
```
Pinned cc-connect v1.4.1 does not currently expose per-turn token usage through
its documented Bridge or Management API, and an actual binary probe confirms
that enabling `reply_footer` does not add machine-readable usage to Bridge
replies. Therefore this acceptance row is **upstream-blocked**, not complete.
Production ClawX derives turn identity only from cc-connect public session
history. When that history has no usage payload, each assistant turn is
returned with `status: 'missing'` and zero counters so callers can distinguish
"the turn exists but usage is unavailable" from "there is no history". ClawX
does not fill those counters from private cc-connect stores or Codex JSONL.
Test code may use a managed transcript or provider response as an oracle, but
that evidence cannot close the exact-usage runtime-contract row.
`RuntimeProvider.listUsage` is the only Host API usage source. The OpenClaw
adapter owns its existing structured transcript scan; the cc-connect adapter
owns public Management session/history reads and emits one normalized record
per assistant turn. `usage-api` does not call `listSessions`/`loadHistory`
itself and does not know either runtime's storage layout. Runtime records carry
logical and runtime session ids, a stable turn identity, Agent/provider/model
attribution, status, counters, and optional cost/content compatibility fields.
The upstream audit was refreshed on 2026-07-26. npm still marks `1.4.1` as
`latest`; `1.5.0-beta.2` is the newest prerelease. The beta.2 release contains
only a Codex model-visibility fix on top of beta.1 and does not publish a usage
API. The stable and prerelease source trees parse Codex
`thread/tokenUsage/updated` into an internal `ContextUsageReporter`, but the
documented Management and Bridge session detail responses still expose only
message role/content/timestamp. When context display is enabled, the runtime
renders a lossy `[ctx: ~N%]` footer to the platform instead of a structured
per-turn payload. ClawX must not parse that display string or reach into
cc-connect's internal agent/session state. This is why upgrading to the beta or
enabling `reply_footer` does not close the contract.
Upstream PR [cc-connect#1428](https://github.com/chenhg5/cc-connect/pull/1428)
proposes an opt-in Bridge `usage` observer. It is useful directionally, but its
current head is conflicting and is not included in stable v1.4.1 or prerelease
v1.5.0-beta.2.
Its unversioned event contains `session_key`, `turn_id`, input/output/cache
counts and user metadata, but omits `project`, provider/model identity,
reasoning tokens, durable history semantics and replay after reconnect. Those
omissions prevent reliable multi-Agent attribution and historical dashboard
reconstruction, so ClawX must not implement production parity against that
unmerged schema. A future release may use the observer design provided the
published contract addresses these fields or exposes an equivalent durable
Management history field.
Completion requires a pinned cc-connect release to expose a versioned usage
event or history field containing project, session/turn, provider/model, and
token counts, plus documented reconnect/replay behavior or durable history.
ClawX must then map that public payload to `RuntimeUsageRecord`, add a real
API-key/OAuth oracle comparison, and remove the checked-in E2E `fixme`.
`cachedInputTokens` is a subset of input and `reasoningTokens` is a subset of
output. If total is absent, calculate `input + output`; never add cache again.
Cost is shown only when runtime/provider returns an explicit historical value.
Dashboard defaults to the active runtime and offers OpenClaw, cc-connect, and
combined filters.
The shared parser enforces this total rule for both adapters. Public payloads
may expose cache-read/cache-write and reasoning counters independently for
display, but inferred `totalTokens` remains `inputTokens + outputTokens` so
cache and reasoning subsets are never counted twice.
## 10. Channels and Feishu/Lark
Channel account metadata lives under `~/.clawx/app`; app secrets live in the
encrypted credential vault. Generated cc-connect TOML references environment
variables. Connect, disconnect, and delete mean config projection plus
Management API reload/status when the pinned binary lacks per-platform
lifecycle endpoints.
Feishu/Lark replacement evidence requires:
```text
tenant message -> cc-connect platform -> bound project/Agent/workspace
-> Codex -> cc-connect -> tenant reply
```
Both China Feishu and global Lark domain mappings are tested. Status is read
from project platform detail, not inferred from process state. Channel-created
sessions must appear in ClawX history and usage under the bound Agent.
Channel mutations require account-scoped authorization. Runtime hooks may be
used as an evidence collector, not as a second message processor.
Current live-credential evidence proves the Feishu platform reaches
`connected`/`running` through cc-connect, survives Host API disconnect/connect
reload, preserves both the ClawX desktop administrator and configured Channel
administrators, removes the account from managed config on delete, and cleans
up the runtime process. The same real test proves an existing OpenClaw channel
file is a read-only import source: non-secret account metadata is owned by the
canonical runtime config, the app secret is absent from that document and from
plaintext vault bytes, and neither import nor cc-connect-mode delete changes
the compatibility file. Sanitized machine evidence is written to
`artifacts/cc-connect/real-feishu-lifecycle.json`. A tenant-originated inbound
marker and its reply remain a separate manual gate; lifecycle success alone
does not claim message-delivery parity.
## 11. Cron
For the first replacement milestone, cc-connect native cron-expression jobs
are the only supported schedule kind. `at`, `every`, and manual run remain
explicitly unsupported unless the pinned stable binary exposes equivalent
native operations. ClawX must not maintain a second prompt scheduler.
GUI and Channel `/cron` operate the same cc-connect scheduler and store:
- Channel create/update/enable/disable/delete is visible in GUI.
- GUI mutations are visible through Channel `/cron`.
- Scheduled prompt execution returns to the configured Channel through
cc-connect.
- `admin_from` contains ClawX admins and explicit `cron-manager` role members;
other allow-listed users cannot mutate jobs.
- Jobs carry project, session key, workspace, schedule, enabled state, and
runtime ownership.
For prompt/exec jobs without external delivery, ClawX uses the managed local
LINE placeholder session key because cc-connect Cron resolves the first session
key segment as a configured platform. Agent/account/workspace ownership still
comes from the job's project. `clawx:<agent>:<session>` remains a Bridge session
key and must not be passed to the native scheduler. Announce jobs use the real
target platform and recipient key.
Capability metadata exposes `scheduleKinds: ['cron']`, Channel commands, and
the actual support state of manual execution. Unsupported operations are
non-mutating.
cc-connect manual execution is asynchronous: `POST /api/v1/cron/{id}/exec`
acknowledges that a run was triggered, but does not mean the run completed.
ClawX observes completion through the runtime-owned Cron list and maps the
official `last_run` and `last_error` fields to `CronJob.lastRun`; Go's zero
timestamp means the job has never run and is not exposed as a completed run.
Validation must wait for a successful `lastRun` before using public
session/history as delivery evidence.
The Cron UI keeps trigger acknowledgement non-blocking. After the immediate
list refresh, its store observes an unchanged run in the background with a
bounded exponential-backoff refresh until `lastRun` changes, the runtime
auto-removes the job, the user deletes it, the selected runtime changes, or the
job timeout elapses. A repeated trigger supersedes the prior observation. This
polling only observes the runtime-owned scheduler; it never executes the job in
ClawX.
Current real-runtime evidence covers both native scheduler paths with the
bundled cc-connect binary. An enabled exec job fired on an actual minute tick
and wrote its marker from the configured `work_dir`. A Codex OAuth prompt job
also fired on an actual minute tick, entered cc-connect through the managed
project, and exposed its prompt and assistant reply through the public
session-summary/history APIs. The evidence command is
`pnpm run verify:cc-connect:local-real:scheduled-cron`; it does not claim live
tenant-channel delivery, which remains a separate Feishu/Lark credential gate.
Both jobs preserve the cc-connect PID, remain visible through Host API and the
Cron page until cleanup, require delete success plus a second Host API list that
proves the job is absent, and write sanitized machine/visual evidence to
`artifacts/cc-connect/real-scheduled-{exec,prompt}-cron.{json,png}`. The prompt
artifact records only public session keys and success flags; it never records
OAuth material, Management tokens, or temporary absolute paths.
The bundled-runtime E2E also registers a simulated Feishu transport through the
public Bridge protocol and proves Channel `/cron add`, list, disable, enable,
and delete as the projected managed admin are reflected by Host API Cron
operations. A GUI-created announce
job targeting the same Feishu session is visible from Channel `/cron`, and the
runtime PID remains unchanged. Sanitized evidence is written to
`artifacts/cc-connect/real-channel-cron-bridge.json`. This verifies cc-connect
core/platform command routing and one shared native scheduler; it does not
replace live Feishu tenant inbound or scheduled-reply evidence.
The probe advertises Bridge `card` and `buttons` capabilities. Pinned
cc-connect v1.4.1 returns `/cron add` as a usable text acknowledgement and the
`/cron` list as a real card; the test invokes its disable, enable, and delete
callbacks through `card_action` and verifies each mutation through Host API.
Non-approval standalone-button and upstream-triggered delete-message evidence
remain separate from this card/action proof. Preview/update now have an
independent local-real proof: the bundled cc-connect v1.4.1 engine runs against
a deterministic Codex app-server protocol boundary, emits public
`preview_start`/`update_message`, and drives the GUI execution graph plus final
assistant reply. Sanitized evidence is written to
`artifacts/cc-connect/real-rich-progress-bridge.{json,png}`. This proves the
runtime/Bridge/UI integration without claiming a real OpenAI credential; real
OAuth remains a separate gate. Real media is covered independently: the bundled
`cc-connect send` CLI targets an active managed session and emits public Bridge
image/file/audio/video packets. The adapter copies decoded bytes under
`runtimes/cc-connect/media/outgoing/bridge`, session history merges these
runtime-owned attachments with Management API history, renderer final-event
deduplication uses each message id, and Chat keeps `gateway-media` cards visible
even when surrounding process narration is folded into the execution graph.
The real local OpenAI-compatible E2E verifies exact bytes, image preview, all
four GUI cards, and writes sanitized evidence to
`artifacts/cc-connect/real-cli-media-bridge.{json,png}`.
## 12. Health, Doctor, and logs
Runtime ready requires a live process, Management API, Bridge registration,
loaded projects, executable Agent binary, valid required workspace, and scoped
credential checks. A single expired Agent account degrades that Agent rather
than the whole runtime.
`checkHealth({ probe: true })` verifies the child is still alive, the Bridge
WebSocket is currently registered, and every projected project is readable
through Management API. Infrastructure probe failures return `ok: false` with
the failed component; account support/auth diagnostics stay project-scoped so
one invalid account does not mark unrelated Agents unhealthy.
Message preflight resolves the target Agent from the logical session key and
checks that project's provider profile. An invalid default account therefore
does not block an Agent with a valid explicit binding, and an invalid explicit
binding blocks only that Agent before any Bridge message is sent.
Agent create, rename, model/account binding, Channel binding, and delete
operations notify the active runtime. In cc-connect mode they rebuild or
restart cc-connect projects without invoking OpenClaw auth/model projection;
OpenClaw keeps its existing projection and reload behavior.
Skills are sourced from the shared ClawX/OpenClaw-compatible skill registry and
mirrored into every distinct Codex home used by current cc-connect projects.
Runtime start, skill enable/disable, and ClawHub install/uninstall all refresh
every project home, so account isolation does not split skill availability.
Startup order is data lock/version, managed config, skills, binary validation,
process, Management API, Bridge, projects, health, ready. Intentional stop
drains or cancels runs before terminating the process tree. Unexpected crashes
use bounded backoff and eventually enter error state.
Bridge registration is part of startup, not a background best effort. If the
process starts but Bridge registration fails, the provider closes registered
and in-flight WebSockets, terminates the managed process tree, reports `error`,
and leaves no child running. Stop/restart closes sockets that are still waiting
for `register_ack` and suppresses any reconnect scheduled by that close.
Main captures cc-connect stdout/stderr, redacts scoped provider/channel secrets
and common bearer/API-key forms before emission, keeps a bounded in-memory tail,
and writes mode-0600 `runtimes/cc-connect/logs/runtime.log` with size rotation.
Runtime diagnostics combine that stream, matching ClawX manager lines, and a
redacted managed config. Renderer never reads the process pipe or log path
directly.
cc-connect Doctor runs native `doctor user-isolation` against managed config
with an explicit managed `--out` path, then runs bundled `codex doctor --json`
inside the main project's managed `CODEX_HOME`. The adapter writes a
mode-0600 composite JSON audit under `runtimes/cc-connect/audits`; it never uses
the native default `~/.cc-connect/audits`. A Codex project without
`run_as_user` legitimately produces no native user-isolation file, which is
recorded as `auditGenerated: false` rather than treated as missing evidence.
The Codex Doctor subprocess is a provider-owned diagnostic exception only: it
accepts no prompt, creates no chat/session/tool run, and cannot replace or
bypass BridgePlatform delivery.
`doctor.fix` is unsupported in cc-connect mode and is hidden/disabled.
Runtime-neutral Settings strings must not report an OpenClaw Doctor result for
cc-connect.
cc-connect stdout, stderr, structured events, and doctor audits are captured
under `~/.clawx/logs/runtimes/cc-connect` with rotation and pre-write secret
redaction. Diagnostics use the active provider and must not include OpenClaw
gateway logs as cc-connect runtime logs.
## 13. Migration and rollback
Migration steps:
1. Create and lock `~/.clawx` layout.
2. Import ClawX application settings and provider accounts from legacy
Electron userData.
3. Register existing OpenClaw workspaces as external paths.
4. Encrypt provider secrets and create account-level OAuth homes.
5. Move ClawX-owned cc-connect data from legacy userData into the new runtime
directory.
6. Build logical session projection without modifying runtime stores.
7. Start the selected runtime only after migration commits.
Rollback means selecting OpenClaw, stopping cc-connect, and preserving its
managed data. Rollback never deletes credentials, sessions, workspace, or
cc-connect config. A migration failure restores the backup and leaves the prior
data version writable by the prior application.
## 14. Delivery phases and evidence gates
| Phase | Goal and implementation | Required verification | Impact |
| --- | --- | --- | --- |
| A. Contract and dependency | Pin/probe stable cc-connect; add runtime contracts and API client | Binary contract test, bundle manifest, type/unit tests | Shared types; no behavior switch |
| B. Data root and credentials | Add layout, fail-closed pre-write lock, migrations, encrypted vault, OAuth homes | vN to vN+1 and rollback packaged run; real two-Electron ownership/handover; secret scan | All persistent paths and runtime/scheduler startup |
| C. Workspace and skills | Registry, OpenClaw reuse, project `work_dir`, shared skill projection | Two-Agent isolation; real skill invocation; source-checkout negative test | Agent create/delete and files |
| D. Bridge chat/events | Official Bridge send, tools, approvals, cancellation, replay | Real API-key and OAuth tool-heavy chats; disconnect/replay; screenshots | Core communication path |
| E. Sessions and usage | Official APIs, logical binding, per-turn usage | Named/cross-Agent/Channel/restart/delete; token oracle comparison | Sidebar, history, Models |
| F. Channels and cron | Feishu/Lark full path; one native scheduler for GUI and Channel | Tenant inbound/reply; Channel/GUI Cron bidirectional CRUD and scheduled reply | Channel and Cron surfaces |
| G. Health and diagnostics | Scoped health, native doctor, real logs | Crash, port conflict, expired auth, doctor audit, log redaction | Settings and diagnostics |
| H. Packaging and release | Offline resources and platform smoke | Source bundle integrity; `afterPack` target verification; final macOS x64/arm64, Windows x64, Linux x64/arm64 resource checks; native Electron/Host API/runtime startup, Cron/Doctor, rollback, PID/port/process cleanup | Build/release only |
Every phase must produce code-level route evidence and actual runtime evidence
under `artifacts/cc-connect/<run-id>/`:
- `api/`: sanitized requests and responses.
- `logs/`: ClawX, cc-connect, Bridge, doctor, and scheduler excerpts.
- `screenshots/`: ClawX and Channel UI evidence.
- `fs/`: sanitized manifests, workspace trees, and migration checks.
- `report.json`: acceptance row, command, status, evidence paths, and gaps.
Mock-only evidence cannot close a real-runtime row. Opt-in credentials may stay
outside normal CI, but replacement readiness remains partial until the latest
report contains PASS evidence for real OAuth, external OpenAI API key, Feishu
inbound/reply, native Channel Cron, and packaged target platforms.
Deterministic Electron evidence covers same-account browser re-login projection
and protects Codex-refreshed managed auth from stale-vault rollback. A live
expired-token refresh failure followed by browser re-login still requires an
explicit real OAuth fixture and remains an external validation row.
## 15. Acceptance and explicit non-parity
cc-connect replacement is complete only when:
- No cc-connect Chat, session, tool, approval, cancellation, or usage path
launches or talks to Codex outside cc-connect.
- No shared cc-connect service writes OpenClaw config or cc-connect private
session files.
- GUI Chat, Feishu/Lark, and native Cron all execute through cc-connect and the
bound Agent/account/workspace.
- OpenAI OAuth and API-key modes pass real end-to-end tests with account
isolation.
- Session/history/title/delete and token usage match the shared runtime
contract across Agent and Channel cases.
- Skills are actually invoked, health/Doctor/logs are runtime-aware, and
packaged applications run offline.
- Required logs and screenshots exist and sensitive-data scans pass.
Accepted non-parity for the first milestone:
- cc-connect remains behind Developer Mode.
- cc-connect Doctor Fix does not replace OpenClaw Doctor Fix.
- Only native cron expressions are supported; `at` and `every` are not
emulated.
- Real credential and all-platform release checks remain opt-in until a
separate CI policy decision.
+12
View File
@@ -68,6 +68,10 @@ mac:
to: bin
- from: resources/cli/posix/
to: cli/
- from: build/cc-connect/darwin-${arch}/
to: cc-connect/
- from: build/codex/darwin-${arch}/
to: codex/
category: public.app-category.productivity
icon: resources/icons/icon.icns
target:
@@ -119,6 +123,10 @@ win:
to: bin
- from: resources/cli/win32/
to: cli/
- from: build/cc-connect/win32-${arch}/
to: cc-connect/
- from: build/codex/win32-${arch}/
to: codex/
icon: resources/icons/icon.ico
target:
- target: nsis
@@ -147,6 +155,10 @@ linux:
to: bin
- from: resources/cli/posix/
to: cli/
- from: build/cc-connect/linux-${arch}/
to: cc-connect/
- from: build/codex/linux-${arch}/
to: codex/
icon: resources/icons
target:
- target: AppImage
+4 -1
View File
@@ -14,7 +14,10 @@ class DiagnosticsExtension implements HostApiProviderExtension {
}
getHostApiContributions(ctx: ExtensionContext): HostApiContribution[] {
const diagnostics = createDiagnosticsApi({ gatewayManager: ctx.gatewayManager });
const diagnostics = createDiagnosticsApi({
gatewayManager: ctx.gatewayManager,
runtimeManager: ctx.runtimeManager,
});
const actions: Record<string, RuntimeHostAction> = {
gatewaySnapshot: () => diagnostics.gatewaySnapshot(),
acpTrace: () => diagnostics.acpTrace(),
+2
View File
@@ -1,5 +1,6 @@
import type { BrowserWindow } from 'electron';
import type { GatewayManager } from '../gateway/manager';
import type { RuntimeManager } from '../runtime/manager';
import type { HostApiContribution, HostApiContributionRegistrar } from '../main/ipc/host-contract';
import type {
MarketplaceSearchParams,
@@ -12,6 +13,7 @@ import type {
export interface ExtensionContext {
gatewayManager: GatewayManager;
runtimeManager: RuntimeManager;
getMainWindow: () => BrowserWindow | null;
hostApi: HostApiContributionRegistrar;
}
+12 -6
View File
@@ -53,15 +53,13 @@ export function normalizeGatewayChatRuntimeEvent(payload: unknown): ChatRuntimeE
: null;
}
if (phase === 'end' || phase === 'completed' || phase === 'done' || phase === 'finished') {
if (phase === 'completed' || phase === 'done' || phase === 'finished') {
const base = withBase('run.ended', raw);
const aborted = phase === 'end' && data.aborted === true;
return base
? {
...base,
status: aborted ? 'aborted' : 'completed',
status: 'completed',
endedAt: readNumber(data.endedAt),
...(aborted ? { error: readString(data.error) } : {}),
livenessState: readString(data.livenessState),
replayInvalid: typeof data.replayInvalid === 'boolean' ? data.replayInvalid : undefined,
stopReason: readString(data.stopReason),
@@ -92,8 +90,6 @@ export function normalizeGatewayChatRuntimeEvent(payload: unknown): ChatRuntimeE
status: 'aborted',
endedAt: readNumber(data.endedAt),
error: readString(data.error),
livenessState: readString(data.livenessState),
replayInvalid: typeof data.replayInvalid === 'boolean' ? data.replayInvalid : undefined,
stopReason: readString(data.stopReason),
}
: null;
@@ -207,6 +203,16 @@ export function normalizeGatewayChatRuntimeEvent(payload: unknown): ChatRuntimeE
phase: readString(data.phase),
status: readString(data.status),
message: readString(data.message),
actions: Array.isArray(data.actions)
? data.actions.flatMap((action) => {
if (!action || typeof action !== 'object') return [];
const record = action as Record<string, unknown>;
const value = readString(record.action);
if (!value) return [];
const label = readString(record.label);
return [{ action: value, ...(label ? { label } : {}) }];
})
: undefined,
}
: null;
}
+4 -5
View File
@@ -1,6 +1,6 @@
import { app } from 'electron';
import path from 'path';
import { existsSync, readFileSync, mkdirSync, readdirSync, symlinkSync } from 'fs';
import { existsSync, readFileSync, mkdirSync, readdirSync, rmSync, symlinkSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
@@ -34,7 +34,6 @@ import { syncProxyConfigToOpenClaw } from '../utils/openclaw-proxy';
import { logger } from '../utils/logger';
import { prependPathEntry } from '../utils/env-path';
import { copyPluginFromNodeModules, fixupPluginManifest, cpSyncSafe, buildCandidateSources, repairTrustedOfficialPluginInstallRecords, removeTrustedOfficialPluginInstallRecord, syncTrustedOfficialPluginInstallRecord, 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 } from '../utils/openclaw-upgrade-snapshot';
import { stripSystemdSupervisorEnv } from './config-sync-env';
@@ -121,7 +120,7 @@ function cleanupStaleBuiltInExtensions(): void {
if (existsSync(fsPath(extDir))) {
logger.info(`[plugin] Removing stale built-in extension copy: ${ext}`);
try {
safeRmSync(fsPath(extDir));
rmSync(fsPath(extDir), { recursive: true, force: true });
} catch (err) {
logger.warn(`[plugin] Failed to remove stale extension ${ext}:`, err);
}
@@ -193,7 +192,7 @@ function ensureConfiguredPluginsUpgraded(configuredChannels: string[]): boolean
logger.info(`[plugin] ${isInstalled ? 'Auto-upgrading' : 'Installing'} ${channelType} plugin${isInstalled ? `: ${installedVersion}${sourceVersion}` : `: ${sourceVersion}`} (bundled)`);
try {
mkdirSync(fsPath(join(homedir(), '.openclaw', 'extensions')), { recursive: true });
safeRmSync(fsPath(targetDir));
rmSync(fsPath(targetDir), { recursive: true, force: true });
cpSyncSafe(bundledDir, targetDir);
fixupPluginManifest(targetDir);
syncTrustedOfficialPluginInstallRecord(dirName, targetDir);
@@ -259,7 +258,7 @@ function cleanupUnconfiguredChannelPlugins(configuredChannels: string[]): boolea
logger.info(`[plugin] Removing unconfigured channel plugin: ${channelType} (${dirName})`);
try {
safeRmSync(fsPath(targetDir));
rmSync(fsPath(targetDir), { recursive: true, force: true });
} catch (err) {
logger.warn(`[plugin] Failed to remove unconfigured channel plugin ${channelType}:`, err);
succeeded = false;
+83 -51
View File
@@ -5,12 +5,10 @@
import { app, BrowserWindow, nativeImage, session, shell, type Session } from 'electron';
import { join } from 'path';
import { GatewayManager } from '../gateway/manager';
import {
bindCronLiveRunBroker,
CronLiveRunBroker,
} from '../services/cron-live-run-broker';
import { RuntimeManager } from '../runtime/manager';
import { OpenClawRuntimeProvider } from '../runtime/openclaw-provider';
import { CcConnectRuntimeProvider } from '../runtime/cc-connect-provider';
import { registerIpcHandlers } from './ipc-handlers';
import { HOST_EVENT_CHANNELS } from '@shared/host-events/contract';
import { HostApiRegistry } from './ipc/host-invoke';
import { createTray } from './tray';
import { createMenu } from './menu';
@@ -58,19 +56,22 @@ import { deviceOAuthManager } from '../utils/device-oauth';
import { browserOAuthManager } from '../utils/browser-oauth';
import { whatsAppLoginManager } from '../utils/whatsapp-login';
import { syncAllProviderAuthToRuntime } from '../services/providers/provider-runtime-sync';
import { getClawXDataLayout, initializeClawXDataLayout } from '../utils/clawx-data-layout';
import { migrateLegacyProviderSecretsToVault } from '../services/secrets/secret-store';
import { migrateLegacyClawXData } from '../utils/clawx-data-migration';
const WINDOWS_APP_USER_MODEL_ID = 'app.clawx.desktop';
const isE2EMode = process.env.CLAWX_E2E === '1';
const requestedUserDataDir = process.env.CLAWX_USER_DATA_DIR?.trim();
const enforceWriterLockInE2E = process.env.CLAWX_E2E_ENFORCE_WRITER_LOCK === '1';
const requestedRemoteDebuggingPort = process.env.CLAWX_REMOTE_DEBUGGING_PORT?.trim();
const legacyElectronUserDataDir = app.getPath('userData');
const clawXDataLayout = getClawXDataLayout();
if (requestedRemoteDebuggingPort) {
app.commandLine.appendSwitch('remote-debugging-port', requestedRemoteDebuggingPort);
}
if (isE2EMode && requestedUserDataDir) {
app.setPath('userData', requestedUserDataDir);
}
app.setPath('userData', clawXDataLayout.electronUserDataDir);
// Disable GPU hardware acceleration globally for maximum stability across
// all GPU configurations (no GPU, integrated, discrete).
@@ -109,12 +110,17 @@ if (!gotElectronLock) {
}
let releaseProcessInstanceFileLock: () => void = () => {};
let gotFileLock = true;
if (gotElectronLock && !isE2EMode) {
if (gotElectronLock && (!isE2EMode || enforceWriterLockInE2E)) {
try {
const fileLock = acquireProcessInstanceFileLock({
userDataDir: app.getPath('userData'),
lockName: 'clawx',
force: true, // Electron lock already guarantees exclusivity; force-clean orphan/recycled-PID locks
userDataDir: clawXDataLayout.locksDir,
lockName: 'writer',
lockPath: clawXDataLayout.writerLockPath,
metadata: {
appVersion: app.getVersion(),
channel: process.env.CLAWX_RELEASE_CHANNEL?.trim() || (app.isPackaged ? 'stable' : 'dev'),
executable: process.execPath,
},
});
gotFileLock = fileLock.acquired;
releaseProcessInstanceFileLock = fileLock.release;
@@ -130,15 +136,28 @@ if (gotElectronLock && !isE2EMode) {
app.exit(0);
}
} catch (error) {
console.warn('[ClawX] Failed to acquire process instance file lock; continuing with Electron single-instance lock only', error);
gotFileLock = false;
console.error('[ClawX] Failed to acquire process instance file lock; refusing to start a shared-root writer', error);
app.exit(1);
}
}
const gotTheLock = gotElectronLock && gotFileLock;
if (gotTheLock) {
try {
// No shared-root state may be created or migrated until this process owns
// the cross-install writer lock.
initializeClawXDataLayout(clawXDataLayout);
} catch (error) {
releaseProcessInstanceFileLock();
throw error;
}
}
// Global references
let mainWindow: BrowserWindow | null = null;
let gatewayManager!: GatewayManager;
let cronLiveRunBroker!: CronLiveRunBroker;
let runtimeManager!: RuntimeManager;
let clawHubService!: ClawHubService;
const hostApiRegistry = new HostApiRegistry();
const webBrowserGuestRegistry = new WebBrowserGuestRegistry();
@@ -326,6 +345,17 @@ async function initialize(): Promise<void> {
logger.debug(
`Runtime: platform=${process.platform}/${process.arch}, electron=${process.versions.electron}, node=${process.versions.node}, packaged=${app.isPackaged}, pid=${process.pid}, ppid=${process.ppid}`
);
const legacyMigration = await migrateLegacyClawXData({
legacyElectronUserDataDir,
layout: clawXDataLayout,
});
if (legacyMigration.copied.length > 0) {
logger.info(`Imported ${legacyMigration.copied.length} legacy ClawX data path(s) into ${clawXDataLayout.root}`);
}
const migratedSecretCount = await migrateLegacyProviderSecretsToVault();
if (migratedSecretCount > 0) {
logger.info(`Migrated ${migratedSecretCount} provider credential account(s) into the encrypted ClawX vault`);
}
webBrowserSession = configureWebBrowserSession({
registry: webBrowserGuestRegistry,
@@ -378,7 +408,7 @@ async function initialize(): Promise<void> {
// Register IPC handlers
registerIpcHandlers(
gatewayManager,
cronLiveRunBroker,
runtimeManager,
clawHubService,
window,
hostApiRegistry,
@@ -386,6 +416,7 @@ async function initialize(): Promise<void> {
webBrowserGuestRegistry,
);
await runtimeManager.getActiveKind();
loadMainWindow(window);
// Create system tray
@@ -396,6 +427,7 @@ async function initialize(): Promise<void> {
// Initialize extension system
await extensionRegistry.initialize({
gatewayManager,
runtimeManager,
getMainWindow: () => mainWindow,
hostApi: {
register: (extensionId, contributions) => (
@@ -472,55 +504,47 @@ async function initialize(): Promise<void> {
// Bridge gateway and host-side events before any auto-start logic runs, so
// renderer subscribers observe the full startup lifecycle.
gatewayManager.on('status', (status: { state: string }) => {
runtimeManager.on('status', (status: { state: string; runtimeKind?: string }) => {
sendMainWindowEvent('gateway:status-changed', status);
if (status.state === 'running' && !isE2EMode) {
if (status.runtimeKind === 'openclaw' && status.state === 'running' && !isE2EMode) {
void ensureClawXContext().catch((error) => {
logger.warn('Failed to re-merge ClawX context after gateway reconnect:', error);
});
}
});
gatewayManager.on('error', (error) => {
runtimeManager.on('error', (error) => {
sendMainWindowEvent('gateway:error', { message: error.message });
});
gatewayManager.on('notification', (notification) => {
runtimeManager.on('notification', (notification) => {
sendMainWindowEvent('gateway:notification', notification);
});
gatewayManager.on('gateway:health', (data) => {
runtimeManager.on('gateway:health', (data) => {
sendMainWindowEvent('gateway:health-changed', data);
});
gatewayManager.on('gateway:presence', (data) => {
runtimeManager.on('gateway:presence', (data) => {
sendMainWindowEvent('gateway:presence-changed', data);
});
gatewayManager.on('chat:message', (data) => {
runtimeManager.on('chat:message', (data) => {
sendMainWindowEvent('gateway:chat-message', data);
});
gatewayManager.on('chat:runtime-event', (data) => {
runtimeManager.on('chat:runtime-event', (data) => {
sendMainWindowEvent('chat:runtime-event', data);
});
gatewayManager.on('channel:status', (data) => {
runtimeManager.on('channel:status', (data) => {
sendMainWindowEvent('gateway:channel-status', data);
});
gatewayManager.on('exit', (code) => {
runtimeManager.on('exit', (code) => {
sendMainWindowEvent('gateway:exit', { code });
});
bindCronLiveRunBroker({
gatewayManager,
broker: cronLiveRunBroker,
publishChange: (change) => {
sendMainWindowEvent(HOST_EVENT_CHANNELS.cron.liveRunOverlayChanged, change);
},
});
deviceOAuthManager.on('oauth:code', (payload) => {
sendMainWindowEvent('oauth:code', payload);
});
@@ -561,12 +585,14 @@ async function initialize(): Promise<void> {
const gatewayAutoStart = await getSetting('gatewayAutoStart');
if (!isE2EMode && gatewayAutoStart) {
try {
await syncAllProviderAuthToRuntime();
logger.debug('Auto-starting Gateway...');
await gatewayManager.start();
logger.info('Gateway auto-start succeeded');
if (await runtimeManager.getActiveKind() === 'openclaw') {
await syncAllProviderAuthToRuntime();
}
logger.debug(`Auto-starting ${await runtimeManager.getActiveKind()} runtime...`);
await runtimeManager.start();
logger.info('Runtime auto-start succeeded');
} catch (error) {
logger.error('Gateway auto-start failed:', error);
logger.error('Runtime auto-start failed:', error);
mainWindow?.webContents.send('gateway:error', String(error));
}
} else if (isE2EMode) {
@@ -619,7 +645,10 @@ if (gotTheLock) {
}
gatewayManager = new GatewayManager();
cronLiveRunBroker = new CronLiveRunBroker();
runtimeManager = new RuntimeManager({
openclaw: new OpenClawRuntimeProvider(gatewayManager),
ccConnect: new CcConnectRuntimeProvider(),
});
clawHubService = new ClawHubService();
// Register builtin extensions and load manifest
@@ -689,8 +718,8 @@ if (gotTheLock) {
void extensionRegistry.teardownAll();
const stopPromise = gatewayManager.stop().catch((err) => {
logger.warn('gatewayManager.stop() error during quit:', err);
const stopPromise = runtimeManager.stop().catch((err) => {
logger.warn('runtimeManager.stop() error during quit:', err);
});
const timeoutPromise = new Promise<'timeout'>((resolve) => {
setTimeout(() => resolve('timeout'), 5000);
@@ -698,14 +727,16 @@ if (gotTheLock) {
void Promise.race([stopPromise.then(() => 'stopped' as const), timeoutPromise]).then((result) => {
if (result === 'timeout') {
logger.warn('Gateway shutdown timed out during app quit; proceeding with forced quit');
void gatewayManager.forceTerminateOwnedProcessForQuit().then((terminated) => {
if (terminated) {
logger.warn('Forced gateway process termination completed after quit timeout');
}
}).catch((err) => {
logger.warn('Forced gateway termination failed after quit timeout:', err);
});
logger.warn('Runtime shutdown timed out during app quit; proceeding with forced quit');
if (runtimeManager.getActiveProvider().kind === 'openclaw') {
void gatewayManager.forceTerminateOwnedProcessForQuit().then((terminated) => {
if (terminated) {
logger.warn('Forced gateway process termination completed after quit timeout');
}
}).catch((err) => {
logger.warn('Forced gateway termination failed after quit timeout:', err);
});
}
}
markQuitCleanupCompleted(quitLifecycleState);
app.quit();
@@ -719,6 +750,7 @@ if (gotTheLock) {
logger.error(`${reason}:`, error);
try {
void gatewayManager?.stop().catch(() => { /* ignore */ });
void runtimeManager?.stop().catch(() => { /* ignore */ });
} catch {
// ignore — stop() may not be callable if state is corrupted
}
@@ -738,4 +770,4 @@ if (gotTheLock) {
}
// Export for testing
export { mainWindow, gatewayManager };
export { mainWindow, gatewayManager, runtimeManager };
+52 -46
View File
@@ -8,6 +8,7 @@ import { homedir } from 'node:os';
import { join, extname, basename, resolve, sep, relative } from 'node:path';
import { syncMacTrafficLightPosition } from './traffic-light-layout';
import { GatewayManager } from '../gateway/manager';
import { RuntimeManager } from '../runtime/manager';
import { ClawHubService } from '../gateway/clawhub';
import {
type ProviderConfig,
@@ -29,7 +30,7 @@ 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';
import { getCcConnectMediaDir, getOpenClawMediaDir } from '../utils/runtime-media-paths';
import { getProviderService } from '../services/providers/provider-service';
import {
getOpenClawProviderKey,
@@ -61,13 +62,12 @@ import { AcpSessionAccessRegistry } from '../services/acp-session-access-registr
import { createAttachmentAccess, StagedAttachmentRegistry } from '../services/attachment-access';
import { createAttachmentOpenWithService } from '../services/attachment-open-with';
import { createCronApi } from '../services/cron-api';
import type { CronLiveRunBroker } from '../services/cron-live-run-broker';
import { createFilesApi } from '../services/files-api';
import { createMediaApi } from '../services/media-api';
import { createProvidersApi } from '../services/providers-api';
import { createSessionsApi } from '../services/sessions-api';
import { createSkillsApi } from '../services/skills-api';
import { createUsageApi } from '../services/usage-api';
import { createUsageApi, getRecentTokenHistoryForRuntime } from '../services/usage-api';
import { createWebBrowserApi } from '../services/web-browser-api';
import type { WebBrowserGuestRegistry } from './web-browser-policy';
import {
@@ -86,7 +86,7 @@ const gatewayRpcBackpressure = new GatewayRpcBackpressure();
*/
export function registerIpcHandlers(
gatewayManager: GatewayManager,
cronLiveRunBroker: CronLiveRunBroker,
runtimeManager: RuntimeManager,
clawHubService: ClawHubService,
mainWindow: BrowserWindow,
hostApiRegistry: HostApiRegistry,
@@ -94,12 +94,12 @@ export function registerIpcHandlers(
registry: WebBrowserGuestRegistry,
): void {
// Unified request protocol (non-breaking: legacy channels remain available)
registerUnifiedRequestHandlers(gatewayManager);
registerUnifiedRequestHandlers(gatewayManager, runtimeManager);
// Typed host invoke handlers (new renderer facade; legacy channels remain available)
registerTypedHostHandlers(
gatewayManager,
cronLiveRunBroker,
runtimeManager,
clawHubService,
mainWindow,
hostApiRegistry,
@@ -108,13 +108,13 @@ export function registerIpcHandlers(
);
// Gateway handlers
registerGatewayHandlers(gatewayManager);
registerGatewayHandlers(runtimeManager);
// OpenClaw handlers
registerOpenClawHandlers();
// Provider handlers
registerProviderHandlers(gatewayManager);
registerProviderHandlers(gatewayManager, runtimeManager);
// Shell handlers
registerShellHandlers();
@@ -129,7 +129,7 @@ export function registerIpcHandlers(
registerSettingsHandlers(gatewayManager);
// Usage handlers
registerUsageHandlers();
registerUsageHandlers(runtimeManager);
// Cron task handlers (proxy to Gateway RPC)
registerCronHandlers(gatewayManager);
@@ -146,7 +146,7 @@ export function registerIpcHandlers(
function registerTypedHostHandlers(
gatewayManager: GatewayManager,
cronLiveRunBroker: CronLiveRunBroker,
runtimeManager: RuntimeManager,
clawHubService: ClawHubService,
mainWindow: BrowserWindow,
hostApiRegistry: HostApiRegistry,
@@ -162,7 +162,7 @@ function registerTypedHostHandlers(
openWith: attachmentOpenWith,
});
hostApiRegistry.registerCoreServices({
app: createAppApi(),
app: createAppApi(runtimeManager),
openclaw: createOpenClawApi(),
shell: createShellApi(),
webBrowser: createWebBrowserApi({ browserSession, registry }),
@@ -170,28 +170,34 @@ function registerTypedHostHandlers(
window: createWindowApi(mainWindow),
updates: createUpdatesApi(appUpdater),
uv: createUvApi(),
settings: createSettingsApi(gatewayManager),
gateway: createGatewayApi(gatewayManager, gatewayRpcBackpressure),
settings: createSettingsApi(gatewayManager, runtimeManager),
gateway: createGatewayApi(runtimeManager, gatewayRpcBackpressure, gatewayManager),
logs: createLogsApi(),
channels: createChannelsApi({ gatewayManager, mainWindow }),
agents: createAgentsApi({ gatewayManager }),
providers: createProvidersApi({ gatewayManager, mainWindow }),
channels: createChannelsApi({ gatewayManager, runtimeManager, mainWindow }),
agents: createAgentsApi({ gatewayManager, runtimeManager }),
providers: createProvidersApi({ gatewayManager, runtimeManager, mainWindow }),
files: createFilesApi({
runtimeManager,
attachmentAccess,
openWith: attachmentOpenWith,
stagedAttachments,
}),
media: createMediaApi({ attachmentAccess }),
sessions: createSessionsApi(),
chat: createChatApi({ gatewayManager, mainWindow, acpSessionAccessRegistry }),
cron: createCronApi({ gatewayManager, cronLiveRunBroker }),
skills: createSkillsApi({ clawHubService, gatewayManager }),
usage: createUsageApi(),
media: createMediaApi({ runtimeManager, attachmentAccess }),
sessions: createSessionsApi(runtimeManager),
chat: createChatApi({
gatewayManager,
runtimeManager,
mainWindow,
acpSessionAccessRegistry,
}),
cron: createCronApi({ gatewayManager, runtimeManager }),
skills: createSkillsApi({ clawHubService, gatewayManager, runtimeManager }),
usage: createUsageApi(runtimeManager),
});
registerHostInvokeHandler(hostApiRegistry);
}
function registerUnifiedRequestHandlers(gatewayManager: GatewayManager): void {
function registerUnifiedRequestHandlers(gatewayManager: GatewayManager, runtimeManager: RuntimeManager): void {
const providerService = getProviderService();
const handleProxySettingsChange = async () => {
const settings = await getAllSettings();
@@ -541,12 +547,7 @@ function registerUnifiedRequestHandlers(gatewayManager: GatewayManager): void {
}
case 'usage': {
if (request.action === 'recentTokenHistory') {
const payload = request.payload as { limit?: number } | number | undefined;
const limit = typeof payload === 'number' ? payload : payload?.limit;
const safeLimit = typeof limit === 'number' && Number.isFinite(limit)
? Math.max(Math.floor(limit), 1)
: undefined;
data = await getRecentTokenUsageHistory(safeLimit);
data = await getRecentTokenHistoryForRuntime(request.payload, runtimeManager);
break;
}
return {
@@ -719,10 +720,10 @@ function registerCronHandlers(gatewayManager: GatewayManager): void {
/**
* Gateway-related IPC handlers
*/
function registerGatewayHandlers(gatewayManager: GatewayManager): void {
function registerGatewayHandlers(runtimeManager: RuntimeManager): void {
// Get Gateway status
ipcMain.handle('gateway:status', () => {
return gatewayManager.getStatus();
return runtimeManager.getStatus();
});
// Gateway RPC call
@@ -732,7 +733,7 @@ function registerGatewayHandlers(gatewayManager: GatewayManager): void {
method,
params,
timeoutMs,
(rpcMethod, rpcParams, rpcTimeoutMs) => gatewayManager.rpc(rpcMethod, rpcParams, rpcTimeoutMs),
(rpcMethod, rpcParams, rpcTimeoutMs) => runtimeManager.rpc(rpcMethod, rpcParams, rpcTimeoutMs),
);
return { success: true, result };
} catch (error) {
@@ -811,7 +812,10 @@ function registerWhatsAppHandlers(mainWindow: BrowserWindow): void {
/**
* Provider-related IPC handlers
*/
function registerProviderHandlers(gatewayManager: GatewayManager): void {
function registerProviderHandlers(
gatewayManager: GatewayManager,
runtimeManager: RuntimeManager,
): void {
const providerService = getProviderService();
const legacyProviderChannelsWarned = new Set<string>();
const logLegacyProviderChannel = (channel: string): void => {
@@ -829,9 +833,14 @@ function registerProviderHandlers(gatewayManager: GatewayManager): void {
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);
browserOAuthManager.on('oauth:success', async ({ provider, accountId }) => {
try {
if (await runtimeManager.getActiveKind() !== 'openclaw') return;
logger.info(`[IPC] Scheduling Gateway restart after ${provider} OAuth success for ${accountId}...`);
gatewayManager.debouncedRestart(8000);
} catch (error) {
logger.warn('[IPC] Failed to resolve active runtime after browser OAuth success:', error);
}
});
// Get all providers with key info
@@ -1230,12 +1239,9 @@ function registerSettingsHandlers(gatewayManager: GatewayManager): void {
return { success: true, settings };
});
}
function registerUsageHandlers(): void {
ipcMain.handle('usage:recentTokenHistory', async (_, limit?: number) => {
const safeLimit = typeof limit === 'number' && Number.isFinite(limit)
? Math.max(Math.floor(limit), 1)
: undefined;
return await getRecentTokenUsageHistory(safeLimit);
function registerUsageHandlers(runtimeManager: RuntimeManager): void {
ipcMain.handle('usage:recentTokenHistory', async (_, payload?: number | { limit?: number; runtimeKind?: unknown }) => {
return await getRecentTokenHistoryForRuntime(payload, runtimeManager);
});
}
/**
@@ -1319,7 +1325,7 @@ function getMimeType(ext: string): string {
return EXT_MIME_MAP[ext.toLowerCase()] || 'application/octet-stream';
}
const OUTBOUND_DIR = join(homedir(), '.openclaw', 'media', 'outbound');
const OPENCLAW_OUTBOUND_DIR = join(getOpenClawMediaDir(), 'outbound');
// ── File preview (sandboxed) ──────────────────────────────────────────
//
@@ -1388,14 +1394,14 @@ function isPathInside(child: string, parent: string): boolean {
*/
function getFilePreviewWriteRoots(): string[] {
const roots: string[] = [];
const openclawDir = join(homedir(), '.openclaw');
roots.push(resolve(openclawDir));
roots.push(resolve(join(homedir(), '.openclaw')));
roots.push(resolve(getCcConnectMediaDir()));
try {
roots.push(resolve(app.getPath('userData')));
} catch {
// ignore — userData should always exist
}
roots.push(resolve(OUTBOUND_DIR));
roots.push(resolve(OPENCLAW_OUTBOUND_DIR));
return roots;
}
+113 -86
View File
@@ -1,30 +1,50 @@
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
const LOCK_SCHEMA = 'clawx-instance-lock';
const LOCK_VERSION = 1;
const LEGACY_LOCK_VERSION = 1;
const STRUCTURED_LOCK_VERSION = 2;
export interface StructuredLockContent {
schema: string;
version: number;
pid: number;
ownerToken?: string;
appVersion?: string;
channel?: string;
executable?: string;
startedAt?: string;
heartbeatAt?: string;
}
export interface ProcessInstanceFileLock {
acquired: boolean;
lockPath: string;
ownerPid?: number;
ownerFormat?: 'legacy' | 'structured' | 'unknown';
ownerDetails?: StructuredLockContent;
release: () => void;
}
export interface ProcessInstanceLockMetadata {
appVersion: string;
channel: string;
executable: string;
startedAt?: string;
}
export interface ProcessInstanceFileLockOptions {
userDataDir: string;
lockName: string;
pid?: number;
isPidAlive?: (pid: number) => boolean;
/**
* When true, unconditionally remove any existing lock file before attempting
* to acquire. Use this when an external mechanism (e.g. Electron's
* `requestSingleInstanceLock`) already guarantees that no other real instance
* is running, so a surviving lock file can only be stale (orphan child
* process, PID recycling on Windows, etc.).
*/
/** Legacy escape hatch. New shared-data-root callers must not use it. */
force?: boolean;
lockPath?: string;
metadata?: ProcessInstanceLockMetadata;
heartbeatIntervalMs?: number;
heartbeatExpiryMs?: number;
}
function defaultPidAlive(pid: number): boolean {
@@ -32,51 +52,35 @@ function defaultPidAlive(pid: number): boolean {
process.kill(pid, 0);
return true;
} catch (error) {
const errno = (error as NodeJS.ErrnoException).code;
return errno !== 'ESRCH';
return (error as NodeJS.ErrnoException).code !== 'ESRCH';
}
}
type ParsedLockOwner =
| { kind: 'legacy'; pid: number }
| { kind: 'structured'; pid: number }
| { kind: 'structured'; pid: number; details: StructuredLockContent }
| { kind: 'unknown' };
interface StructuredLockContent {
schema: string;
version: number;
pid: number;
}
function parsePositivePid(raw: string): number | undefined {
if (!/^\d+$/.test(raw)) {
return undefined;
}
if (!/^\d+$/.test(raw)) return undefined;
const parsed = Number.parseInt(raw, 10);
if (!Number.isFinite(parsed) || parsed <= 0) {
return undefined;
}
return parsed;
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
}
function parseStructuredLockContent(raw: string): StructuredLockContent | undefined {
try {
const parsed = JSON.parse(raw) as Partial<StructuredLockContent>;
if (
parsed?.schema === LOCK_SCHEMA
&& parsed?.version === LOCK_VERSION
&& typeof parsed?.pid === 'number'
parsed.schema === LOCK_SCHEMA
&& (parsed.version === LEGACY_LOCK_VERSION || parsed.version === STRUCTURED_LOCK_VERSION)
&& typeof parsed.pid === 'number'
&& Number.isFinite(parsed.pid)
&& parsed.pid > 0
) {
return {
schema: parsed.schema,
version: parsed.version,
pid: parsed.pid,
};
return parsed as StructuredLockContent;
}
} catch {
// ignore parse errors
// Unknown content is never removed automatically.
}
return undefined;
}
@@ -85,111 +89,135 @@ function readLockOwner(lockPath: string): ParsedLockOwner {
try {
const raw = readFileSync(lockPath, 'utf8').trim();
const legacyPid = parsePositivePid(raw);
if (legacyPid !== undefined) {
return { kind: 'legacy', pid: legacyPid };
}
if (legacyPid !== undefined) return { kind: 'legacy', pid: legacyPid };
const structured = parseStructuredLockContent(raw);
if (structured) {
return { kind: 'structured', pid: structured.pid };
}
if (structured) return { kind: 'structured', pid: structured.pid, details: structured };
} catch {
// ignore read errors
// Missing and unreadable lock files have unknown ownership.
}
return { kind: 'unknown' };
}
function writeLockAtomic(lockPath: string, content: string): void {
const temporaryPath = `${lockPath}.${process.pid}.${randomUUID()}.tmp`;
try {
writeFileSync(temporaryPath, content, { encoding: 'utf8', mode: 0o600 });
renameSync(temporaryPath, lockPath);
} catch (error) {
rmSync(temporaryPath, { force: true });
throw error;
}
}
function heartbeatExpired(owner: ParsedLockOwner, expiryMs: number): boolean {
if (owner.kind !== 'structured') return true;
if (!owner.details.heartbeatAt) return true;
const heartbeat = Date.parse(owner.details.heartbeatAt);
return !Number.isFinite(heartbeat) || Date.now() - heartbeat > expiryMs;
}
export function acquireProcessInstanceFileLock(
options: ProcessInstanceFileLockOptions,
): ProcessInstanceFileLock {
const pid = options.pid ?? process.pid;
const isPidAlive = options.isPidAlive ?? defaultPidAlive;
const lockPath = options.lockPath ?? join(options.userDataDir, `${options.lockName}.instance.lock`);
const heartbeatExpiryMs = options.heartbeatExpiryMs ?? 30_000;
mkdirSync(dirname(lockPath), { recursive: true });
mkdirSync(options.userDataDir, { recursive: true });
const lockPath = join(options.userDataDir, `${options.lockName}.instance.lock`);
// When force mode is enabled, unconditionally remove any existing lock file
// before attempting acquisition. This is safe because an external mechanism
// (Electron's requestSingleInstanceLock) already guarantees exclusivity.
if (options.force && existsSync(lockPath)) {
const staleOwner = readLockOwner(lockPath);
try {
rmSync(lockPath, { force: true });
} catch {
// best-effort; fall through to normal acquisition
}
if (staleOwner.kind !== 'unknown') {
console.info(
`[ClawX] Force-cleaned stale instance lock (pid=${staleOwner.pid}, format=${staleOwner.kind})`,
);
}
rmSync(lockPath, { force: true });
}
let ownerPid: number | undefined;
let ownerFormat: ProcessInstanceFileLock['ownerFormat'] = 'unknown';
let ownerDetails: StructuredLockContent | undefined;
for (let attempt = 0; attempt < 2; attempt += 1) {
try {
const fd = openSync(lockPath, 'wx');
const ownerToken = randomUUID();
const startedAt = options.metadata?.startedAt ?? new Date().toISOString();
const structuredContent: StructuredLockContent | undefined = options.metadata
? {
schema: LOCK_SCHEMA,
version: STRUCTURED_LOCK_VERSION,
pid,
ownerToken,
appVersion: options.metadata.appVersion,
channel: options.metadata.channel,
executable: options.metadata.executable,
startedAt,
heartbeatAt: startedAt,
}
: undefined;
try {
// Keep writing legacy numeric format for broad backward compatibility.
// Parser accepts both legacy numeric and structured JSON formats.
writeFileSync(fd, String(pid), 'utf8');
writeFileSync(fd, structuredContent ? JSON.stringify(structuredContent) : String(pid), 'utf8');
} finally {
closeSync(fd);
}
let released = false;
const heartbeatTimer = structuredContent
? setInterval(() => {
const currentOwner = readLockOwner(lockPath);
if (currentOwner.kind !== 'structured' || currentOwner.details.ownerToken !== ownerToken) return;
structuredContent.heartbeatAt = new Date().toISOString();
try {
writeLockAtomic(lockPath, JSON.stringify(structuredContent));
} catch {
// A missed heartbeat never transfers ownership.
}
}, options.heartbeatIntervalMs ?? 5_000)
: undefined;
heartbeatTimer?.unref();
return {
acquired: true,
lockPath,
release: () => {
if (released) return;
released = true;
if (heartbeatTimer) clearInterval(heartbeatTimer);
try {
const currentOwner = readLockOwner(lockPath);
if (currentOwner.kind === 'unknown' || currentOwner.pid !== pid) return;
if (
(currentOwner.kind === 'legacy' || currentOwner.kind === 'structured')
&& currentOwner.pid !== pid
) {
return;
}
if (currentOwner.kind === 'unknown') {
return;
}
currentOwner.kind === 'structured'
&& currentOwner.details.ownerToken
&& currentOwner.details.ownerToken !== ownerToken
) return;
rmSync(lockPath, { force: true });
} catch {
// best-effort
// Best effort during shutdown.
}
},
};
} catch (error) {
const errno = (error as NodeJS.ErrnoException).code;
if (errno !== 'EEXIST') {
break;
}
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') break;
const owner = readLockOwner(lockPath);
if (owner.kind === 'legacy' || owner.kind === 'structured') {
ownerPid = owner.pid;
ownerFormat = owner.kind;
ownerDetails = owner.kind === 'structured' ? owner.details : undefined;
} else {
ownerPid = undefined;
ownerFormat = 'unknown';
ownerDetails = undefined;
}
const shouldTreatAsStale =
(owner.kind === 'legacy' || owner.kind === 'structured')
&& !isPidAlive(owner.pid);
if (shouldTreatAsStale && existsSync(lockPath)) {
const stale = (owner.kind === 'legacy' || owner.kind === 'structured')
&& !isPidAlive(owner.pid)
&& heartbeatExpired(owner, heartbeatExpiryMs);
if (stale && existsSync(lockPath)) {
try {
rmSync(lockPath, { force: true });
continue;
} catch {
// If deletion fails, treat as held lock.
// Treat an undeletable stale lock as held.
}
}
break;
}
}
@@ -199,8 +227,7 @@ export function acquireProcessInstanceFileLock(
lockPath,
ownerPid,
ownerFormat,
release: () => {
// no-op when lock wasn't acquired
},
ownerDetails,
release: () => {},
};
}
+34 -72
View File
@@ -3,19 +3,11 @@ import {
WEB_BROWSER_INITIAL_URL,
WEB_BROWSER_PARTITION,
WEB_BROWSER_USER_AGENT,
normalizeWebBrowserHtmlFileUrl,
normalizeWebBrowserTopLevelUrl,
} 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;
@@ -75,7 +67,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 === '';
}
@@ -143,70 +135,48 @@ export function installWebBrowserGuestPolicy(
}
guest.setUserAgent(WEB_BROWSER_USER_AGENT);
let committedHtmlUrl = normalizeWebBrowserHtmlFileUrl(guest.getURL());
let restoringCommittedUrl = false;
const blockPageNavigation = (
details: Electron.Event<Electron.WebContentsWillFrameNavigateEventParams>,
const rejectDisallowedNavigation = (
details: Electron.Event<Electron.WebContentsWillNavigateEventParams>,
): void => {
logger.warn(`[WebBrowser] Blocked guest navigation to ${details.url}`);
details.preventDefault();
};
const stopInvalidProgrammaticNavigation = (
details: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
): void => {
if (!details.isMainFrame || normalizeWebBrowserHtmlFileUrl(details.url)) {
if (!details.isMainFrame || normalizeWebBrowserTopLevelUrl(details.url) !== null) {
return;
}
logger.warn(`[WebBrowser] Stopped invalid programmatic navigation to ${details.url}`);
guest.stop();
logger.warn(`[WebBrowser] Blocked top-level navigation to ${details.url}`);
details.preventDefault();
};
const blockRedirect = (
const rejectDisallowedRedirect = (
details: Electron.Event<Electron.WebContentsWillRedirectEventParams>,
): void => {
logger.warn(`[WebBrowser] Blocked guest redirect to ${details.url}`);
details.preventDefault();
};
guest.setWindowOpenHandler(({ url }) => {
logger.warn(`[WebBrowser] Blocked popup target ${url}`);
return DENY_WINDOW_OPEN;
});
const makeLinksVisuallyInert = (): void => {
void guest.insertCSS(INERT_LINK_CSS, { cssOrigin: 'user' }).catch((error) => {
logger.warn('[WebBrowser] Failed to neutralize HTML links:', error);
});
};
const rememberCommittedHtml = (_event: Electron.Event, url: string): void => {
const normalizedUrl = normalizeWebBrowserHtmlFileUrl(url);
if (normalizedUrl) {
committedHtmlUrl = normalizedUrl;
}
restoringCommittedUrl = false;
};
const restoreAfterInPageNavigation = (
_event: Electron.Event,
url: string,
isMainFrame: boolean,
): void => {
if (!isMainFrame || !committedHtmlUrl || url === committedHtmlUrl || restoringCommittedUrl) {
if (!details.isMainFrame || normalizeWebBrowserTopLevelUrl(details.url) !== null) {
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);
});
logger.warn(`[WebBrowser] Blocked top-level 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);
}
return DENY_WINDOW_OPEN;
});
let cleaned = false;
const cleanup = (): void => {
if (cleaned) {
@@ -214,12 +184,8 @@ export function installWebBrowserGuestPolicy(
}
cleaned = true;
guest.off('will-frame-navigate', blockPageNavigation);
guest.off('did-start-navigation', stopInvalidProgrammaticNavigation);
guest.off('will-redirect', blockRedirect);
guest.off('did-finish-load', makeLinksVisuallyInert);
guest.off('did-navigate', rememberCommittedHtml);
guest.off('did-navigate-in-page', restoreAfterInPageNavigation);
guest.off('will-navigate', rejectDisallowedNavigation);
guest.off('will-redirect', rejectDisallowedRedirect);
guest.off('destroyed', cleanup);
if (!guest.isDestroyed()) {
guest.setWindowOpenHandler(() => DENY_WINDOW_OPEN);
@@ -229,12 +195,8 @@ export function installWebBrowserGuestPolicy(
}
};
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.on('will-navigate', rejectDisallowedNavigation);
guest.on('will-redirect', rejectDisallowedRedirect);
guest.once('destroyed', cleanup);
cleanupGuestPolicy = cleanup;
};
+106 -22
View File
@@ -1,56 +1,140 @@
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));
// Keep a deterministic identity even though this session may load only local HTML.
// The macOS UA is fixed on every platform for stable website compatibility and deterministic requests.
browserSession.setUserAgent(WEB_BROWSER_USER_AGENT);
browserSession.setPermissionCheckHandler(() => false);
browserSession.setPermissionRequestHandler((_contents, _permission, callback) => {
callback(false);
});
browserSession.setDevicePermissionHandler(() => false);
browserSession.setDisplayMediaRequestHandler((_request, callback) => {
callback({});
});
browserSession.setPermissionCheckHandler((_contents, permission) => (
CLIPBOARD_PERMISSIONS.has(permission)
));
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 });
},
);
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);
}
})();
});
if (!DOWNLOAD_OBSERVED_SESSIONS.has(browserSession)) {
DOWNLOAD_OBSERVED_SESSIONS.add(browserSession);
browserSession.on('will-download', (event) => {
event.preventDefault();
// 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');
}
});
});
}
// This isolated browser Session intentionally does not mirror client proxy settings or recycle connections.
return browserSession;
}
@@ -0,0 +1,115 @@
import { randomUUID } from 'node:crypto';
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { app } from 'electron';
import { getClawXDataLayout, resolveClawXDataRoot } from '../utils/clawx-data-layout';
export type CcConnectPermissionMode = 'suggest' | 'full-auto';
type AgentBinding = {
providerAccountId?: string;
permissionMode?: CcConnectPermissionMode;
updatedAt: string;
};
type AgentBindingDocument = {
schema: 'clawx-agent-bindings';
version: 1;
agents: Record<string, AgentBinding>;
};
function bindingsPath(): string {
const layout = getClawXDataLayout(resolveClawXDataRoot(process.env, app.getPath('userData')));
return join(layout.appDir, 'agent-bindings.json');
}
async function readDocument(): Promise<AgentBindingDocument> {
try {
const parsed = JSON.parse(await readFile(bindingsPath(), 'utf8')) as Partial<AgentBindingDocument>;
if (parsed.schema === 'clawx-agent-bindings' && parsed.version === 1 && parsed.agents) {
return parsed as AgentBindingDocument;
}
} catch {
// Missing or malformed bindings start empty and are replaced atomically on write.
}
return { schema: 'clawx-agent-bindings', version: 1, agents: {} };
}
async function writeDocument(document: AgentBindingDocument): Promise<void> {
const path = bindingsPath();
await mkdir(dirname(path), { recursive: true });
const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
await writeFile(temporaryPath, `${JSON.stringify(document, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
await rename(temporaryPath, path);
}
export async function listCcConnectAgentProviderBindings(): Promise<Record<string, string>> {
const document = await readDocument();
return Object.fromEntries(Object.entries(document.agents).flatMap(([agentId, binding]) => (
binding.providerAccountId ? [[agentId, binding.providerAccountId]] : []
)));
}
export async function listCcConnectAgentPermissionModes(): Promise<Record<string, CcConnectPermissionMode>> {
const document = await readDocument();
return Object.fromEntries(Object.entries(document.agents).flatMap(([agentId, binding]) => (
binding.permissionMode === 'suggest' || binding.permissionMode === 'full-auto'
? [[agentId, binding.permissionMode]]
: []
)));
}
export async function setCcConnectAgentProviderBinding(
agentId: string,
providerAccountId: string | null,
): Promise<void> {
const normalizedAgentId = agentId.trim();
if (!normalizedAgentId) throw new Error('agentId is required');
const document = await readDocument();
const normalizedAccountId = providerAccountId?.trim();
if (normalizedAccountId) {
document.agents[normalizedAgentId] = {
...document.agents[normalizedAgentId],
providerAccountId: normalizedAccountId,
updatedAt: new Date().toISOString(),
};
} else {
const existing = document.agents[normalizedAgentId];
if (existing?.permissionMode) {
document.agents[normalizedAgentId] = {
permissionMode: existing.permissionMode,
updatedAt: new Date().toISOString(),
};
} else {
delete document.agents[normalizedAgentId];
}
}
await writeDocument(document);
}
export async function setCcConnectAgentPermissionMode(
agentId: string,
permissionMode: CcConnectPermissionMode,
): Promise<void> {
const normalizedAgentId = agentId.trim();
if (!normalizedAgentId) throw new Error('agentId is required');
if (permissionMode !== 'suggest' && permissionMode !== 'full-auto') {
throw new Error('permissionMode must be suggest or full-auto');
}
const document = await readDocument();
document.agents[normalizedAgentId] = {
...document.agents[normalizedAgentId],
permissionMode,
updatedAt: new Date().toISOString(),
};
await writeDocument(document);
}
export async function deleteCcConnectAgentBinding(agentId: string): Promise<void> {
const normalizedAgentId = agentId.trim();
if (!normalizedAgentId) return;
const document = await readDocument();
if (!(normalizedAgentId in document.agents)) return;
delete document.agents[normalizedAgentId];
await writeDocument(document);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,47 @@
import { chmod, mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { getCcConnectManagedDir } from './cc-connect-paths';
function safeName(value: string): string {
return encodeURIComponent(value.trim() || 'default').replace(/%/g, '_');
}
function shellQuote(value: string): string {
return `'${value.replace(/'/g, `'"'"'`)}'`;
}
export async function ensureCcConnectCodexLauncher(options: {
accountId: string;
codexHomeDir: string;
codexPath: string;
envAliases?: Record<string, string>;
}): Promise<string> {
const launchersDir = join(getCcConnectManagedDir(), 'config', 'launchers');
await mkdir(launchersDir, { recursive: true });
const baseName = `codex-${safeName(options.accountId)}`;
if (process.platform === 'win32') {
const path = join(launchersDir, `${baseName}.cmd`);
const content = [
'@echo off',
`set "CODEX_HOME=${options.codexHomeDir}"`,
...Object.entries(options.envAliases ?? {}).map(([target, source]) => `set "${target}=%${source}%"`),
`"${options.codexPath.replace(/"/g, '""')}" %*`,
'',
].join('\r\n');
await writeFile(path, content, { encoding: 'utf8', mode: 0o700 });
return path;
}
const path = join(launchersDir, baseName);
const content = [
'#!/bin/sh',
`export CODEX_HOME=${shellQuote(options.codexHomeDir)}`,
...Object.entries(options.envAliases ?? {}).map(([target, source]) => `export ${target}="\${${source}}"`),
`exec ${shellQuote(options.codexPath)} "$@"`,
'',
].join('\n');
await writeFile(path, content, { encoding: 'utf8', mode: 0o700 });
await chmod(path, 0o700);
return path;
}
@@ -0,0 +1,452 @@
import { readdir, readFile, stat } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import type { RawMessage } from '@shared/chat/types';
const MAX_TRANSCRIPT_SEARCH_DEPTH = 6;
const MAX_TOOL_OUTPUT_CHARS = 16_000;
const TRANSCRIPT_TURN_MATCH_WINDOW_MS = 2 * 60_000;
const MAX_TRANSCRIPT_FILE_CACHE_ENTRIES = 512;
const MAX_TRANSCRIPT_PATH_CACHE_ENTRIES = 2_048;
const MAX_FALLBACK_TURN_HINTS = 20;
const MAX_FALLBACK_DIRECTORIES = 12;
const MAX_FALLBACK_CANDIDATE_FILES = 64;
const MAX_FALLBACK_FILE_BYTES = 8 * 1024 * 1024;
const MAX_FALLBACK_TOTAL_BYTES = 32 * 1024 * 1024;
type CachedTranscriptFile = {
mtimeMs: number;
size: number;
jsonl: string;
turnMetadata?: {
sessionTimestamp?: number;
sessionWorkDir?: string;
userTurns: Array<{
content: string;
timestamp?: number;
}>;
};
toolMessages?: RawMessage[];
};
const transcriptFileCache = new Map<string, CachedTranscriptFile>();
const transcriptPathBySessionId = new Map<string, string>();
function setBoundedCache<K, V>(cache: Map<K, V>, key: K, value: V, maxEntries: number): void {
cache.delete(key);
cache.set(key, value);
while (cache.size > maxEntries) {
const oldestKey = cache.keys().next().value;
if (oldestKey === undefined) break;
cache.delete(oldestKey);
}
}
export type CcConnectTranscriptTurnHint = {
content: string;
timestamp: number;
};
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
function parseTimestamp(value: unknown): number | undefined {
if (typeof value !== 'string' || !value.trim()) return undefined;
const timestamp = Date.parse(value);
return Number.isFinite(timestamp) ? timestamp : undefined;
}
function parseToolArguments(value: unknown): unknown {
if (typeof value !== 'string') return value ?? {};
const trimmed = value.trim();
if (!trimmed) return {};
try {
return JSON.parse(trimmed);
} catch {
return trimmed;
}
}
function displayToolName(name: string): string {
switch (name) {
case 'exec_command':
return 'Bash';
case 'apply_patch':
return 'Patch';
case 'web_search':
case 'web_search_call':
return 'Web Search';
default:
return name || 'tool';
}
}
function toolOutputIsError(output: string): boolean {
const exitCode = output.match(/\bProcess exited with code (\d+)\b/i)?.[1];
return exitCode !== undefined && Number(exitCode) !== 0;
}
function toolOutputText(value: unknown): string {
if (typeof value === 'string') return value;
return JSON.stringify(value ?? '');
}
function truncateToolOutput(output: string): string {
return output.length > MAX_TOOL_OUTPUT_CHARS
? `${output.slice(0, MAX_TOOL_OUTPUT_CHARS)}\n… output truncated by ClawX`
: output;
}
async function readTranscriptFile(path: string): Promise<CachedTranscriptFile | null> {
const metadata = await stat(path).catch(() => null);
if (!metadata) return null;
const cached = transcriptFileCache.get(path);
if (cached && cached.mtimeMs === metadata.mtimeMs && cached.size === metadata.size) {
setBoundedCache(transcriptFileCache, path, cached, MAX_TRANSCRIPT_FILE_CACHE_ENTRIES);
return cached;
}
const jsonl = await readFile(path, 'utf8').catch(() => '');
const entry = {
mtimeMs: metadata.mtimeMs,
size: metadata.size,
jsonl,
};
setBoundedCache(transcriptFileCache, path, entry, MAX_TRANSCRIPT_FILE_CACHE_ENTRIES);
return entry;
}
async function findTranscriptFile(
directory: string,
agentSessionId: string,
depth = 0,
): Promise<string | undefined> {
if (depth > MAX_TRANSCRIPT_SEARCH_DEPTH) return undefined;
const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
for (const entry of entries) {
if (!entry.isFile()) continue;
if (entry.name.endsWith('.jsonl') && entry.name.includes(agentSessionId)) {
return join(directory, entry.name);
}
}
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const match = await findTranscriptFile(join(directory, entry.name), agentSessionId, depth + 1);
if (match) return match;
}
return undefined;
}
function transcriptDateParts(timestamp: number, utc: boolean): [string, string, string] {
const date = new Date(timestamp);
const year = utc ? date.getUTCFullYear() : date.getFullYear();
const month = (utc ? date.getUTCMonth() : date.getMonth()) + 1;
const day = utc ? date.getUTCDate() : date.getDate();
return [String(year), String(month).padStart(2, '0'), String(day).padStart(2, '0')];
}
function transcriptCandidateDateParts(timestamp: number): Array<[string, string, string]> {
const candidates = [
transcriptDateParts(timestamp - 24 * 60 * 60_000, false),
transcriptDateParts(timestamp, false),
transcriptDateParts(timestamp + 24 * 60 * 60_000, false),
transcriptDateParts(timestamp, true),
];
return Array.from(new Map(candidates.map((parts) => [parts.join('/'), parts])).values());
}
function transcriptTurnMetadata(file: CachedTranscriptFile): NonNullable<CachedTranscriptFile['turnMetadata']> {
if (file.turnMetadata) return file.turnMetadata;
let sessionTimestamp: number | undefined;
let sessionWorkDir: string | undefined;
const userTurns: NonNullable<CachedTranscriptFile['turnMetadata']>['userTurns'] = [];
for (const line of file.jsonl.split(/\r?\n/)) {
if (!line.trim()) continue;
let record: Record<string, unknown>;
try {
const parsed = JSON.parse(line);
if (!isRecord(parsed)) continue;
record = parsed;
} catch {
continue;
}
if (record.type === 'session_meta' && isRecord(record.payload)) {
sessionTimestamp = parseTimestamp(record.payload.timestamp) ?? parseTimestamp(record.timestamp);
sessionWorkDir = typeof record.payload.cwd === 'string' ? record.payload.cwd : undefined;
continue;
}
if (record.type !== 'response_item' || !isRecord(record.payload)) continue;
const payload = record.payload;
if (payload.type !== 'message' || payload.role !== 'user' || !Array.isArray(payload.content)) continue;
const timestamp = parseTimestamp(record.timestamp) ?? sessionTimestamp;
for (const item of payload.content) {
if (!isRecord(item) || item.type !== 'input_text' || typeof item.text !== 'string') continue;
userTurns.push({
content: item.text.trim(),
...(timestamp !== undefined ? { timestamp } : {}),
});
}
}
file.turnMetadata = { sessionTimestamp, sessionWorkDir, userTurns };
return file.turnMetadata;
}
function transcriptMatchesWorkDir(file: CachedTranscriptFile, expectedWorkDir?: string): boolean {
if (!expectedWorkDir) return true;
const { sessionWorkDir } = transcriptTurnMetadata(file);
return sessionWorkDir !== undefined && resolve(sessionWorkDir) === resolve(expectedWorkDir);
}
function transcriptMatchesTurn(
file: CachedTranscriptFile,
hints: CcConnectTranscriptTurnHint[],
expectedWorkDir?: string,
): boolean {
const { userTurns } = transcriptTurnMetadata(file);
if (userTurns.length === 0 || !transcriptMatchesWorkDir(file, expectedWorkDir)) return false;
return hints.some((hint) => userTurns.some((turn) => (
turn.timestamp !== undefined
&& Math.abs(turn.timestamp - hint.timestamp) <= TRANSCRIPT_TURN_MATCH_WINDOW_MS
&& turn.content === hint.content.trim()
)));
}
async function findTurnTranscriptFiles(
codexHomeDir: string,
hints: CcConnectTranscriptTurnHint[],
expectedWorkDir?: string,
): Promise<string[]> {
const sessionRoot = join(codexHomeDir, 'sessions');
const directories = new Map<string, string>();
const recentHints = [...hints]
.sort((left, right) => right.timestamp - left.timestamp)
.slice(0, MAX_FALLBACK_TURN_HINTS);
for (const hint of recentHints) {
for (const parts of transcriptCandidateDateParts(hint.timestamp)) {
const directory = join(sessionRoot, ...parts);
directories.set(directory, directory);
if (directories.size >= MAX_FALLBACK_DIRECTORIES) break;
}
if (directories.size >= MAX_FALLBACK_DIRECTORIES) break;
}
const matches: string[] = [];
let candidateFiles = 0;
let candidateBytes = 0;
for (const directory of directories.values()) {
const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
const transcriptEntries = entries
.filter((entry) => entry.isFile() && entry.name.endsWith('.jsonl'))
.sort((left, right) => right.name.localeCompare(left.name));
for (const entry of transcriptEntries) {
if (candidateFiles >= MAX_FALLBACK_CANDIDATE_FILES) return matches;
candidateFiles += 1;
const path = join(directory, entry.name);
const metadata = await stat(path).catch(() => null);
if (!metadata || metadata.size > MAX_FALLBACK_FILE_BYTES) continue;
if (candidateBytes + metadata.size > MAX_FALLBACK_TOTAL_BYTES) return matches;
candidateBytes += metadata.size;
const file = await readTranscriptFile(path);
if (file?.jsonl && transcriptMatchesTurn(file, recentHints, expectedWorkDir)) matches.push(path);
}
}
return matches;
}
export function parseCcConnectCodexTranscriptTools(jsonl: string): RawMessage[] {
const messages: RawMessage[] = [];
const toolNamesByCallId = new Map<string, string>();
for (const line of jsonl.split(/\r?\n/)) {
if (!line.trim()) continue;
let record: Record<string, unknown>;
try {
const parsed = JSON.parse(line);
if (!isRecord(parsed)) continue;
record = parsed;
} catch {
continue;
}
if (record.type !== 'response_item' || !isRecord(record.payload)) continue;
const payload = record.payload;
const payloadType = typeof payload.type === 'string' ? payload.type : '';
const callId = typeof payload.call_id === 'string'
? payload.call_id.trim()
: typeof payload.id === 'string'
? payload.id.trim()
: '';
if (!callId) continue;
const timestamp = parseTimestamp(record.timestamp);
if (payloadType === 'function_call' || payloadType === 'custom_tool_call') {
const rawName = typeof payload.name === 'string' ? payload.name.trim() : '';
const name = displayToolName(rawName);
toolNamesByCallId.set(callId, name);
messages.push({
id: `cc-connect-codex-tool-${callId}`,
role: 'assistant',
content: [{
type: 'toolCall',
id: callId,
name,
arguments: parseToolArguments(payload.arguments ?? payload.input),
}],
...(timestamp !== undefined ? { timestamp } : {}),
stopReason: 'tool_use',
});
continue;
}
if (payloadType === 'function_call_output' || payloadType === 'custom_tool_call_output') {
const rawOutput = toolOutputText(payload.output ?? payload.content);
const output = truncateToolOutput(rawOutput);
const name = toolNamesByCallId.get(callId) || 'tool';
const isError = toolOutputIsError(rawOutput);
messages.push({
id: `cc-connect-codex-tool-result-${callId}`,
role: 'toolresult',
toolCallId: callId,
toolName: name,
content: output,
details: {
status: isError ? 'error' : 'completed',
aggregated: output,
},
...(isError ? { isError: true } : {}),
...(timestamp !== undefined ? { timestamp } : {}),
});
continue;
}
if (payloadType === 'web_search_call') {
const name = 'Web Search';
messages.push({
id: `cc-connect-codex-tool-${callId}`,
role: 'assistant',
content: [{
type: 'toolCall',
id: callId,
name,
arguments: payload.action ?? {},
}],
...(timestamp !== undefined ? { timestamp } : {}),
stopReason: 'tool_use',
});
const status = typeof payload.status === 'string' ? payload.status.toLowerCase() : '';
const isError = ['cancelled', 'error', 'failed'].includes(status);
if (status === 'completed' || isError) {
const output = isError ? `Web search ${status}` : 'Web search completed';
messages.push({
id: `cc-connect-codex-tool-result-${callId}`,
role: 'toolresult',
toolCallId: callId,
toolName: name,
content: output,
details: {
status: isError ? 'error' : 'completed',
aggregated: output,
},
...(isError ? { isError: true } : {}),
...(timestamp !== undefined ? { timestamp } : {}),
});
}
continue;
}
if (payloadType === 'mcp_tool_call') {
const server = typeof payload.server === 'string' ? payload.server : '';
const tool = typeof payload.tool === 'string'
? payload.tool
: typeof payload.name === 'string'
? payload.name
: 'tool';
const name = server ? `${server}: ${tool}` : tool;
messages.push({
id: `cc-connect-codex-tool-${callId}`,
role: 'assistant',
content: [{
type: 'toolCall',
id: callId,
name,
arguments: parseToolArguments(payload.arguments ?? payload.input),
}],
...(timestamp !== undefined ? { timestamp } : {}),
stopReason: 'tool_use',
});
if (payload.result !== undefined || payload.error !== undefined) {
const isError = payload.error !== undefined;
const output = truncateToolOutput(toolOutputText(payload.error ?? payload.result));
messages.push({
id: `cc-connect-codex-tool-result-${callId}`,
role: 'toolresult',
toolCallId: callId,
toolName: name,
content: output,
details: {
status: isError ? 'error' : 'completed',
aggregated: output,
},
...(isError ? { isError: true } : {}),
...(timestamp !== undefined ? { timestamp } : {}),
});
}
}
}
return messages;
}
export async function loadCcConnectCodexTranscriptTools(
codexHomeDirs: string | Iterable<string>,
agentSessionId: string,
turnHints: CcConnectTranscriptTurnHint[] = [],
expectedWorkDir?: string,
): Promise<RawMessage[]> {
const hasValidAgentSessionId = /^[A-Za-z0-9_-]+$/.test(agentSessionId);
if (!hasValidAgentSessionId && turnHints.length === 0) return [];
const homes = typeof codexHomeDirs === 'string'
? [codexHomeDirs]
: Array.from(codexHomeDirs);
const uniqueHomes = Array.from(new Set(homes.filter(Boolean)));
const idMatchedPaths = new Set<string>();
for (const codexHomeDir of uniqueHomes) {
if (hasValidAgentSessionId) {
const sessionPathCacheKey = `${resolve(codexHomeDir)}\0${agentSessionId}`;
let transcriptPath = transcriptPathBySessionId.get(sessionPathCacheKey);
if (!transcriptPath) {
transcriptPath = await findTranscriptFile(join(codexHomeDir, 'sessions'), agentSessionId);
}
if (transcriptPath) {
setBoundedCache(
transcriptPathBySessionId,
sessionPathCacheKey,
transcriptPath,
MAX_TRANSCRIPT_PATH_CACHE_ENTRIES,
);
const file = await readTranscriptFile(transcriptPath);
const matchesPublicTurn = turnHints.length === 0
|| (file !== null && transcriptMatchesTurn(file, turnHints, expectedWorkDir));
if (file?.jsonl && transcriptMatchesWorkDir(file, expectedWorkDir) && matchesPublicTurn) {
idMatchedPaths.add(transcriptPath);
}
}
}
}
let transcriptPaths = new Set<string>();
if (idMatchedPaths.size === 1) {
transcriptPaths = idMatchedPaths;
} else if (idMatchedPaths.size === 0) {
const fallbackPaths = new Set<string>();
for (const codexHomeDir of uniqueHomes) {
for (const path of await findTurnTranscriptFiles(codexHomeDir, turnHints, expectedWorkDir)) {
fallbackPaths.add(path);
}
}
if (fallbackPaths.size === 1) transcriptPaths = fallbackPaths;
}
const messages: RawMessage[] = [];
for (const transcriptPath of transcriptPaths) {
const file = await readTranscriptFile(transcriptPath);
if (!file?.jsonl) continue;
file.toolMessages ??= parseCcConnectCodexTranscriptTools(file.jsonl);
messages.push(...file.toolMessages);
}
return messages.sort((left, right) => (left.timestamp ?? 0) - (right.timestamp ?? 0));
}
@@ -0,0 +1,8 @@
export const CC_CONNECT_MANAGEMENT_PORT = 9820;
export function buildCcConnectWebAdminUrl(port = CC_CONNECT_MANAGEMENT_PORT): string {
const normalizedPort = Number.isFinite(port) && port > 0
? Math.trunc(port)
: CC_CONNECT_MANAGEMENT_PORT;
return `http://127.0.0.1:${normalizedPort}/`;
}
+63
View File
@@ -0,0 +1,63 @@
import { app } from 'electron';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { getClawXDataLayout, resolveClawXDataRoot } from '../utils/clawx-data-layout';
function binaryName(): string {
return process.platform === 'win32' ? 'cc-connect.exe' : 'cc-connect';
}
export function getCcConnectManagedDir(): string {
return getClawXDataLayout(resolveClawXDataRoot(process.env, app.getPath('userData'))).ccConnectRuntimeDir;
}
export function getCcConnectConfigPath(): string {
return join(getCcConnectManagedDir(), 'config.toml');
}
export function getCcConnectCodexHomeDir(): string {
return join(getCcConnectManagedDir(), 'codex-home');
}
export function getCcConnectAccountCodexHomeDir(accountId: string): string {
const normalized = accountId.trim() || 'default';
const safeAccountId = encodeURIComponent(normalized).replace(/%/g, '_');
const layout = getClawXDataLayout(resolveClawXDataRoot(process.env, app.getPath('userData')));
return join(layout.credentialsDir, 'oauth', safeAccountId, 'codex-home');
}
export function getCcConnectWorkspacesDir(): string {
return getClawXDataLayout(resolveClawXDataRoot(process.env, app.getPath('userData'))).agentWorkspacesDir;
}
export function getCcConnectAgentWorkspaceDir(agentId = 'main'): string {
const safeAgentId = agentId.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-') || 'main';
return join(getCcConnectWorkspacesDir(), safeAgentId);
}
export function getCcConnectProviderProfilePath(): string {
return join(getCcConnectManagedDir(), 'provider-profile.json');
}
export function getCcConnectBinaryPath(): string {
if (!app.isPackaged && process.env.CLAWX_CC_CONNECT_PATH) {
return process.env.CLAWX_CC_CONNECT_PATH;
}
if (app.isPackaged) {
return join(process.resourcesPath, 'cc-connect', binaryName());
}
const bundledDevBinary = join(process.cwd(), 'build', 'cc-connect', `${process.platform}-${process.arch}`, binaryName());
if (existsSync(bundledDevBinary)) {
return bundledDevBinary;
}
return bundledDevBinary;
}
export function assertCcConnectBinaryPath(candidate = getCcConnectBinaryPath()): string {
if (!existsSync(candidate)) {
throw new Error(
`cc-connect binary not found at ${candidate}. Run pnpm run bundle:cc-connect:current before selecting cc-connect runtime.`,
);
}
return candidate;
}
@@ -0,0 +1,786 @@
import { access, chmod, cp, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { app } from 'electron';
import { getProviderAccount, getDefaultProviderAccountId } from '@electron/services/providers/provider-store';
import { getProviderSecret, getSecretStore } from '@electron/services/secrets/secret-store';
import { getProviderDefaultModel } from '@electron/utils/provider-registry';
import type { ProviderAccount, ProviderSecret } from '@electron/shared/providers/types';
import {
getCcConnectAccountCodexHomeDir,
getCcConnectCodexHomeDir,
getCcConnectProviderProfilePath,
} from './cc-connect-paths';
export type CodexProviderProfile = {
providerId: string | null;
vendorId: string | null;
label?: string;
authMode?: string;
model?: string;
modelRef?: string;
supported: boolean;
unsupportedReason?: string;
codexArgs: string[];
env?: Record<string, string>;
envKeys?: string[];
launcherEnv?: Record<string, string>;
ccConnectProvider?: {
name: string;
apiKeyEnvKey?: string;
baseUrl?: string;
model?: string;
wireApi?: 'responses';
};
secretAvailable: boolean;
codexHomeDir?: string;
updatedAt: string;
};
type OpenAIOAuthTokenSet = {
idToken: string;
accessToken: string;
refreshToken: string;
accountId: string;
};
type OpenAIOAuthTokenResolution = {
tokens: OpenAIOAuthTokenSet;
source: 'managed' | 'secret';
};
type OpenAIOAuthTokenResolutionOptions = {
preferSecret?: boolean;
};
export type CodexOAuthAuthFileSummary = {
path: string;
exists: boolean;
complete: boolean;
accountId?: string;
authMode?: string;
lastRefresh?: string;
updatedAt?: string;
error?: string;
};
export type CodexOAuthProviderSummary = {
accountId: string;
vendorId: string;
authMode?: string;
hasOAuthSecret: boolean;
subject?: string;
email?: string;
managedMatchesAccount?: boolean;
userMatchesAccount?: boolean;
};
export type CodexOAuthStatus = {
success: true;
managedCodexHome: string;
authPath: string;
managed: CodexOAuthAuthFileSummary;
user: CodexOAuthAuthFileSummary;
provider?: CodexOAuthProviderSummary;
};
function resolveModel(account: ProviderAccount): string | undefined {
const model = account.model?.trim();
if (model) return model;
return getProviderDefaultModel(account.vendorId)?.trim() || undefined;
}
function publicProfile(profile: CodexProviderProfile): CodexProviderProfile {
const { env, ...rest } = profile;
return {
...rest,
envKeys: Object.keys(env ?? {}),
};
}
function tomlString(value: string): string {
return JSON.stringify(value);
}
function tomlInlineStringMap(values: Record<string, string>): string {
return `{ ${Object.entries(values).map(([key, value]) => `${tomlString(key)} = ${tomlString(value)}`).join(', ')} }`;
}
function normalizeOpenAIResponsesBaseUrl(baseUrl: string): string {
return baseUrl.trim().replace(/\/+$/, '').replace(/\/responses$/i, '');
}
function normalizeModelHubCodexResponsesBaseUrl(baseUrl: string): string | null {
const trimmed = baseUrl.trim();
if (!trimmed) return null;
try {
const url = new URL(trimmed);
if (url.hostname !== 'aidp.bytedance.net') return null;
if (!url.pathname.startsWith('/api/modelhub/online')) return null;
url.pathname = '/api/modelhub/online';
url.search = '';
url.hash = '';
return url.toString().replace(/\/$/, '');
} catch {
return null;
}
}
async function writeManagedCodexResponsesConfig(options: {
accountId: string;
providerKey: string;
providerName: string;
baseUrl: string;
envKey: string;
model?: string;
envHttpHeaders?: Record<string, string>;
modelReasoningEffort?: string;
}): Promise<string> {
const codexHomeDir = getCcConnectAccountCodexHomeDir(options.accountId);
await mkdir(codexHomeDir, { recursive: true });
const configPath = join(codexHomeDir, 'config.toml');
const tableKey = /^[A-Za-z_][A-Za-z0-9_-]*$/.test(options.providerKey)
? options.providerKey
: tomlString(options.providerKey);
const envHeaderEntries = Object.entries(options.envHttpHeaders ?? {});
const lines = [
...(options.model ? [`model = ${tomlString(options.model)}`] : []),
`model_provider = ${tomlString(options.providerKey)}`,
...(options.modelReasoningEffort ? [`model_reasoning_effort = ${tomlString(options.modelReasoningEffort)}`] : []),
'',
`[model_providers.${tableKey}]`,
`name = ${tomlString(options.providerName)}`,
`base_url = ${tomlString(options.baseUrl)}`,
`env_key = ${tomlString(options.envKey)}`,
'wire_api = "responses"',
...(envHeaderEntries.length > 0
? [`env_http_headers = ${tomlInlineStringMap(options.envHttpHeaders ?? {})}`]
: []),
'',
];
await writeFile(configPath, lines.join('\n'), { encoding: 'utf8', mode: 0o600 });
await chmod(configPath, 0o600).catch(() => {});
return codexHomeDir;
}
function stableModelHubSessionId(account: ProviderAccount): string {
return `clawx-cc-connect-${account.id}`;
}
function sanitizedEnvKeyPart(value: string): string {
const sanitized = value
.trim()
.replace(/[^A-Za-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '')
.toUpperCase();
return sanitized || 'HEADER';
}
function accountScopedEnvKey(accountId: string, purpose: string): string {
return `CLAWX_CODEX_${sanitizedEnvKeyPart(accountId)}_${sanitizedEnvKeyPart(purpose)}`;
}
function buildCustomHeaderEnv(account: ProviderAccount, options?: { exclude?: Set<string> }): {
env: Record<string, string>;
envHttpHeaders: Record<string, string>;
} {
const entries = Object.entries(account.headers ?? {})
.map(([name, value]) => [name.trim(), String(value ?? '').trim()] as const)
.filter(([name, value]) => name && value)
.filter(([name]) => !options?.exclude?.has(name.toLowerCase()));
const env: Record<string, string> = {};
const envHttpHeaders: Record<string, string> = {};
const used = new Set<string>();
for (const [name, value] of entries) {
const baseKey = accountScopedEnvKey(account.id, `HEADER_${name}`);
let envKey = baseKey;
let index = 2;
while (used.has(envKey)) {
envKey = `${baseKey}_${index}`;
index += 1;
}
used.add(envKey);
env[envKey] = value;
envHttpHeaders[name] = envKey;
}
return { env, envHttpHeaders };
}
function extractSessionIdFromExtraHeader(value: string): string | undefined {
try {
const parsed = JSON.parse(value) as unknown;
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined;
const sessionId = (parsed as Record<string, unknown>).session_id;
return typeof sessionId === 'string' && sessionId.trim() ? sessionId.trim() : undefined;
} catch {
return undefined;
}
}
function buildModelHubEnv(account: ProviderAccount, apiKey: string): {
env: Record<string, string>;
envHttpHeaders: Record<string, string>;
} {
const apiKeyEnvKey = accountScopedEnvKey(account.id, 'API_KEY');
const extraHeaderEnvKey = accountScopedEnvKey(account.id, 'EXTRA_HEADER');
const stickySessionEnvKey = accountScopedEnvKey(account.id, 'STICKY_SESSION_ID');
const customHeaders = buildCustomHeaderEnv(account, { exclude: new Set(['api-key', 'extra']) });
const existingExtraHeader = account.headers?.extra?.trim();
const sessionId = existingExtraHeader
? extractSessionIdFromExtraHeader(existingExtraHeader) ?? stableModelHubSessionId(account)
: stableModelHubSessionId(account);
const extraHeader = existingExtraHeader || JSON.stringify({ session_id: sessionId });
return {
env: {
[apiKeyEnvKey]: apiKey,
...customHeaders.env,
[extraHeaderEnvKey]: extraHeader,
[stickySessionEnvKey]: sessionId,
},
envHttpHeaders: {
...customHeaders.envHttpHeaders,
'Api-Key': apiKeyEnvKey,
extra: extraHeaderEnvKey,
},
};
}
function getUserCodexAuthPath(): string {
const e2eOverride = process.env.CLAWX_E2E_USER_CODEX_AUTH_JSON?.trim();
if (process.env.CLAWX_E2E === '1' && e2eOverride) {
return e2eOverride;
}
return join(app.getPath('home'), '.codex', 'auth.json');
}
async function ensureAccountCodexHome(accountId: string): Promise<string> {
const accountHome = getCcConnectAccountCodexHomeDir(accountId);
await mkdir(accountHome, { recursive: true });
return accountHome;
}
async function migrateLegacyCodexHomeToAccount(accountId: string): Promise<void> {
const accountHome = getCcConnectAccountCodexHomeDir(accountId);
const legacyHome = getCcConnectCodexHomeDir();
const accountExists = await access(accountHome).then(() => true).catch(() => false);
if (accountExists) return;
const legacyExists = await access(legacyHome).then(() => true).catch(() => false);
if (!legacyExists) return;
await mkdir(dirname(accountHome), { recursive: true });
try {
await rename(legacyHome, accountHome);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'EXDEV') {
await cp(legacyHome, accountHome, { recursive: true, force: false, errorOnExist: false });
await rm(legacyHome, { recursive: true, force: true });
return;
}
throw error;
}
}
async function writeManagedOpenAIOAuthAuthFile(
tokens: OpenAIOAuthTokenSet,
accountId: string,
): Promise<string> {
const codexHomeDir = getCcConnectAccountCodexHomeDir(accountId);
await mkdir(codexHomeDir, { recursive: true });
const authPath = join(codexHomeDir, 'auth.json');
await writeFile(authPath, JSON.stringify({
auth_mode: 'chatgpt',
OPENAI_API_KEY: null,
tokens: {
id_token: tokens.idToken,
access_token: tokens.accessToken,
refresh_token: tokens.refreshToken,
account_id: tokens.accountId,
},
last_refresh: new Date().toISOString(),
}, null, 2), { encoding: 'utf8', mode: 0o600 });
await chmod(authPath, 0o600).catch(() => {});
return codexHomeDir;
}
async function readCompleteCodexAuthTokens(authPath: string): Promise<OpenAIOAuthTokenSet | undefined> {
try {
const auth = JSON.parse(await readFile(authPath, 'utf8')) as {
tokens?: {
id_token?: unknown;
access_token?: unknown;
refresh_token?: unknown;
account_id?: unknown;
};
};
const tokens = auth.tokens;
if (
!tokens ||
typeof tokens.id_token !== 'string' ||
typeof tokens.access_token !== 'string' ||
typeof tokens.refresh_token !== 'string' ||
typeof tokens.account_id !== 'string' ||
!tokens.id_token.trim() ||
!tokens.access_token.trim() ||
!tokens.refresh_token.trim() ||
!tokens.account_id.trim()
) {
return undefined;
}
return {
idToken: tokens.id_token.trim(),
accessToken: tokens.access_token.trim(),
refreshToken: tokens.refresh_token.trim(),
accountId: tokens.account_id.trim(),
};
} catch {
return undefined;
}
}
async function readCodexAuthSummary(authPath: string): Promise<CodexOAuthAuthFileSummary> {
let raw: string;
try {
raw = await readFile(authPath, 'utf8');
} catch {
return { path: authPath, exists: false, complete: false };
}
const updatedAt = await stat(authPath)
.then((fileStat) => fileStat.mtime.toISOString())
.catch(() => undefined);
try {
const parsed = JSON.parse(raw) as {
auth_mode?: unknown;
tokens?: { account_id?: unknown };
last_refresh?: unknown;
};
const tokens = await readCompleteCodexAuthTokens(authPath);
return {
path: authPath,
exists: true,
complete: Boolean(tokens),
accountId: tokens?.accountId ?? (
typeof parsed.tokens?.account_id === 'string' && parsed.tokens.account_id.trim()
? parsed.tokens.account_id.trim()
: undefined
),
authMode: typeof parsed.auth_mode === 'string' ? parsed.auth_mode : undefined,
lastRefresh: typeof parsed.last_refresh === 'string' ? parsed.last_refresh : undefined,
updatedAt,
};
} catch {
return {
path: authPath,
exists: true,
complete: false,
updatedAt,
error: 'Invalid Codex auth.json',
};
}
}
function codexTokensMatchAccount(
tokens: OpenAIOAuthTokenSet,
account: ProviderAccount,
secret?: Extract<ProviderSecret, { type: 'oauth' }>,
): boolean {
if (!secret) return true;
const expectedAccountId = secret.subject?.trim();
const userAccountId = tokens.accountId.trim();
const accessMatches = tokens.accessToken === secret.accessToken;
const refreshMatches = tokens.refreshToken === secret.refreshToken;
const accountMatches = Boolean(expectedAccountId && userAccountId && expectedAccountId === userAccountId);
const providerIdMatches = Boolean(userAccountId && account.id === userAccountId);
return accessMatches || refreshMatches || accountMatches || providerIdMatches;
}
async function resolveProviderAccount(accountId?: string): Promise<{
account: ProviderAccount | null;
secret?: Extract<ProviderSecret, { type: 'oauth' }>;
}> {
const resolvedAccountId = accountId?.trim() || await getDefaultProviderAccountId();
const account = resolvedAccountId ? await getProviderAccount(resolvedAccountId) : null;
const secret = account ? await getProviderSecret(account.id) : null;
return {
account,
secret: secret?.type === 'oauth' && secret.accessToken && secret.refreshToken ? secret : undefined,
};
}
async function resolveOpenAIOAuthTokens(
account: ProviderAccount,
secret?: Extract<ProviderSecret, { type: 'oauth' }>,
options?: OpenAIOAuthTokenResolutionOptions,
): Promise<OpenAIOAuthTokenResolution | undefined> {
const secretIdToken = secret?.idToken?.trim();
const secretResolution: OpenAIOAuthTokenResolution | undefined = secret && secretIdToken
? {
tokens: {
idToken: secretIdToken,
accessToken: secret.accessToken,
refreshToken: secret.refreshToken,
accountId: secret.subject?.trim() || account.id,
},
source: 'secret',
}
: undefined;
// Browser re-login is authoritative once; normal starts keep Codex-rotated managed tokens.
if (options?.preferSecret && secretResolution) {
return secretResolution;
}
const managedAuthPath = join(await ensureAccountCodexHome(account.id), 'auth.json');
const managedTokens = await readCompleteCodexAuthTokens(managedAuthPath);
if (managedTokens && codexTokensMatchAccount(managedTokens, account, secret)) {
return { tokens: managedTokens, source: 'managed' };
}
return secretResolution;
}
export async function getCcConnectCodexOAuthStatus(payload?: {
accountId?: string;
}): Promise<CodexOAuthStatus> {
const { account, secret } = await resolveProviderAccount(payload?.accountId);
const resolvedAccountId = account?.id ?? payload?.accountId?.trim() ?? 'default';
const managedCodexHome = await ensureAccountCodexHome(resolvedAccountId);
const authPath = join(managedCodexHome, 'auth.json');
const userAuthPath = getUserCodexAuthPath();
const [managed, user] = await Promise.all([
readCodexAuthSummary(authPath),
readCodexAuthSummary(userAuthPath),
]);
const managedTokens = account ? await readCompleteCodexAuthTokens(authPath) : undefined;
const userTokens = account ? await readCompleteCodexAuthTokens(userAuthPath) : undefined;
return {
success: true,
managedCodexHome,
authPath,
managed,
user,
...(account ? {
provider: {
accountId: account.id,
vendorId: account.vendorId,
authMode: account.authMode,
hasOAuthSecret: Boolean(secret),
subject: secret?.subject,
email: secret?.email,
managedMatchesAccount: managedTokens ? codexTokensMatchAccount(managedTokens, account, secret) : undefined,
userMatchesAccount: userTokens ? codexTokensMatchAccount(userTokens, account, secret) : undefined,
},
} : {}),
};
}
export async function importUserCodexOAuthToManagedHome(payload?: {
accountId?: string;
}): Promise<CodexOAuthStatus> {
const { account, secret } = await resolveProviderAccount(payload?.accountId);
const userAuthPath = getUserCodexAuthPath();
const tokens = await readCompleteCodexAuthTokens(userAuthPath);
if (!tokens) {
throw new Error(`No complete Codex OAuth auth.json found at ${userAuthPath}`);
}
if (account && !codexTokensMatchAccount(tokens, account, secret)) {
throw new Error('Local Codex OAuth credentials do not match the selected provider account');
}
await writeManagedOpenAIOAuthAuthFile(tokens, account?.id ?? payload?.accountId?.trim() ?? 'default');
return getCcConnectCodexOAuthStatus({ accountId: account?.id ?? payload?.accountId });
}
export async function logoutCcConnectCodexOAuth(payload?: {
accountId?: string;
managedOnly?: boolean;
}): Promise<CodexOAuthStatus> {
const { account } = await resolveProviderAccount(payload?.accountId);
const accountId = account?.id ?? payload?.accountId?.trim() ?? 'default';
const managedHome = await ensureAccountCodexHome(accountId);
await rm(join(managedHome, 'auth.json'), { force: true });
if (!payload?.managedOnly && account?.authMode === 'oauth_browser') {
await getSecretStore().delete(account.id);
}
return getCcConnectCodexOAuthStatus({ accountId });
}
async function buildProfileForAccount(
account: ProviderAccount,
options?: OpenAIOAuthTokenResolutionOptions,
): Promise<CodexProviderProfile> {
const secret = await getProviderSecret(account.id);
const model = resolveModel(account);
const base = {
providerId: account.id,
vendorId: account.vendorId,
label: account.label,
authMode: account.authMode,
model,
modelRef: model ? `${account.vendorId}/${model}` : undefined,
secretAvailable: Boolean(secret),
updatedAt: new Date().toISOString(),
};
if (account.vendorId === 'openai') {
if (account.authMode === 'oauth_browser') {
const oauthSecret = secret?.type === 'oauth' && secret.accessToken && secret.refreshToken
? secret
: undefined;
const tokenResolution = await resolveOpenAIOAuthTokens(account, oauthSecret, options);
if (!tokenResolution) {
return {
...base,
supported: false,
unsupportedReason: 'Codex OAuth credentials are missing. Sign in to Codex using the ClawX-managed CODEX_HOME or sign in to OpenAI again before using cc-connect Codex runtime.',
codexArgs: [],
};
}
const codexHomeDir = tokenResolution.source === 'managed'
? await ensureAccountCodexHome(account.id)
: await writeManagedOpenAIOAuthAuthFile(tokenResolution.tokens, account.id);
return {
...base,
supported: true,
codexArgs: model ? ['--model', model] : [],
env: { CODEX_HOME: codexHomeDir },
codexHomeDir,
secretAvailable: true,
};
}
const env: Record<string, string> = {};
const apiKeyEnvKey = accountScopedEnvKey(account.id, 'API_KEY');
if ((secret?.type === 'api_key' || secret?.type === 'local') && secret.apiKey) {
env[apiKeyEnvKey] = secret.apiKey;
}
if (!env[apiKeyEnvKey]) {
return {
...base,
supported: false,
unsupportedReason: 'OpenAI API key credentials are missing. Add an OpenAI API key before using the cc-connect Codex runtime with this provider.',
codexArgs: [],
};
}
const baseUrl = account.baseUrl?.trim();
if (baseUrl) {
const providerKey = 'clawx-openai';
const normalizedBaseUrl = normalizeOpenAIResponsesBaseUrl(baseUrl);
const codexHomeDir = await writeManagedCodexResponsesConfig({
accountId: account.id,
providerKey,
providerName: 'OpenAI',
baseUrl: normalizedBaseUrl,
envKey: apiKeyEnvKey,
model,
});
return {
...base,
supported: true,
codexArgs: [
'-c',
`model_provider=${tomlString(providerKey)}`,
'-c',
`model_providers.${providerKey}.name="OpenAI"`,
'-c',
`model_providers.${providerKey}.base_url=${tomlString(normalizedBaseUrl)}`,
'-c',
`model_providers.${providerKey}.env_key=${tomlString(apiKeyEnvKey)}`,
'-c',
`model_providers.${providerKey}.wire_api="responses"`,
...(model ? ['--model', model] : []),
],
env: {
...env,
CODEX_HOME: codexHomeDir,
},
codexHomeDir,
launcherEnv: { OPENAI_API_KEY: apiKeyEnvKey },
ccConnectProvider: {
name: providerKey,
apiKeyEnvKey,
baseUrl: normalizedBaseUrl,
wireApi: 'responses',
...(model ? { model } : {}),
},
};
}
const codexHomeDir = await ensureAccountCodexHome(account.id);
return {
...base,
supported: true,
codexArgs: model ? ['--model', model] : [],
env: { ...env, CODEX_HOME: codexHomeDir },
codexHomeDir,
launcherEnv: { OPENAI_API_KEY: apiKeyEnvKey },
ccConnectProvider: {
name: 'openai',
apiKeyEnvKey,
...(model ? { model } : {}),
},
};
}
if (account.vendorId === 'custom') {
const protocol = account.apiProtocol || 'openai-completions';
if (protocol !== 'openai-responses') {
return {
...base,
supported: false,
unsupportedReason: `cc-connect Codex runtime cannot use custom provider "${account.label}" because Codex 0.137 only supports the Responses wire API. This provider is configured for Chat Completions.`,
codexArgs: [],
};
}
const baseUrl = account.baseUrl?.trim();
if (!baseUrl) {
return {
...base,
supported: false,
unsupportedReason: `cc-connect Codex runtime cannot use custom provider "${account.label}" because a Responses-compatible base URL is required.`,
codexArgs: [],
};
}
if ((secret?.type !== 'api_key' && secret?.type !== 'local') || !secret.apiKey) {
return {
...base,
supported: false,
unsupportedReason: `cc-connect Codex runtime cannot use custom provider "${account.label}" because its API key is missing.`,
codexArgs: [],
};
}
const modelHubBaseUrl = normalizeModelHubCodexResponsesBaseUrl(baseUrl);
const providerKey = modelHubBaseUrl ? 'modelhub_openapi' : 'clawx-custom';
const envKey = accountScopedEnvKey(account.id, 'API_KEY');
const normalizedBaseUrl = modelHubBaseUrl ?? normalizeOpenAIResponsesBaseUrl(baseUrl);
const customHeaders = modelHubBaseUrl
? buildModelHubEnv(account, secret.apiKey)
: buildCustomHeaderEnv(account);
const env: Record<string, string> = modelHubBaseUrl
? customHeaders.env
: { [envKey]: secret.apiKey, ...customHeaders.env };
const envHttpHeaders = Object.keys(customHeaders.envHttpHeaders).length > 0
? customHeaders.envHttpHeaders
: undefined;
const codexHomeDir = await writeManagedCodexResponsesConfig({
accountId: account.id,
providerKey,
providerName: modelHubBaseUrl ? 'ByteDance ModelHub OpenAPI' : (account.label || 'Custom'),
baseUrl: normalizedBaseUrl,
envKey,
model,
envHttpHeaders,
...(modelHubBaseUrl ? { modelReasoningEffort: 'none' } : {}),
});
return {
...base,
supported: true,
codexArgs: [
'-c',
`model_provider=${tomlString(providerKey)}`,
'-c',
`model_providers.${providerKey}.name=${tomlString(modelHubBaseUrl ? 'ByteDance ModelHub OpenAPI' : (account.label || 'Custom'))}`,
'-c',
`model_providers.${providerKey}.base_url=${tomlString(normalizedBaseUrl)}`,
'-c',
`model_providers.${providerKey}.env_key=${tomlString(envKey)}`,
'-c',
`model_providers.${providerKey}.wire_api="responses"`,
...(modelHubBaseUrl ? [
'-c',
'model_reasoning_effort="none"',
] : []),
...(envHttpHeaders ? [
'-c',
`model_providers.${providerKey}.env_http_headers=${tomlInlineStringMap(envHttpHeaders)}`,
] : []),
...(model ? ['--model', model] : []),
],
env: {
...env,
CODEX_HOME: codexHomeDir,
},
codexHomeDir,
ccConnectProvider: {
name: providerKey,
apiKeyEnvKey: envKey,
baseUrl: normalizedBaseUrl,
wireApi: 'responses',
...(model ? { model } : {}),
},
};
}
if (account.vendorId === 'ollama') {
return {
...base,
supported: true,
codexArgs: [
'--oss',
'--local-provider',
'ollama',
...(model ? ['--model', model] : []),
],
};
}
return {
...base,
supported: false,
unsupportedReason: `cc-connect Codex runtime currently supports OpenAI/Codex and Ollama provider accounts; "${account.vendorId}" is not supported yet.`,
codexArgs: [],
};
}
export async function buildCcConnectProviderProfileForAccount(
accountId: string,
): Promise<CodexProviderProfile> {
const account = await getProviderAccount(accountId);
if (account) return buildProfileForAccount(account);
return {
providerId: accountId,
vendorId: null,
supported: false,
unsupportedReason: `Provider account "${accountId}" was not found`,
codexArgs: [],
secretAvailable: false,
updatedAt: new Date().toISOString(),
};
}
export async function syncCcConnectProviderProfile(
payload?: { providerId?: string; reason?: string },
): Promise<CodexProviderProfile> {
const providerId = payload?.providerId?.trim() || await getDefaultProviderAccountId();
const account = providerId ? await getProviderAccount(providerId) : null;
if (account?.vendorId === 'openai' && account.authMode === 'oauth_browser') {
await migrateLegacyCodexHomeToAccount(account.id);
}
const profile: CodexProviderProfile = account
? await buildProfileForAccount(account, { preferSecret: payload?.reason === 'oauth' })
: {
providerId: null,
vendorId: null,
supported: true,
codexArgs: [],
secretAvailable: false,
updatedAt: new Date().toISOString(),
};
const profilePath = getCcConnectProviderProfilePath();
await mkdir(dirname(profilePath), { recursive: true });
await writeFile(profilePath, JSON.stringify({
...publicProfile(profile),
reason: payload?.reason ?? 'sync',
}, null, 2), 'utf8');
return profile;
}
export function toPublicCodexProviderProfile(profile: CodexProviderProfile): CodexProviderProfile {
return publicProfile(profile);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,125 @@
import { randomUUID } from 'node:crypto';
import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { app } from 'electron';
import { getClawXDataLayout, resolveClawXDataRoot } from '../utils/clawx-data-layout';
import { getCcConnectManagedDir } from './cc-connect-paths';
type SessionMetadataDocument = {
schema: 'clawx-cc-connect-session-metadata';
version: 1;
labels: Record<string, string>;
updatedAt: string;
migratedFromLegacyAt?: string;
};
export interface CcConnectSessionMetadataStore {
getLabel(sessionKey: string): Promise<string | undefined>;
setLabel(sessionKey: string, label: string): Promise<void>;
deleteLabel(sessionKey: string): Promise<void>;
}
function defaultMetadataPath(): string {
const layout = getClawXDataLayout(resolveClawXDataRoot(process.env, app.getPath('userData')));
return join(layout.appDir, 'cc-connect-session-metadata.json');
}
function defaultLegacyPath(): string {
return join(getCcConnectManagedDir(), 'data', 'sessions', '.clawx-supplemental-history.json');
}
async function writeAtomic(path: string, document: SessionMetadataDocument): Promise<void> {
await mkdir(dirname(path), { recursive: true });
const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
await writeFile(temporaryPath, `${JSON.stringify(document, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
await chmod(temporaryPath, 0o600).catch(() => {});
await rename(temporaryPath, path);
await chmod(path, 0o600).catch(() => {});
}
function emptyDocument(): SessionMetadataDocument {
return {
schema: 'clawx-cc-connect-session-metadata',
version: 1,
labels: {},
updatedAt: new Date(0).toISOString(),
};
}
function normalizedLabels(value: unknown): Record<string, string> {
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
return Object.fromEntries(Object.entries(value).flatMap(([key, label]) => (
typeof label === 'string' && label.trim() ? [[key, label.trim().slice(0, 80)]] : []
)));
}
export class FileCcConnectSessionMetadataStore implements CcConnectSessionMetadataStore {
private queue = Promise.resolve();
constructor(
private readonly metadataPath = defaultMetadataPath(),
private readonly legacyPath = defaultLegacyPath(),
) {}
async getLabel(sessionKey: string): Promise<string | undefined> {
const document = await this.readDocument();
return document.labels[sessionKey];
}
async setLabel(sessionKey: string, label: string): Promise<void> {
const normalized = label.trim().slice(0, 80);
if (!normalized) throw new Error('Label cannot be empty');
await this.exclusive(async () => {
const document = await this.readDocument();
document.labels[sessionKey] = normalized;
document.updatedAt = new Date().toISOString();
await writeAtomic(this.metadataPath, document);
});
}
async deleteLabel(sessionKey: string): Promise<void> {
await this.exclusive(async () => {
const document = await this.readDocument();
if (!(sessionKey in document.labels)) return;
delete document.labels[sessionKey];
document.updatedAt = new Date().toISOString();
await writeAtomic(this.metadataPath, document);
});
}
private async readDocument(): Promise<SessionMetadataDocument> {
try {
const parsed = JSON.parse(await readFile(this.metadataPath, 'utf8')) as Partial<SessionMetadataDocument>;
if (parsed.schema !== 'clawx-cc-connect-session-metadata' || parsed.version !== 1) {
throw new Error(`Unsupported cc-connect session metadata: ${this.metadataPath}`);
}
return { ...parsed, labels: normalizedLabels(parsed.labels) } as SessionMetadataDocument;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
const document = emptyDocument();
try {
const legacy = JSON.parse(await readFile(this.legacyPath, 'utf8')) as { labels?: unknown };
document.labels = normalizedLabels(legacy.labels);
document.migratedFromLegacyAt = new Date().toISOString();
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
document.updatedAt = new Date().toISOString();
await writeAtomic(this.metadataPath, document);
return document;
}
private async exclusive<T>(operation: () => Promise<T>): Promise<T> {
const previous = this.queue;
let release!: () => void;
this.queue = new Promise<void>((resolve) => { release = resolve; });
await previous;
try {
return await operation();
} finally {
release();
}
}
}
+73
View File
@@ -0,0 +1,73 @@
import { cp, mkdir, rm, writeFile } from 'node:fs/promises';
import { basename, join } from 'node:path';
import type { SkillsStatusResult } from '@shared/host-api/contract';
import { getCcConnectCodexHomeDir } from './cc-connect-paths';
import { listLocalSkills, type LocalSkillRecord } from '../services/skills/local-skill-service';
function safeSkillDirName(skill: Pick<LocalSkillRecord, 'id' | 'slug' | 'baseDir'>): string {
const candidate = skill.slug || skill.id || (skill.baseDir ? basename(skill.baseDir) : 'skill');
return candidate.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'skill';
}
function isCodexNativeSkill(skill: LocalSkillRecord): boolean {
return skill.source === 'agents-skills-personal' || skill.source === 'agents-skills-project';
}
export async function syncCcConnectSkillRecords(
records: LocalSkillRecord[],
codexHomeDir = getCcConnectCodexHomeDir(),
): Promise<SkillsStatusResult> {
const skillsRoot = join(codexHomeDir, 'skills');
await mkdir(skillsRoot, { recursive: true });
const enabled = records.filter((skill) => skill.enabled !== false && skill.baseDir);
const manifest: Array<Record<string, unknown>> = [];
for (const skill of enabled) {
const targetDirName = safeSkillDirName(skill);
const targetDir = join(skillsRoot, targetDirName);
await rm(targetDir, { recursive: true, force: true });
const native = isCodexNativeSkill(skill);
if (!native) {
await cp(skill.baseDir!, targetDir, { recursive: true, force: true });
}
const runtimeDir = native ? skill.baseDir! : targetDir;
manifest.push({
skillKey: skill.id,
slug: skill.slug,
name: skill.name,
description: skill.description,
source: skill.source,
baseDir: runtimeDir,
filePath: join(runtimeDir, 'SKILL.md'),
projection: native ? 'codex-native' : 'mirrored',
version: skill.version,
bundled: skill.isBundled,
always: skill.isCore,
});
}
await writeFile(join(skillsRoot, 'manifest.json'), JSON.stringify({
updatedAt: new Date().toISOString(),
skills: manifest,
}, null, 2), 'utf8');
return {
skills: manifest.map((skill) => ({
skillKey: String(skill.skillKey || ''),
slug: typeof skill.slug === 'string' ? skill.slug : undefined,
name: typeof skill.name === 'string' ? skill.name : undefined,
description: typeof skill.description === 'string' ? skill.description : undefined,
disabled: false,
version: typeof skill.version === 'string' ? skill.version : undefined,
bundled: skill.bundled === true,
always: skill.always === true,
source: typeof skill.source === 'string' ? skill.source : undefined,
baseDir: typeof skill.baseDir === 'string' ? skill.baseDir : undefined,
filePath: typeof skill.filePath === 'string' ? skill.filePath : undefined,
})),
};
}
export async function syncCcConnectSkills(codexHomeDir?: string): Promise<SkillsStatusResult> {
return syncCcConnectSkillRecords(await listLocalSkills(), codexHomeDir);
}
+62
View File
@@ -0,0 +1,62 @@
import { app } from 'electron';
import { existsSync } from 'node:fs';
import { dirname, join } from 'node:path';
export type CodexBundle = {
baseDir: string;
binaryPath: string;
pathDir: string;
targetTriple: string;
};
function codexBinaryName(): string {
return process.platform === 'win32' ? 'codex.exe' : 'codex';
}
function codexTargetTriple(platform = process.platform, arch = process.arch): string {
if (platform === 'darwin' && arch === 'x64') return 'x86_64-apple-darwin';
if (platform === 'darwin' && arch === 'arm64') return 'aarch64-apple-darwin';
if (platform === 'linux' && arch === 'x64') return 'x86_64-unknown-linux-musl';
if (platform === 'linux' && arch === 'arm64') return 'aarch64-unknown-linux-musl';
if (platform === 'win32' && arch === 'x64') return 'x86_64-pc-windows-msvc';
if (platform === 'win32' && arch === 'arm64') return 'aarch64-pc-windows-msvc';
throw new Error(`Unsupported Codex target: ${platform}-${arch}`);
}
function baseDir(): string {
if (app.isPackaged) {
return join(process.resourcesPath, 'codex');
}
if (process.env.CLAWX_CODEX_PATH) {
return dirname(dirname(process.env.CLAWX_CODEX_PATH));
}
return join(process.cwd(), 'build', 'codex', `${process.platform}-${process.arch}`);
}
export function getCodexBundle(): CodexBundle {
const base = baseDir();
return {
baseDir: base,
binaryPath: join(base, 'bin', codexBinaryName()),
pathDir: join(base, 'codex-path'),
targetTriple: codexTargetTriple(),
};
}
export function assertCodexBundle(candidate = getCodexBundle()): CodexBundle {
if (!existsSync(candidate.binaryPath)) {
throw new Error(
`Codex binary not found at ${candidate.binaryPath}. Run pnpm run bundle:codex:current before selecting cc-connect runtime.`,
);
}
return candidate;
}
export function prependCodexPathDir(env: NodeJS.ProcessEnv, bundle = getCodexBundle()): NodeJS.ProcessEnv {
if (!existsSync(bundle.pathDir)) return env;
const delimiter = process.platform === 'win32' ? ';' : ':';
return {
...env,
PATH: [bundle.pathDir, env.PATH || ''].filter(Boolean).join(delimiter),
};
}
+142
View File
@@ -0,0 +1,142 @@
import { EventEmitter } from 'node:events';
import { getSetting, setSetting } from '@electron/utils/store';
import type {
RuntimeCapabilities,
RuntimeEventName,
RuntimeKind,
RuntimeOperationCapabilities,
RuntimeProvider,
RuntimeStatus,
} from './types';
export type RuntimeManagerOptions = {
openclaw: RuntimeProvider;
ccConnect: RuntimeProvider;
};
function normalizeRuntimeKind(value: unknown): RuntimeKind {
return value === 'cc-connect' ? 'cc-connect' : 'openclaw';
}
export class RuntimeManager extends EventEmitter {
private activeKind: RuntimeKind | null = null;
private readonly providers: Record<RuntimeKind, RuntimeProvider>;
private selectionQueue: Promise<void> = Promise.resolve();
constructor(options: RuntimeManagerOptions) {
super();
this.providers = {
openclaw: options.openclaw,
'cc-connect': options.ccConnect,
};
this.forwardProviderEvents(options.openclaw);
this.forwardProviderEvents(options.ccConnect);
}
async getActiveKind(): Promise<RuntimeKind> {
await this.selectionQueue;
return await this.ensureActiveKind();
}
private async ensureActiveKind(): Promise<RuntimeKind> {
if (!this.activeKind) {
const persistedKind = normalizeRuntimeKind(await getSetting('runtimeKind'));
const devModeUnlocked = await getSetting('devModeUnlocked');
this.activeKind = devModeUnlocked === true ? persistedKind : 'openclaw';
if (persistedKind !== this.activeKind) {
await setSetting('runtimeKind', this.activeKind);
}
}
return this.activeKind;
}
getActiveProvider(): RuntimeProvider {
return this.providers[this.activeKind ?? 'openclaw'];
}
getProvider(kind: RuntimeKind): RuntimeProvider {
return this.providers[kind];
}
async setActiveKind(kind: RuntimeKind): Promise<void> {
const change = async () => {
await this.ensureActiveKind();
const requestedKind = normalizeRuntimeKind(kind);
const devModeUnlocked = await getSetting('devModeUnlocked');
const nextKind = requestedKind === 'cc-connect' && devModeUnlocked !== true
? 'openclaw'
: requestedKind;
const previous = this.getActiveProvider();
if (this.activeKind !== nextKind) {
await previous.stop();
}
this.activeKind = nextKind;
await setSetting('runtimeKind', nextKind);
this.emit('status', this.getStatus());
};
const result = this.selectionQueue.then(change, change);
this.selectionQueue = result.then(() => undefined, () => undefined);
await result;
}
listCapabilities(): RuntimeCapabilities {
return this.getActiveProvider().listCapabilities();
}
listOperationCapabilities(): RuntimeOperationCapabilities {
return this.getActiveProvider().listOperationCapabilities();
}
getStatus(): RuntimeStatus {
return this.getActiveProvider().getStatus();
}
start(): Promise<void> {
return this.getActiveProvider().start();
}
stop(): Promise<void> {
return this.getActiveProvider().stop();
}
restart(): Promise<void> {
return this.getActiveProvider().restart();
}
checkHealth(options?: { probe?: boolean }) {
return this.getActiveProvider().checkHealth(options);
}
rpc<T = unknown>(method: string, params?: unknown, timeoutMs?: number): Promise<T> {
return this.getActiveProvider().rpc(method, params, timeoutMs);
}
private forwardProviderEvents(provider: RuntimeProvider): void {
const events: RuntimeEventName[] = [
'status',
'error',
'notification',
'gateway:health',
'gateway:presence',
'chat:message',
'chat:runtime-event',
'channel:status',
'exit',
];
for (const eventName of events) {
provider.on(eventName, (payload: unknown) => {
if (provider !== this.getActiveProvider()) return;
if (eventName === 'status' && payload && typeof payload === 'object') {
this.emit(eventName, {
...(payload as Record<string, unknown>),
runtimeKind: provider.kind,
capabilities: provider.listCapabilities(),
operationCapabilities: provider.listOperationCapabilities(),
});
return;
}
this.emit(eventName, payload);
});
}
}
}
+186
View File
@@ -0,0 +1,186 @@
import { EventEmitter } from 'node:events';
import type { GatewayManager } from '../gateway/manager';
import type {
RuntimeControlUiPayload,
RuntimeProvider,
RuntimeConfigRefreshPayload,
RuntimeSendWithMediaPayload,
} from './types';
import {
OPENCLAW_RUNTIME_CAPABILITIES,
withRuntimeStatus,
} from './types';
import { getRuntimeOperationCapabilities } from './rpc-contract';
import { createChatSendWithMediaHandler } from '../services/chat-api';
import {
createOpenClawCronJob,
deleteOpenClawCronJob,
listCronJobs,
toggleOpenClawCronJob,
triggerOpenClawCronJob,
updateOpenClawCronJob,
} from '../services/cron-api';
import { createSessionsApi } from '../services/sessions-api';
import { logger } from '../utils/logger';
import { runOpenClawDoctor, runOpenClawDoctorFix } from '../utils/openclaw-doctor';
import { PORTS } from '../utils/config';
import { scheduleControlUiDeviceAutoApproval } from '../utils/control-ui-device-pairing';
import { buildOpenClawControlUiUrl } from '../utils/openclaw-control-ui';
import { getSetting } from '../utils/store';
import { getRecentTokenUsageHistory } from '../utils/token-usage';
import { writeOpenClawCompatibilityProjection } from '../utils/channel-config';
import type { OpenClawDoctorMode } from '@shared/host-api/contract';
import { runtimeUsageLimit, toRuntimeUsageRecords } from './usage';
export class OpenClawRuntimeProvider extends EventEmitter implements RuntimeProvider {
readonly kind = 'openclaw' as const;
private readonly sessionsApi = createSessionsApi();
constructor(private readonly gatewayManager: GatewayManager) {
super();
const forward = (eventName: string) => (payload: unknown) => {
this.emit(eventName, payload);
};
for (const eventName of [
'status',
'error',
'notification',
'gateway:health',
'gateway:presence',
'chat:message',
'chat:runtime-event',
'channel:status',
'exit',
]) {
this.gatewayManager.on(eventName, forward(eventName));
}
}
listCapabilities() {
return OPENCLAW_RUNTIME_CAPABILITIES;
}
listOperationCapabilities() {
return getRuntimeOperationCapabilities(this.kind);
}
getStatus() {
return withRuntimeStatus(
this.gatewayManager.getStatus(),
this.kind,
this.listCapabilities(),
undefined,
this.listOperationCapabilities(),
);
}
async start() {
await writeOpenClawCompatibilityProjection();
return await this.gatewayManager.start();
}
stop() {
return this.gatewayManager.stop();
}
async restart() {
await writeOpenClawCompatibilityProjection();
return await this.gatewayManager.restart();
}
checkHealth(options?: { probe?: boolean }) {
return this.gatewayManager.checkHealth(options);
}
rpc<T = unknown>(method: string, params?: unknown, timeoutMs?: number): Promise<T> {
switch (method) {
case 'cron.list':
return listCronJobs(this.gatewayManager) as Promise<T>;
case 'cron.create':
case 'cron.add':
return createOpenClawCronJob(this.gatewayManager, params as never) as Promise<T>;
case 'cron.update': {
const body = params && typeof params === 'object' ? params as Record<string, unknown> : {};
if ('input' in body) {
return updateOpenClawCronJob(this.gatewayManager, body as never) as Promise<T>;
}
return this.gatewayManager.rpc(method, params, timeoutMs);
}
case 'cron.delete':
case 'cron.remove':
return deleteOpenClawCronJob(this.gatewayManager, params) as Promise<T>;
case 'cron.toggle':
return toggleOpenClawCronJob(this.gatewayManager, params as never) as Promise<T>;
case 'cron.run':
return triggerOpenClawCronJob(this.gatewayManager, params) as Promise<T>;
case 'runtime.controlUi':
return this.getControlUi(params as never) as Promise<T>;
case 'sessions.rename':
case 'session.rename':
return this.sessionsApi.rename(params as never) as Promise<T>;
default:
return this.gatewayManager.rpc(method, params, timeoutMs);
}
}
async sendMessageWithMedia(payload: RuntimeSendWithMediaPayload) {
const handler = createChatSendWithMediaHandler(this.gatewayManager, logger);
const response = await handler(payload);
if (!response.success) {
throw new Error(response.error || 'OpenClaw chat send failed');
}
return response.result ?? {};
}
async listSessions(payload?: unknown) {
return await this.sessionsApi.summaries(payload as never);
}
async loadHistory(payload?: unknown) {
return await this.sessionsApi.history(payload as never);
}
async deleteSession(payload?: unknown) {
return await this.sessionsApi.delete(payload as never);
}
async listUsage(payload?: unknown) {
const limit = runtimeUsageLimit(payload);
const entries = await getRecentTokenUsageHistory({
...(limit !== undefined ? { limit } : {}),
runtimeKind: 'openclaw',
});
return {
success: true,
records: toRuntimeUsageRecords(entries, { runtimeKind: this.kind }),
};
}
async listLogs() {
return { content: logger.getRecentLogs().join('\n') };
}
runDoctor(mode: OpenClawDoctorMode) {
return mode === 'fix' ? runOpenClawDoctorFix() : runOpenClawDoctor();
}
async refreshConfig(payload: RuntimeConfigRefreshPayload): Promise<void> {
if (this.gatewayManager.getStatus().state === 'stopped') return;
if (payload.forceRestart) {
this.gatewayManager.debouncedRestart(150);
return;
}
this.gatewayManager.debouncedReload(150);
}
async getControlUi(payload?: RuntimeControlUiPayload) {
if (!this.listCapabilities().controlUi) {
return { success: false, error: 'openclaw runtime does not support Control UI' };
}
const token = await getSetting('gatewayToken');
const port = this.getStatus().port || PORTS.OPENCLAW_GATEWAY;
const url = buildOpenClawControlUiUrl(port, token, { view: payload?.view });
scheduleControlUiDeviceAutoApproval(this.gatewayManager);
return { success: true, url, token, port };
}
}
+128
View File
@@ -0,0 +1,128 @@
import type {
RuntimeCapabilities,
RuntimeKind,
RuntimeOperationCapabilities,
RuntimeOperationSupport,
} from './types';
export type RuntimeRpcContractEntry = {
runtime: RuntimeKind;
method: string;
capability: keyof RuntimeCapabilities;
support: RuntimeOperationSupport;
notes: string;
};
const OPENCLAW_PROXY_METHODS: Array<[string, keyof RuntimeCapabilities, string]> = [
['chat.send', 'chat', 'Sent through OpenClaw Gateway chat.send.'],
['chat.abort', 'chat', 'Forwarded to OpenClaw Gateway.'],
['chat.approval.respond', 'chat', 'Forwarded to OpenClaw Gateway.'],
['sessions.list', 'sessions', 'Served by the OpenClaw session API facade.'],
['chat.history', 'history', 'Served by the OpenClaw session API facade.'],
['sessions.delete', 'sessions', 'Served by the OpenClaw session API facade.'],
['session.delete', 'sessions', 'Compatibility alias for sessions.delete.'],
['chat.session.delete', 'sessions', 'Compatibility alias for sessions.delete.'],
['sessions.rename', 'sessions', 'Served by the OpenClaw session API facade.'],
['session.rename', 'sessions', 'Compatibility alias for sessions.rename.'],
['providers.sync', 'providers', 'Forwarded to OpenClaw Gateway/provider services.'],
['providers.profile', 'providers', 'Forwarded to OpenClaw Gateway/provider services.'],
['models.sync', 'models', 'Forwarded to OpenClaw Gateway/model services.'],
['models.profile', 'models', 'Forwarded to OpenClaw Gateway/model services.'],
['skills.status', 'skills', 'Forwarded to OpenClaw skills service.'],
['skills.update', 'skills', 'Forwarded to OpenClaw skills service.'],
['channels.status', 'channels', 'Forwarded to OpenClaw Gateway.'],
['channels.add', 'channels', 'Forwarded to OpenClaw Gateway.'],
['channels.requestQr', 'channels', 'Forwarded to OpenClaw Gateway.'],
['channels.connect', 'channels', 'Forwarded to OpenClaw Gateway.'],
['channels.disconnect', 'channels', 'Forwarded to OpenClaw Gateway.'],
['channels.delete', 'channels', 'Forwarded to OpenClaw Gateway.'],
['runtime.controlUi', 'controlUi', 'Opens the OpenClaw Control UI.'],
['cron.list', 'cron', 'Adapted by the OpenClaw runtime provider.'],
['cron.create', 'cron', 'Adapted by the OpenClaw runtime provider.'],
['cron.add', 'cron', 'Compatibility alias for cron.create.'],
['cron.update', 'cron', 'Adapted by the OpenClaw runtime provider.'],
['cron.delete', 'cron', 'Adapted by the OpenClaw runtime provider.'],
['cron.remove', 'cron', 'Compatibility alias for cron.delete.'],
['cron.toggle', 'cron', 'Adapted by the OpenClaw runtime provider.'],
['cron.run', 'cron', 'Adapted by the OpenClaw runtime provider.'],
['logs.list', 'logs', 'Served from the OpenClaw log buffer.'],
['doctor.run', 'doctor', 'Runs openclaw doctor.'],
['doctor.fix', 'doctor', 'Runs openclaw doctor --fix.'],
['doctor.memory.status', 'doctor', 'Forwarded to OpenClaw memory doctor RPCs.'],
];
const CC_CONNECT_NATIVE_METHODS: Array<[string, keyof RuntimeCapabilities, string]> = [
['chat.send', 'chat', 'Delivered through cc-connect BridgePlatform into Codex.'],
['chat.abort', 'chat', 'Sends cc-connect /stop to the active Bridge session; runtime restart is only a disconnected-Bridge fallback.'],
['chat.approval.respond', 'chat', 'Returns a validated card_action through cc-connect BridgePlatform for a pending approval, question, or runtime choice.'],
['sessions.list', 'sessions', 'Loaded from the cc-connect public Management session API.'],
['chat.history', 'history', 'Loaded from the cc-connect public Management session history API.'],
['sessions.delete', 'sessions', 'Deletes the runtime session through the cc-connect public Management API.'],
['session.delete', 'sessions', 'Compatibility alias for sessions.delete.'],
['chat.session.delete', 'sessions', 'Compatibility alias for sessions.delete.'],
['sessions.rename', 'sessions', 'Stores a ClawX display label without mutating cc-connect private session files.'],
['session.rename', 'sessions', 'Compatibility alias for sessions.rename.'],
['providers.sync', 'providers', 'Writes the managed Codex provider profile and restarts when needed.'],
['providers.profile', 'providers', 'Returns the managed Codex profile plus public cc-connect project provider/model state without restart.'],
['models.sync', 'models', 'Aliases provider sync for the active Codex model profile.'],
['models.profile', 'models', 'Returns the managed Codex model plus public cc-connect project provider/model state without restart.'],
['skills.status', 'skills', 'Synchronizes skills into the managed cc-connect Codex home.'],
['skills.update', 'skills', 'Synchronizes skills into the managed cc-connect Codex home.'],
['channels.status', 'channels', 'Reads configured channel accounts plus live cc-connect project platform status.'],
['channels.connect', 'channels', 'Reloads cc-connect channel platform config through the Management API.'],
['channels.disconnect', 'channels', 'Reloads cc-connect channel platform config through the Management API.'],
['channels.delete', 'channels', 'Reloads cc-connect channel platform config after channel config deletion.'],
['runtime.controlUi', 'controlUi', 'Opens the cc-connect Web Admin.'],
['cron.list', 'cron', 'Uses cc-connect management API.'],
['cron.create', 'cron', 'Uses cc-connect management API.'],
['cron.add', 'cron', 'Compatibility alias for cron.create.'],
['cron.update', 'cron', 'Uses cc-connect management API.'],
['cron.delete', 'cron', 'Uses cc-connect management API.'],
['cron.remove', 'cron', 'Compatibility alias for cron.delete.'],
['cron.toggle', 'cron', 'Uses cc-connect management API update with enabled=true/false.'],
['cron.run', 'cron', 'Uses cc-connect management API.'],
['logs.list', 'logs', 'Served from managed cc-connect config and runtime paths.'],
['doctor.run', 'doctor', 'Runs cc-connect doctor user-isolation.'],
];
const CC_CONNECT_UNSUPPORTED_METHODS: Array<[string, keyof RuntimeCapabilities, string]> = [
['channels.add', 'channels', 'Channel accounts are configured through the ClawX Host API before cc-connect reload.'],
['channels.requestQr', 'channels', 'cc-connect does not expose the OpenClaw QR pairing RPC.'],
['doctor.fix', 'doctor', 'cc-connect Doctor does not support fix mode.'],
['doctor.memory.status', 'doctor', 'OpenClaw Dreams memory doctor RPCs do not have a cc-connect equivalent.'],
];
function entries(
runtime: RuntimeKind,
support: RuntimeOperationSupport,
items: Array<[string, keyof RuntimeCapabilities, string]>,
): RuntimeRpcContractEntry[] {
return items.map(([method, capability, notes]) => ({
runtime,
method,
capability,
support,
notes,
}));
}
export const RUNTIME_RPC_CONTRACT: RuntimeRpcContractEntry[] = [
...entries('openclaw', 'proxy', OPENCLAW_PROXY_METHODS),
...entries('cc-connect', 'native', CC_CONNECT_NATIVE_METHODS),
...entries('cc-connect', 'unsupported', CC_CONNECT_UNSUPPORTED_METHODS),
];
export function getRuntimeRpcCoverage(runtime: RuntimeKind): RuntimeRpcContractEntry[] {
return RUNTIME_RPC_CONTRACT.filter((entry) => entry.runtime === runtime);
}
export function getRuntimeOperationCapabilities(runtime: RuntimeKind): RuntimeOperationCapabilities {
return Object.fromEntries(getRuntimeRpcCoverage(runtime).map((entry) => [
entry.method,
{
capability: entry.capability,
support: entry.support,
notes: entry.notes,
},
]));
}
+190
View File
@@ -0,0 +1,190 @@
import type { EventEmitter } from 'node:events';
import type { RawMessage } from '@shared/chat/types';
import type { OpenClawDoctorMode, OpenClawDoctorResult } from '@shared/host-api/contract';
import type {
GatewayHealth,
GatewayStatus,
RuntimeCapabilities,
RuntimeKind,
RuntimeOperationCapabilities,
} from '@shared/types/gateway';
export type {
RuntimeCapabilities,
RuntimeKind,
RuntimeOperationCapabilities,
RuntimeOperationSupport,
} from '@shared/types/gateway';
export type RuntimeStatus = GatewayStatus & {
runtimeKind: RuntimeKind;
capabilities: RuntimeCapabilities;
configDir?: string;
};
export type RuntimeHealth = GatewayHealth;
export type RuntimeSessionListResult = {
success?: boolean;
sessions?: Array<{ key: string; displayName?: string; agentId?: string }>;
summaries?: Array<{ sessionKey: string; firstUserText: string | null; lastTimestamp: number | null }>;
error?: string;
};
export type RuntimeHistoryResult = {
success?: boolean;
messages?: RawMessage[];
error?: string;
};
export type RuntimeDeleteSessionResult = {
success: boolean;
error?: string;
};
export type RuntimeLogResult = {
content: string;
};
export type RuntimeUsageRecord = {
id: string;
runtimeKind: RuntimeKind;
logicalSessionId: string;
runtimeSessionId: string;
turnId: string;
agentId: string;
providerAccountId?: string;
provider: string;
model: string;
timestamp: string;
status: 'available' | 'missing' | 'error';
inputTokens: number;
cachedInputTokens: number;
cacheWriteTokens: number;
outputTokens: number;
reasoningTokens: number;
totalTokens: number;
costUsd?: number;
content?: string;
};
export type RuntimeUsageListResult = {
success: boolean;
records: RuntimeUsageRecord[];
error?: string;
};
export type RuntimeSendWithMediaPayload = {
sessionKey: string;
message: string;
deliver?: boolean;
idempotencyKey: string;
media?: Array<{ filePath: string; mimeType: string; fileName: string }>;
};
export type RuntimeSendWithMediaResult = {
runId?: string;
};
export type RuntimeConfigRefreshPayload = {
scope: 'channels' | 'providers' | 'skills' | 'runtime';
reason: string;
channelType?: string;
forceRestart?: boolean;
};
export type RuntimeProviderSyncPayload = {
providerId?: string;
reason: string;
};
export type RuntimeControlUiPayload = {
view?: 'dreams';
};
export type RuntimeControlUiResult = {
success: boolean;
url?: string;
token?: string;
port?: number;
error?: string;
};
export type RuntimeEventName =
| 'status'
| 'error'
| 'notification'
| 'gateway:health'
| 'gateway:presence'
| 'chat:message'
| 'chat:runtime-event'
| 'channel:status'
| 'exit';
export type RuntimeProvider = {
kind: RuntimeKind;
on: EventEmitter['on'];
off: EventEmitter['off'];
start: () => Promise<void>;
stop: () => Promise<void>;
restart: () => Promise<void>;
getStatus: () => RuntimeStatus;
checkHealth: (options?: { probe?: boolean }) => Promise<RuntimeHealth>;
rpc: <T = unknown>(method: string, params?: unknown, timeoutMs?: number) => Promise<T>;
sendMessageWithMedia: (payload: RuntimeSendWithMediaPayload) => Promise<RuntimeSendWithMediaResult>;
listSessions: (payload?: unknown) => Promise<RuntimeSessionListResult>;
loadHistory: (payload?: unknown) => Promise<RuntimeHistoryResult>;
deleteSession: (payload?: unknown) => Promise<RuntimeDeleteSessionResult>;
listUsage: (payload?: unknown) => Promise<RuntimeUsageListResult>;
listLogs: (payload?: { tailLines?: number }) => Promise<RuntimeLogResult>;
runDoctor: (mode: OpenClawDoctorMode) => Promise<OpenClawDoctorResult>;
listCapabilities: () => RuntimeCapabilities;
listOperationCapabilities: () => RuntimeOperationCapabilities;
refreshConfig?: (payload: RuntimeConfigRefreshPayload) => Promise<void>;
syncProviderProfile?: (payload: RuntimeProviderSyncPayload) => Promise<unknown>;
getControlUi?: (payload?: RuntimeControlUiPayload) => Promise<RuntimeControlUiResult>;
};
export const OPENCLAW_RUNTIME_CAPABILITIES: RuntimeCapabilities = {
chat: true,
sessions: true,
history: true,
providers: true,
models: true,
channels: true,
cron: true,
logs: true,
skills: true,
doctor: true,
controlUi: true,
};
export const CC_CONNECT_RUNTIME_CAPABILITIES: RuntimeCapabilities = {
chat: true,
sessions: true,
history: true,
providers: true,
models: true,
channels: true,
cron: true,
logs: true,
skills: true,
doctor: true,
controlUi: true,
};
export function withRuntimeStatus(
status: GatewayStatus,
runtimeKind: RuntimeKind,
capabilities: RuntimeCapabilities,
configDir?: string,
operationCapabilities?: RuntimeOperationCapabilities,
): RuntimeStatus {
return {
...status,
runtimeKind,
capabilities,
...(operationCapabilities ? { operationCapabilities } : {}),
...(configDir ? { configDir } : {}),
};
}
+94
View File
@@ -0,0 +1,94 @@
import { createHash } from 'node:crypto';
import type { TokenUsageHistoryEntry } from '../utils/token-usage-core';
import type { RuntimeKind, RuntimeUsageRecord } from './types';
type RuntimeUsageIdentity = {
runtimeKind: RuntimeKind;
logicalSessionId?: string;
runtimeSessionId?: string;
providerAccountId?: string;
provider?: string;
model?: string;
};
export function runtimeUsageLimit(payload: unknown): number | undefined {
const value = payload && typeof payload === 'object' && !Array.isArray(payload)
? (payload as { limit?: unknown }).limit
: payload;
if (typeof value === 'number' && Number.isFinite(value)) {
return Math.max(Math.floor(value), 1);
}
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return Math.max(Math.floor(parsed), 1);
}
return undefined;
}
export function toRuntimeUsageRecords(
entries: TokenUsageHistoryEntry[],
identity: RuntimeUsageIdentity,
): RuntimeUsageRecord[] {
return entries.map((entry) => {
const logicalSessionId = identity.logicalSessionId ?? entry.sessionId;
const runtimeSessionId = identity.runtimeSessionId ?? entry.sessionId;
const fallbackTurnId = createHash('sha256')
.update(JSON.stringify([
runtimeSessionId,
entry.timestamp,
entry.provider,
entry.model,
entry.content,
entry.inputTokens,
entry.outputTokens,
entry.totalTokens,
]))
.digest('hex')
.slice(0, 20);
const turnId = entry.turnId ?? `${runtimeSessionId}:${fallbackTurnId}`;
return {
id: `${identity.runtimeKind}:${runtimeSessionId}:${turnId}`,
runtimeKind: identity.runtimeKind,
logicalSessionId,
runtimeSessionId,
turnId,
agentId: entry.agentId,
...(identity.providerAccountId ? { providerAccountId: identity.providerAccountId } : {}),
provider: entry.provider ?? identity.provider ?? 'unknown',
model: entry.model ?? identity.model ?? 'unknown',
timestamp: entry.timestamp,
status: entry.usageStatus,
inputTokens: entry.inputTokens,
cachedInputTokens: entry.cacheReadTokens,
cacheWriteTokens: entry.cacheWriteTokens,
outputTokens: entry.outputTokens,
reasoningTokens: entry.reasoningTokens ?? 0,
totalTokens: entry.totalTokens,
...(entry.costUsd !== undefined ? { costUsd: entry.costUsd } : {}),
...(entry.content ? { content: entry.content } : {}),
};
});
}
export function toTokenUsageHistoryEntry(record: RuntimeUsageRecord): TokenUsageHistoryEntry {
return {
runtimeKind: record.runtimeKind,
timestamp: record.timestamp,
sessionId: record.logicalSessionId,
runtimeSessionId: record.runtimeSessionId,
turnId: record.turnId,
agentId: record.agentId,
...(record.providerAccountId ? { providerAccountId: record.providerAccountId } : {}),
model: record.model,
provider: record.provider,
...(record.content ? { content: record.content } : {}),
usageStatus: record.status,
inputTokens: record.inputTokens,
outputTokens: record.outputTokens,
cacheReadTokens: record.cachedInputTokens,
cacheWriteTokens: record.cacheWriteTokens,
...(record.reasoningTokens > 0 ? { reasoningTokens: record.reasoningTokens } : {}),
totalTokens: record.totalTokens,
...(record.costUsd !== undefined ? { costUsd: record.costUsd } : {}),
};
}
+1 -4
View File
@@ -394,15 +394,12 @@ export class AcpChatService {
}
this.permissionsEnabled = true;
const messageId = payload.messageId ?? randomUUID();
const isSlashCommand = payload.message?.trimStart().startsWith('/') === true;
await connection.prompt({
sessionId: acpSessionId,
prompt,
// ACP 1.1 removed messageId from the PromptRequest wire shape. Keep
// ClawX correlation metadata in the protocol extension envelope.
// OpenClaw must receive slash commands without its textual cwd prefix
// so the Gateway can classify and fold command replies into chat final.
_meta: { sessionKey: payload.sessionKey, prefixCwd: !isSlashCommand, messageId },
_meta: { sessionKey: payload.sessionKey, prefixCwd: true, messageId },
});
this.trace('session/prompt:success', {
sessionKey: payload.sessionKey,
+65 -22
View File
@@ -1,4 +1,5 @@
import type { GatewayManager } from '../gateway/manager';
import type { RuntimeManager } from '../runtime/manager';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import {
assignChannelToAgent,
@@ -11,6 +12,11 @@ import {
updateAgentModel,
updateAgentName,
} from '../utils/agent-config';
import {
deleteCcConnectAgentBinding,
setCcConnectAgentPermissionMode,
setCcConnectAgentProviderBinding,
} from '../runtime/cc-connect-agent-bindings';
import { deleteChannelAccountConfig } from '../utils/channel-config';
import { ensureClawXContext } from '../utils/openclaw-workspace';
import { isRecord } from './payload-utils';
@@ -18,6 +24,7 @@ import { syncAgentModelOverrideToRuntime, syncAllProviderAuthToRuntime } from '.
type AgentsApiContext = {
gatewayManager: GatewayManager;
runtimeManager?: RuntimeManager;
};
function requireString(payload: unknown, key: string): string {
@@ -27,23 +34,34 @@ 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();
async function refreshActiveRuntime(ctx: AgentsApiContext, reason: string): Promise<void> {
const provider = ctx.runtimeManager?.getActiveProvider();
if (provider?.refreshConfig) {
await provider.refreshConfig({ scope: 'runtime', reason });
return;
}
void reason;
if (ctx.gatewayManager.getStatus().state !== 'stopped') {
ctx.gatewayManager.debouncedReload();
}
}
async function restartGatewayForAgentDeletion(ctx: AgentsApiContext): Promise<void> {
async function restartRuntimeForAgentDeletion(ctx: AgentsApiContext): Promise<void> {
try {
await ctx.gatewayManager.restart();
console.log('[agents] Gateway restart completed after agent deletion');
if (ctx.runtimeManager) {
await ctx.runtimeManager.restart();
} else {
await ctx.gatewayManager.restart();
}
console.log('[agents] Runtime restart completed after agent deletion');
} catch (err) {
console.warn('[agents] Gateway restart after agent deletion failed:', err);
console.warn('[agents] Runtime restart after agent deletion failed:', err);
}
}
function usesCcConnect(ctx: AgentsApiContext): boolean {
return ctx.runtimeManager?.getActiveProvider().kind === 'cc-connect';
}
export function createAgentsApi(ctx: AgentsApiContext): CompleteHostServiceRegistry['agents'] {
return {
list: async () => ({ success: true, ...(await listAgentsSnapshot()) }),
@@ -51,10 +69,12 @@ export function createAgentsApi(ctx: AgentsApiContext): CompleteHostServiceRegis
const name = requireString(payload, 'name');
const inheritWorkspace = isRecord(payload) ? payload.inheritWorkspace === true : undefined;
const snapshot = await createAgent(name, { inheritWorkspace });
syncAllProviderAuthToRuntime().catch((err) => {
console.warn('[agents] Failed to sync provider auth after agent creation:', err);
});
scheduleGatewayReload(ctx, 'create-agent');
if (!usesCcConnect(ctx)) {
syncAllProviderAuthToRuntime().catch((err) => {
console.warn('[agents] Failed to sync provider auth after agent creation:', err);
});
}
await refreshActiveRuntime(ctx, 'create-agent');
void ensureClawXContext({ waitForAllConfiguredWorkspaces: true }).catch((err) => {
console.warn('[agents] Failed to ensure ClawX context after agent creation:', err);
});
@@ -64,29 +84,52 @@ 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');
await refreshActiveRuntime(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 providerAccountIdProvided = isRecord(payload)
&& Object.prototype.hasOwnProperty.call(payload, 'providerAccountId');
const providerAccountId = isRecord(payload) && typeof payload.providerAccountId === 'string'
? payload.providerAccountId
: null;
const permissionMode = isRecord(payload) && (payload.permissionMode === 'suggest' || payload.permissionMode === 'full-auto')
? payload.permissionMode
: undefined;
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);
if (providerAccountIdProvided) {
await setCcConnectAgentProviderBinding(agentId, providerAccountId);
snapshot.agents = snapshot.agents.map((agent) => (
agent.id === agentId ? { ...agent, providerAccountId } : agent
));
}
if (permissionMode) {
await setCcConnectAgentPermissionMode(agentId, permissionMode);
snapshot.agents = snapshot.agents.map((agent) => (
agent.id === agentId ? { ...agent, permissionMode } : agent
));
}
if (!usesCcConnect(ctx)) {
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 refreshActiveRuntime(ctx, 'update-agent-model');
return { success: true, ...snapshot };
},
delete: async (payload) => {
const agentId = requireString(payload, 'id');
const { snapshot, removedEntry } = await deleteAgentConfig(agentId);
await restartGatewayForAgentDeletion(ctx);
await deleteCcConnectAgentBinding(agentId);
await restartRuntimeForAgentDeletion(ctx);
await removeAgentWorkspaceDirectory(removedEntry).catch((err) => {
console.warn('[agents] Failed to remove workspace after agent deletion:', err);
});
@@ -96,7 +139,7 @@ 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');
await refreshActiveRuntime(ctx, 'assign-channel');
return { success: true, ...snapshot };
},
removeChannel: async (payload) => {
@@ -122,7 +165,7 @@ export function createAgentsApi(ctx: AgentsApiContext): CompleteHostServiceRegis
await clearChannelBinding(channelType, accountId);
}
const snapshot = await listAgentsSnapshot();
scheduleGatewayReload(ctx, 'remove-agent-channel');
await refreshActiveRuntime(ctx, 'remove-agent-channel');
return { success: true, ...snapshot };
},
};
+7 -2
View File
@@ -1,4 +1,5 @@
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import type { RuntimeManager } from '../runtime/manager';
import { runOpenClawDoctor, runOpenClawDoctorFix } from '../utils/openclaw-doctor';
import { isRecord } from './payload-utils';
@@ -6,11 +7,15 @@ type OpenClawDoctorPayload = {
mode?: unknown;
};
export function createAppApi(): CompleteHostServiceRegistry['app'] {
export function createAppApi(runtimeManager?: RuntimeManager): CompleteHostServiceRegistry['app'] {
return {
openClawDoctor: async (payload) => {
const body = isRecord(payload) ? payload as OpenClawDoctorPayload : {};
return body.mode === 'fix' ? runOpenClawDoctorFix() : runOpenClawDoctor();
const mode = body.mode === 'fix' ? 'fix' : 'diagnose';
if (runtimeManager) {
return runtimeManager.getActiveProvider().runDoctor(mode);
}
return mode === 'fix' ? runOpenClawDoctorFix() : runOpenClawDoctor();
},
};
}
+13 -35
View File
@@ -48,7 +48,6 @@ 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',
@@ -107,7 +106,6 @@ type LocalScope = 'workspace' | 'openclaw-media' | 'staging';
type ResolvedLocal = {
kind: 'local';
entryKind: 'file' | 'directory';
canonicalPath: string;
scope: LocalScope;
mimeType: string;
@@ -573,21 +571,13 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
}
if (!isSamePath(canonicalCandidate, stagedPath)) throw new AttachmentFailure('invalidReference');
const stagedStat = await fs.stat(canonicalCandidate);
const entryKind = stagedStat.isFile()
? 'file'
: stagedStat.isDirectory()
? 'directory'
: null;
if (!entryKind) throw new AttachmentFailure('notFile');
if (!stagedStat.isFile()) throw new AttachmentFailure('notFile');
return {
kind: 'local',
entryKind,
canonicalPath: canonicalCandidate,
scope: 'staging',
mimeType: entryKind === 'directory'
? DIRECTORY_MIME_TYPE
: mimeTypeHint || mimeTypeForPath(canonicalCandidate),
size: entryKind === 'directory' ? 0 : stagedStat.size,
mimeType: mimeTypeHint || mimeTypeForPath(canonicalCandidate),
size: stagedStat.size,
};
}
}
@@ -599,12 +589,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
throw new AttachmentFailure(attachmentFailure(error));
}
const targetStat = await fs.stat(canonicalCandidate);
const entryKind = targetStat.isFile()
? 'file'
: targetStat.isDirectory()
? 'directory'
: null;
if (!entryKind) throw new AttachmentFailure('notFile');
if (!targetStat.isFile()) throw new AttachmentFailure('notFile');
const workspaceRoot = mediaOnly ? null : await frozenCanonicalDirectory(context.workspaceRoot, fs);
const scope: LocalScope = workspaceRoot && isInside(canonicalCandidate, workspaceRoot)
@@ -613,13 +598,10 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
return {
kind: 'local',
entryKind,
canonicalPath: canonicalCandidate,
scope,
mimeType: entryKind === 'directory'
? DIRECTORY_MIME_TYPE
: mimeTypeHint || mimeTypeForPath(canonicalCandidate),
size: entryKind === 'directory' ? 0 : targetStat.size,
mimeType: mimeTypeHint || mimeTypeForPath(canonicalCandidate),
size: targetStat.size,
};
};
@@ -642,7 +624,6 @@ 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,
@@ -706,7 +687,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
...(displayPath ? { displayPath } : {}),
mimeType: target.mimeType,
size: target.size,
target: { kind: 'local', scope: target.scope, entryKind: target.entryKind, ref },
target: { kind: 'local', scope: target.scope, ref },
};
} catch (error) {
return { ok: false, displayName, error: attachmentFailure(error) };
@@ -718,7 +699,6 @@ 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');
@@ -750,7 +730,6 @@ 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');
@@ -822,10 +801,9 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
}
};
const requireCurrentLocalFileTarget = async (ref: AttachmentFileRef): Promise<ResolvedLocal> => {
const requireCurrentLocalTarget = 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');
}
@@ -836,7 +814,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
ref: AttachmentFileRef,
): Promise<AttachmentOpenHandlersResult> => {
try {
const target = await requireCurrentLocalFileTarget(ref);
const target = await requireCurrentLocalTarget(ref);
if (dependencies.openWith.platform === 'linux') {
return { ok: true, platform: 'linux', handlers: [] };
}
@@ -863,7 +841,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
payload: OpenAttachmentWithPayload,
): Promise<OpenAttachmentResult> => {
try {
const target = await requireCurrentLocalFileTarget(payload?.ref);
const target = await requireCurrentLocalTarget(payload?.ref);
if (typeof payload?.handlerId !== 'string'
|| !payload.handlerId.trim()
|| payload.handlerId.length > HANDLER_ID_MAX_LENGTH) {
@@ -872,7 +850,7 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
await dependencies.openWith.open(
target.canonicalPath,
payload.handlerId,
async () => (await requireCurrentLocalFileTarget(payload.ref)).canonicalPath,
async () => (await requireCurrentLocalTarget(payload.ref)).canonicalPath,
);
return { ok: true };
} catch (error) {
@@ -882,8 +860,8 @@ export function createAttachmentAccess(dependencies: AttachmentAccessDependencie
const revealAttachment = async (ref: AttachmentFileRef): Promise<OpenAttachmentResult> => {
try {
await requireCurrentLocalFileTarget(ref);
const revalidated = await requireCurrentLocalFileTarget(ref);
await requireCurrentLocalTarget(ref);
const revalidated = await requireCurrentLocalTarget(ref);
shell.showItemInFolder(revalidated.canonicalPath);
return { ok: true };
} catch (error) {
+38 -16
View File
@@ -73,6 +73,7 @@ import {
import { buildGatewayHealthSummary } from '../utils/gateway-health';
import { logger } from '../utils/logger';
import type { GatewayManager, GatewayHealthSummary } from '../gateway/manager';
import type { RuntimeManager } from '../runtime/manager';
import { isRecord } from './payload-utils';
const WECHAT_QR_TIMEOUT_MS = 8 * 60 * 1000;
@@ -83,6 +84,7 @@ async function listWhatsAppDirectoryPeersFromConfig(_params: unknown): Promise<u
type ChannelsApiContext = {
gatewayManager: GatewayManager;
runtimeManager?: RuntimeManager;
mainWindow?: BrowserWindow;
};
@@ -265,11 +267,12 @@ export async function buildChannelAccountsView(
]);
let gatewayStatus: GatewayChannelStatusPayload | null = null;
const runtimeStatusSource = ctx.runtimeManager ?? ctx.gatewayManager;
if (!skipRuntime) {
try {
const probe = options?.probe === true;
const rpcStartedAt = Date.now();
gatewayStatus = await ctx.gatewayManager.rpc<GatewayChannelStatusPayload>(
gatewayStatus = await runtimeStatusSource.rpc<GatewayChannelStatusPayload>(
'channels.status',
{ probe },
probe ? 5000 : 8000,
@@ -292,8 +295,9 @@ export async function buildChannelAccountsView(
consecutiveHeartbeatMisses: 0,
consecutiveRpcFailures: 0,
};
const status = ctx.runtimeManager?.getStatus() ?? ctx.gatewayManager.getStatus();
const gatewayHealth = buildGatewayHealthSummary({
status: ctx.gatewayManager.getStatus(),
status,
diagnostics: gatewayDiagnostics,
lastChannelsStatusOkAt,
lastChannelsStatusFailureAt,
@@ -379,7 +383,7 @@ export async function buildChannelAccountsView(
const baseGroupStatus = pickChannelRuntimeStatus(visibleAccountSnapshots, channelSummary, {
gatewayHealthState: effectiveGatewayHealthState,
});
const groupStatus = !gatewayStatus && !skipRuntime && ctx.gatewayManager.getStatus().state === 'running'
const groupStatus = !gatewayStatus && !skipRuntime && status.state === 'running'
? 'degraded'
: effectiveGatewayHealthState && !hasRuntimeError && baseGroupStatus === 'connected'
? 'degraded'
@@ -391,7 +395,7 @@ export async function buildChannelAccountsView(
channelType: uiChannelType,
defaultAccountId,
status: groupStatus,
statusReason: !gatewayStatus && !skipRuntime && ctx.gatewayManager.getStatus().state === 'running'
statusReason: !gatewayStatus && !skipRuntime && status.state === 'running'
? 'channels_status_timeout'
: groupStatus === 'degraded' && effectiveGatewayHealthState
? overlayStatusReason(gatewayHealth, 'gateway_degraded')
@@ -985,13 +989,29 @@ async function ensureScopedChannelBinding(channelType: string, accountId?: strin
await migrateLegacyChannelWideBinding(storedChannelType);
}
function scheduleGatewayChannelRestart(ctx: ChannelsApiContext, reason: string): void {
async function scheduleGatewayChannelRestart(ctx: ChannelsApiContext, reason: string): Promise<void> {
const provider = ctx.runtimeManager?.getActiveProvider();
if (provider?.refreshConfig) {
await provider.refreshConfig({ scope: 'channels', reason, forceRestart: true });
return;
}
if (ctx.gatewayManager.getStatus().state === 'stopped') return;
ctx.gatewayManager.debouncedRestart();
void reason;
}
function scheduleGatewayChannelSaveRefresh(ctx: ChannelsApiContext, channelType: string, reason: string): void {
async function scheduleGatewayChannelSaveRefresh(ctx: ChannelsApiContext, channelType: string, reason: string): Promise<void> {
const provider = ctx.runtimeManager?.getActiveProvider();
if (provider?.refreshConfig) {
const storedChannelType = resolveStoredChannelType(channelType);
await provider.refreshConfig({
scope: 'channels',
reason,
channelType: storedChannelType,
forceRestart: FORCE_RESTART_CHANNELS.has(storedChannelType),
});
return;
}
const storedChannelType = resolveStoredChannelType(channelType);
if (ctx.gatewayManager.getStatus().state === 'stopped') return;
if (FORCE_RESTART_CHANNELS.has(storedChannelType)) {
@@ -1072,7 +1092,7 @@ async function awaitWeChatQrLogin(
});
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}`);
await scheduleGatewayChannelSaveRefresh(ctx, OPENCLAW_WECHAT_CHANNEL_TYPE, `wechat:loginSuccess:${normalizedAccountId}`);
if (activeQrLogins.get(loginKey) !== sessionKey) return;
emitChannelEvent(ctx, UI_WECHAT_CHANNEL_TYPE, 'success', {
@@ -1135,7 +1155,7 @@ 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}`);
await scheduleGatewayChannelSaveRefresh(ctx, channelType, `channel:setDefaultAccount:${channelType}`);
return { success: true };
},
bindingSave: async (payload) => {
@@ -1152,7 +1172,7 @@ export function createChannelsApi(ctx: ChannelsApiContext): CompleteHostServiceR
await migrateLegacyChannelWideBinding(storedChannelType);
}
await assignChannelAccountToAgent(agentId, storedChannelType, accountId);
scheduleGatewayChannelSaveRefresh(ctx, channelType, `channel:setBinding:${channelType}`);
await scheduleGatewayChannelSaveRefresh(ctx, channelType, `channel:setBinding:${channelType}`);
return { success: true };
},
bindingDelete: async (payload) => {
@@ -1160,7 +1180,7 @@ 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}`);
await scheduleGatewayChannelSaveRefresh(ctx, channelType, `channel:clearBinding:${channelType}`);
return { success: true };
},
validateConfig: async (payload) => {
@@ -1178,23 +1198,25 @@ export function createChannelsApi(ctx: ChannelsApiContext): CompleteHostServiceR
const accountId = optionalString(payload, 'accountId');
await validateCanonicalAccountId(channelType, accountId, { allowLegacyConfiguredId: true });
const storedChannelType = resolveStoredChannelType(channelType);
await ensureChannelPluginInstalled(storedChannelType);
if (ctx.runtimeManager?.getActiveProvider().kind !== 'cc-connect') {
await ensureChannelPluginInstalled(storedChannelType);
}
const existingValues = await getChannelFormValues(channelType, accountId);
if (isSameConfigValues(existingValues, config)) {
await ensureScopedChannelBinding(channelType, accountId);
scheduleGatewayChannelSaveRefresh(ctx, storedChannelType, `channel:saveConfigNoChange:${storedChannelType}`);
await scheduleGatewayChannelSaveRefresh(ctx, storedChannelType, `channel:saveConfigNoChange:${storedChannelType}`);
return { success: true, noChange: true };
}
await saveChannelConfig(channelType, config, accountId);
await ensureScopedChannelBinding(channelType, accountId);
scheduleGatewayChannelSaveRefresh(ctx, storedChannelType, `channel:saveConfig:${storedChannelType}`);
await scheduleGatewayChannelSaveRefresh(ctx, storedChannelType, `channel:saveConfig:${storedChannelType}`);
return { success: 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)}`);
await scheduleGatewayChannelRestart(ctx, `channel:setEnabled:${resolveStoredChannelType(channelType)}`);
return { success: true };
},
formValues: async (payload) => {
@@ -1209,11 +1231,11 @@ export function createChannelsApi(ctx: ChannelsApiContext): CompleteHostServiceR
if (accountId) {
await deleteChannelAccountConfig(channelType, accountId);
await clearChannelBinding(storedChannelType, accountId);
scheduleGatewayChannelSaveRefresh(ctx, storedChannelType, `channel:deleteAccount:${storedChannelType}`);
await scheduleGatewayChannelSaveRefresh(ctx, storedChannelType, `channel:deleteAccount:${storedChannelType}`);
} else {
await deleteChannelConfig(channelType);
await clearAllBindingsForChannel(storedChannelType);
scheduleGatewayChannelRestart(ctx, `channel:deleteConfig:${storedChannelType}`);
await scheduleGatewayChannelRestart(ctx, `channel:deleteConfig:${storedChannelType}`);
}
return { success: true };
},
+60 -29
View File
@@ -1,6 +1,8 @@
import type { BrowserWindow } from 'electron';
import type { GatewayManager } from '../gateway/manager';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import type { RuntimeManager } from '../runtime/manager';
import type { RuntimeSendWithMediaPayload } from '../runtime/types';
import { logger } from '../utils/logger';
import { createAcpChatService } from './acp-chat-service';
import type { AcpSessionAccessRegistry } from './acp-session-access-registry';
@@ -41,27 +43,19 @@ function normalizeMedia(media: unknown): Array<{ filePath: string; mimeType: str
});
}
export function createChatApi({
gatewayManager,
mainWindow,
acpSessionAccessRegistry,
}: {
gatewayManager: GatewayManager;
mainWindow: BrowserWindow;
acpSessionAccessRegistry: AcpSessionAccessRegistry;
}): CompleteHostServiceRegistry['chat'] {
const acpChat = createAcpChatService(mainWindow, acpSessionAccessRegistry, gatewayManager);
export function createChatSendWithMediaHandler(
gatewayManager: GatewayManager,
log = logger,
): (payload?: unknown) => ReturnType<CompleteHostServiceRegistry['chat']['sendWithMedia']> {
return 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' };
}
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 {
try {
let message = typeof body.message === 'string' ? body.message : '';
const imageAttachments: Array<Record<string, unknown>> = [];
const fileReferences: string[] = [];
@@ -71,7 +65,7 @@ export function createChatApi({
const fsP = await import('node:fs/promises');
for (const item of media) {
const exists = await fsP.access(item.filePath).then(() => true, () => false);
logger.info(
log.info(
`[chat:sendWithMedia] Processing media: name=${item.fileName}, mimeType=${item.mimeType}, exists=${exists}, isVision=${VISION_MIME_TYPES.has(item.mimeType)}`,
);
@@ -82,7 +76,7 @@ export function createChatApi({
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}`);
log.info(`[chat:sendWithMedia] Read ${fileBuffer.length} bytes, base64 length: ${base64Data.length}`);
imageAttachments.push({
content: base64Data,
mimeType: item.mimeType,
@@ -107,24 +101,61 @@ export function createChatApi({
rpcParams.attachments = imageAttachments;
}
logger.info(
log.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'}`);
log.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) {
log.error(`[chat:sendWithMedia] Error: ${String(error)}`);
return { success: false, error: String(error) };
}
};
}
export function createChatApi({
gatewayManager,
runtimeManager,
mainWindow,
acpSessionAccessRegistry,
}: {
gatewayManager: GatewayManager;
runtimeManager?: RuntimeManager;
mainWindow: BrowserWindow;
acpSessionAccessRegistry: AcpSessionAccessRegistry;
}): CompleteHostServiceRegistry['chat'] {
const acpChat = createAcpChatService(mainWindow, acpSessionAccessRegistry, gatewayManager);
const openClawHandler = createChatSendWithMediaHandler(gatewayManager, logger);
const withOpenClawAcp = async <T>(operation: () => Promise<T>) => {
if (runtimeManager && await runtimeManager.getActiveKind() !== 'openclaw') {
return {
success: false,
error: 'ACP chat is only available for the OpenClaw runtime',
} as T;
}
return operation();
};
return {
sendWithMedia: async (payload) => {
if (!runtimeManager) return openClawHandler(payload);
try {
const result = await runtimeManager.getActiveProvider().sendMessageWithMedia(
(isRecord(payload) ? payload : {}) as RuntimeSendWithMediaPayload,
);
return { success: true, result };
} catch (error) {
logger.error(`[chat:sendWithMedia] Error: ${String(error)}`);
return { success: false, error: String(error) };
}
},
loadAcpSession: (payload) => acpChat.loadSession(payload),
sendAcpPrompt: (payload) => acpChat.sendPrompt(payload),
cancelAcpSession: (payload) => acpChat.cancelSession(payload),
respondAcpPermission: (payload) => acpChat.respondPermission(payload),
loadAcpSession: (payload) => withOpenClawAcp(() => acpChat.loadSession(payload)),
sendAcpPrompt: (payload) => withOpenClawAcp(() => acpChat.sendPrompt(payload)),
cancelAcpSession: (payload) => withOpenClawAcp(() => acpChat.cancelSession(payload)),
respondAcpPermission: (payload) => withOpenClawAcp(() => acpChat.respondPermission(payload)),
};
}
+141 -135
View File
@@ -1,16 +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 { parseCronSessionKey, type CronSessionKeyParts } from '@shared/chat/cron-session';
import type { CronJob, CronJobDelivery, CronSchedule } from '@shared/types/cron';
import type { HostSuccess } from '@shared/host-api/contract';
import type { CronJob, CronJobCreateInput, CronJobDelivery, CronJobUpdateInput, CronSchedule } from '@shared/types/cron';
import type { GatewayManager } from '../gateway/manager';
import type { CronLiveRunBroker } from './cron-live-run-broker';
import type { RuntimeManager } from '../runtime/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 {
@@ -49,6 +47,12 @@ interface CronRunLogEntry {
provider?: string;
}
interface CronSessionKeyParts {
agentId: string;
jobId: string;
runSessionId?: string;
}
interface CronSessionFallbackMessage {
id: string;
role: 'user' | 'assistant';
@@ -58,7 +62,20 @@ interface CronSessionFallbackMessage {
}
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;
const parts = sessionKey.split(':');
if (parts.length < 4 || parts[2] !== 'cron') return null;
const agentId = parts[1] || 'main';
const jobId = parts[3];
if (!jobId) return null;
if (parts.length === 4) return { agentId, jobId };
if (parts.length === 6 && parts[4] === 'run' && parts[5]) {
return { agentId, jobId, runSessionId: parts[5] };
}
return null;
}
function normalizeTimestampMs(value: unknown): number | undefined {
if (typeof value === 'number' && Number.isFinite(value)) {
@@ -78,83 +95,14 @@ function formatDuration(durationMs: number | undefined): string | null {
return `${Math.round(durationMs / 1000)}s`;
}
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 {
function buildCronRunMessage(entry: CronRunLogEntry, index: number): 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 = fullReply?.trim() || summary || error;
let content = summary || error;
if (!content) {
content = status === 'error' ? 'Scheduled task failed.' : 'Scheduled task completed.';
}
@@ -249,7 +197,6 @@ 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[] {
@@ -286,7 +233,7 @@ function buildCronSessionFallbackMessages(params: {
}
matchingRuns.forEach((entry, index) => {
const message = buildCronRunMessage(entry, index, params.fullReplies?.get(entry));
const message = buildCronRunMessage(entry, index);
if (message) messages.push(message);
});
@@ -457,7 +404,7 @@ function transformCronJob(job: GatewayCronJob): CronJob {
};
}
async function listCronJobs(gatewayManager: GatewayManager): Promise<CronJob[]> {
export async function listCronJobs(gatewayManager: GatewayManager): Promise<CronJob[]> {
let jobs: GatewayCronJob[] = [];
let usedFallback = false;
@@ -561,74 +508,128 @@ function getId(payload: unknown): string {
return id.trim();
}
export async function createOpenClawCronJob(
gatewayManager: GatewayManager,
input: CronJobCreateInput,
): Promise<CronJob> {
const agentId = typeof input.agentId === 'string' && input.agentId.trim() ? input.agentId.trim() : 'main';
const delivery = normalizeCronDelivery(input.delivery);
const unsupportedDeliveryError = getUnsupportedCronDeliveryError(delivery.channel);
if (delivery.mode === 'announce' && unsupportedDeliveryError) {
throw new Error(unsupportedDeliveryError);
}
const result = await gatewayManager.rpc('cron.add', {
name: input.name,
schedule: normalizeScheduleInput(input.schedule),
payload: { kind: 'agentTurn', message: input.message },
enabled: typeof input.enabled === 'boolean' ? input.enabled : true,
wakeMode: 'next-heartbeat',
sessionTarget: 'isolated',
agentId,
delivery,
});
if (!result || typeof result !== 'object') {
throw new Error('Cron create returned an invalid job');
}
return transformCronJob(result as GatewayCronJob);
}
export async function updateOpenClawCronJob(
gatewayManager: GatewayManager,
payload: { id: string; input: CronJobUpdateInput },
): Promise<CronJob> {
const id = getId(payload);
const input = isRecord(payload.input) ? payload.input : {};
const patch = buildCronUpdatePatch(input);
delete patch.id;
delete patch.input;
const deliveryPatch = patch.delivery && typeof patch.delivery === 'object'
? patch.delivery as Record<string, unknown>
: undefined;
const deliveryChannel = typeof deliveryPatch?.channel === 'string' && deliveryPatch.channel.trim()
? deliveryPatch.channel.trim()
: undefined;
const deliveryMode = typeof deliveryPatch?.mode === 'string' && deliveryPatch.mode.trim()
? deliveryPatch.mode.trim()
: undefined;
const unsupportedDeliveryError = getUnsupportedCronDeliveryError(deliveryChannel);
if (unsupportedDeliveryError && deliveryMode !== 'none') {
throw new Error(unsupportedDeliveryError);
}
const result = await gatewayManager.rpc('cron.update', { id, patch });
if (!result || typeof result !== 'object') {
throw new Error('Cron update returned an invalid job');
}
return transformCronJob(result as GatewayCronJob);
}
function normalizeHostSuccess(result: unknown): HostSuccess {
if (isRecord(result) && typeof result.success === 'boolean') {
return { success: result.success, ...(typeof result.error === 'string' ? { error: result.error } : {}) };
}
return { success: true };
}
export async function deleteOpenClawCronJob(gatewayManager: GatewayManager, payload: unknown): Promise<HostSuccess> {
return normalizeHostSuccess(await gatewayManager.rpc('cron.remove', { id: getId(payload) }));
}
export async function toggleOpenClawCronJob(gatewayManager: GatewayManager, payload: { id: string; enabled: boolean }): Promise<HostSuccess> {
return normalizeHostSuccess(await gatewayManager.rpc('cron.update', {
id: getId(payload),
patch: { enabled: payload.enabled === true },
}));
}
export async function triggerOpenClawCronJob(gatewayManager: GatewayManager, payload: unknown): Promise<HostSuccess> {
return normalizeHostSuccess(await gatewayManager.rpc('cron.run', { id: getId(payload), mode: 'force' }));
}
export function createCronApi({
gatewayManager,
cronLiveRunBroker,
runtimeManager,
}: {
gatewayManager: GatewayManager;
cronLiveRunBroker: CronLiveRunBroker;
runtimeManager?: RuntimeManager;
}): CompleteHostServiceRegistry['cron'] {
const runtimeSupportsCron = () => runtimeManager?.listCapabilities().cron === true;
return {
liveRunOverlays: () => cronLiveRunBroker.getSnapshotSet(),
list: async () => listCronJobs(gatewayManager),
list: async () => {
if (runtimeSupportsCron()) {
return await runtimeManager!.rpc<CronJob[]>('cron.list');
}
return listCronJobs(gatewayManager);
},
create: async (payload) => {
const input = payload;
const agentId = typeof input.agentId === 'string' && input.agentId.trim() ? input.agentId.trim() : 'main';
const delivery = normalizeCronDelivery(input.delivery);
const unsupportedDeliveryError = getUnsupportedCronDeliveryError(delivery.channel);
if (delivery.mode === 'announce' && unsupportedDeliveryError) {
throw new Error(unsupportedDeliveryError);
if (runtimeSupportsCron()) {
return await runtimeManager!.rpc<CronJob>('cron.create', payload);
}
const result = await gatewayManager.rpc('cron.add', {
name: input.name,
schedule: normalizeScheduleInput(input.schedule),
payload: { kind: 'agentTurn', message: input.message },
enabled: typeof input.enabled === 'boolean' ? input.enabled : true,
wakeMode: 'next-heartbeat',
sessionTarget: 'isolated',
agentId,
delivery,
});
if (!result || typeof result !== 'object') {
throw new Error('Cron create returned an invalid job');
}
return transformCronJob(result as GatewayCronJob);
return createOpenClawCronJob(gatewayManager, payload);
},
update: async (payload) => {
const body = payload;
const id = getId(body);
const input = isRecord(body.input) ? body.input : {};
const patch = buildCronUpdatePatch(input);
delete patch.id;
delete patch.input;
const deliveryPatch = patch.delivery && typeof patch.delivery === 'object'
? patch.delivery as Record<string, unknown>
: undefined;
const deliveryChannel = typeof deliveryPatch?.channel === 'string' && deliveryPatch.channel.trim()
? deliveryPatch.channel.trim()
: undefined;
const deliveryMode = typeof deliveryPatch?.mode === 'string' && deliveryPatch.mode.trim()
? deliveryPatch.mode.trim()
: undefined;
const unsupportedDeliveryError = getUnsupportedCronDeliveryError(deliveryChannel);
if (unsupportedDeliveryError && deliveryMode !== 'none') {
throw new Error(unsupportedDeliveryError);
if (runtimeSupportsCron()) {
return await runtimeManager!.rpc<CronJob>('cron.update', payload);
}
const result = await gatewayManager.rpc('cron.update', { id, patch });
if (!result || typeof result !== 'object') {
throw new Error('Cron update returned an invalid job');
return updateOpenClawCronJob(gatewayManager, payload);
},
delete: async (payload) => {
if (runtimeSupportsCron()) {
return await runtimeManager!.rpc<HostSuccess>('cron.delete', { id: getId(payload) });
}
return transformCronJob(result as GatewayCronJob);
return deleteOpenClawCronJob(gatewayManager, payload);
},
delete: async (payload) => gatewayManager.rpc('cron.remove', { id: getId(payload) }),
toggle: async (payload) => {
const body = payload;
return gatewayManager.rpc('cron.update', {
id: getId(body),
patch: { enabled: body.enabled === true },
});
if (runtimeSupportsCron()) {
return await runtimeManager!.rpc<HostSuccess>('cron.toggle', { id: getId(payload), enabled: payload.enabled === true });
}
return toggleOpenClawCronJob(gatewayManager, payload);
},
trigger: async (payload) => {
if (runtimeSupportsCron()) {
return await runtimeManager!.rpc<HostSuccess>('cron.run', { id: getId(payload), mode: 'force' });
}
return triggerOpenClawCronJob(gatewayManager, payload);
},
trigger: async (payload) => gatewayManager.rpc('cron.run', { id: getId(payload), mode: 'force' }),
sessionHistory: async (payload) => {
const body = payload;
const sessionKey = typeof body.sessionKey === 'string' ? body.sessionKey.trim() : '';
@@ -637,6 +638,13 @@ export function createCronApi({
const rawLimit = typeof body.limit === 'number' ? body.limit : Number(body.limit || 200);
const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(Math.floor(rawLimit), 1), 200) : 200;
const activeProvider = runtimeManager?.getActiveProvider();
if (activeProvider?.listCapabilities().history) {
const history = await activeProvider.loadHistory({ sessionKey, limit });
if (history.messages && history.messages.length > 0) {
return history;
}
}
const [jobsResult, runs, sessionEntry] = await Promise.all([
gatewayManager.rpc('cron.list', { includeDisabled: true }, 8000)
.catch(() => ({ jobs: [] as GatewayCronJob[] })),
@@ -645,13 +653,11 @@ export function createCronApi({
]);
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),
-774
View File
@@ -1,774 +0,0 @@
import { createHash, type Hash } from 'node:crypto';
import type { ChatRuntimeEvent } from '../../shared/chat-runtime-events';
import type { GatewayManager } from '../gateway/manager';
import type {
CronLiveRunItem,
CronLiveRunOverlayChange,
CronLiveRunOverlaySnapshot,
CronLiveRunOverlaySnapshotSet,
} from '../../shared/chat/cron-live-run';
import {
getCronSessionBaseKey,
parseCronSessionKey,
} from '../../shared/chat/cron-session';
interface ActiveCronLiveRun {
snapshot: CronLiveRunOverlaySnapshot;
fingerprintOrder: string[];
fingerprints: Set<string>;
}
export const MAX_CRON_LIVE_EVENT_FINGERPRINTS = 256;
export const MAX_ACTIVE_CRON_LIVE_RUNS = 32;
export const MAX_CRON_LIVE_ITEMS_PER_RUN = 128;
export const MAX_CRON_LIVE_ASSISTANT_CHARS = 500_000;
export const MAX_CRON_LIVE_ITEM_DETAIL_CHARS = 100_000;
export const MAX_CRON_LIVE_TERMINAL_TOMBSTONES = 128;
export const MAX_CRON_LIVE_TRAVERSAL_DEPTH = 64;
export const MAX_CRON_LIVE_TRAVERSAL_NODES = 2_048;
export const MAX_CRON_LIVE_TRAVERSAL_KEYS = 1_024;
export const MAX_CRON_LIVE_TRAVERSAL_STRING_CHARS = 16_384;
const DEPTH_MARKER = '[Truncated:Depth]';
const NODE_MARKER = '[Truncated:Nodes]';
const KEY_MARKER = '[Truncated:Keys]';
const PROPERTY_MARKER = '[Unserializable:Property]';
const INVALID_DATE_MARKER = '[Invalid:Date]';
const OUTPUT_MARKER = '[Truncated:Output]';
interface TraversalState {
nodes: number;
keys: number;
}
type BoundedKeys = { keys: string[] } | { marker: string };
function stringMarker(length: number): string {
return `[Truncated:String:${length}]`;
}
function truncateTraversalString(value: string): string {
if (value.length <= MAX_CRON_LIVE_TRAVERSAL_STRING_CHARS) return value;
const marker = stringMarker(value.length);
return `${value.slice(0, MAX_CRON_LIVE_TRAVERSAL_STRING_CHARS - marker.length)}${marker}`;
}
function enterTraversalNode(state: TraversalState, depth: number): string | undefined {
if (depth > MAX_CRON_LIVE_TRAVERSAL_DEPTH) return DEPTH_MARKER;
state.nodes += 1;
return state.nodes > MAX_CRON_LIVE_TRAVERSAL_NODES ? NODE_MARKER : undefined;
}
function collectBoundedKeys(value: object, state: TraversalState): BoundedKeys {
const keys: string[] = [];
let scanned = 0;
try {
for (const key in value) {
scanned += 1;
if (scanned > MAX_CRON_LIVE_TRAVERSAL_KEYS || state.keys >= MAX_CRON_LIVE_TRAVERSAL_KEYS) {
return { marker: KEY_MARKER };
}
if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
if (key.length > MAX_CRON_LIVE_TRAVERSAL_STRING_CHARS) {
return { marker: stringMarker(key.length) };
}
state.keys += 1;
keys.push(key);
}
} catch {
return { marker: PROPERTY_MARKER };
}
keys.sort((left, right) => left < right ? -1 : left > right ? 1 : 0);
return { keys };
}
function readProperty(value: object, key: string): { value: unknown } | { marker: string } {
try {
return { value: (value as Record<string, unknown>)[key] };
} catch {
return { marker: PROPERTY_MARKER };
}
}
function hashToken(hash: Hash, value: string): void {
hash.update(String(value.length));
hash.update(':');
hash.update(value);
hash.update(';');
}
function hashUnknown(
hash: Hash,
value: unknown,
state: TraversalState,
seen: Map<object, number>,
depth = 0,
): void {
const valueType = typeof value;
if (value === null || valueType !== 'object') {
const marker = enterTraversalNode(state, depth);
if (marker) {
hashToken(hash, marker);
return;
}
if (valueType === 'string') {
hashToken(hash, `string:${truncateTraversalString(value as string)}`);
} else if (valueType === 'bigint') {
hashToken(hash, '[Unsupported:bigint]');
} else if (valueType === 'number' || valueType === 'boolean' || valueType === 'undefined') {
hashToken(hash, `${valueType}:${String(value)}`);
} else {
hashToken(hash, `[Unsupported:${valueType}]`);
}
return;
}
const objectValue = value as object;
const seenId = seen.get(objectValue);
if (seenId !== undefined) {
hashToken(hash, `ref:${seenId}`);
return;
}
const marker = enterTraversalNode(state, depth);
if (marker) {
hashToken(hash, marker);
return;
}
seen.set(objectValue, seen.size);
if (value instanceof Date) {
const time = value.getTime();
hashToken(hash, Number.isFinite(time) ? `date:${value.toISOString()}` : INVALID_DATE_MARKER);
return;
}
if (Array.isArray(value)) {
hashToken(hash, `array:${value.length}`);
if (value.length > MAX_CRON_LIVE_TRAVERSAL_NODES - state.nodes) {
hashToken(hash, NODE_MARKER);
return;
}
for (let index = 0; index < value.length; index += 1) {
const property = readProperty(value, String(index));
if ('marker' in property) {
hashToken(hash, property.marker);
} else {
hashUnknown(hash, property.value, state, seen, depth + 1);
}
}
return;
}
const boundedKeys = collectBoundedKeys(objectValue, state);
if ('marker' in boundedKeys) {
hashToken(hash, boundedKeys.marker);
return;
}
hashToken(hash, `object:${boundedKeys.keys.length}`);
for (const key of boundedKeys.keys) {
hashToken(hash, key);
const property = readProperty(objectValue, key);
if ('marker' in property) {
hashToken(hash, property.marker);
} else {
hashUnknown(hash, property.value, state, seen, depth + 1);
}
}
}
function runtimeEventFingerprint(event: ChatRuntimeEvent): string {
try {
const hash = createHash('sha256');
hash.update(`${event.type}|`);
const state: TraversalState = { nodes: 0, keys: 0 };
const seen = new Map<object, number>();
let fingerprintValue: unknown;
switch (event.type) {
case 'run.started':
fingerprintValue = event.startedAt;
break;
case 'run.ended':
fingerprintValue = [event.status, event.endedAt, event.error, event.livenessState, event.replayInvalid, event.stopReason];
break;
case 'assistant.delta':
fingerprintValue = [event.text, event.delta, event.replace, event.phase, event.mediaUrls];
break;
case 'thinking.delta':
fingerprintValue = [event.text, event.delta];
break;
case 'tool.started':
fingerprintValue = [event.toolCallId, event.name, event.args];
break;
case 'tool.updated':
fingerprintValue = [event.toolCallId, event.name, event.partialResult];
break;
case 'tool.completed':
fingerprintValue = [event.toolCallId, event.name, event.result, event.meta, event.isError];
break;
case 'command.output':
fingerprintValue = [
event.itemId,
event.toolCallId,
event.name,
event.title,
event.output,
event.status,
event.phase,
event.exitCode,
event.durationMs,
event.cwd,
];
break;
case 'patch.completed':
fingerprintValue = [
event.itemId,
event.toolCallId,
event.name,
event.title,
event.summary,
event.added,
event.modified,
event.deleted,
];
break;
case 'approval.updated':
fingerprintValue = [
event.itemId,
event.toolCallId,
event.title,
event.kind,
event.phase,
event.status,
event.message,
];
break;
}
hashUnknown(hash, fingerprintValue, state, seen);
return hash.digest('hex');
} catch {
return createHash('sha256').update(`${event.type}|[FingerprintError]`).digest('hex');
}
}
class LimitedStringWriter {
private readonly chunks: string[] = [];
private length = 0;
private truncated = false;
constructor(private readonly limit: number) {}
get full(): boolean {
return this.length >= this.limit;
}
append(value: string): void {
if (this.full) {
this.truncated = true;
return;
}
const available = this.limit - this.length;
const chunk = value.slice(0, available);
this.chunks.push(chunk);
this.length += chunk.length;
if (chunk.length < value.length) this.truncated = true;
}
toString(): string {
const rendered = this.chunks.join('');
return this.truncated
? `${rendered.slice(0, this.limit - OUTPUT_MARKER.length)}${OUTPUT_MARKER}`
: rendered;
}
}
function writeJsonString(writer: LimitedStringWriter, value: string): void {
writer.append('"');
for (const character of value) {
if (writer.full) return;
writer.append(JSON.stringify(character).slice(1, -1));
}
writer.append('"');
}
function writeStableJson(
writer: LimitedStringWriter,
value: unknown,
depth: number,
state: TraversalState,
ancestors: WeakSet<object>,
): void {
if (writer.full) {
writer.append('');
return;
}
const marker = enterTraversalNode(state, depth);
if (marker) {
writeJsonString(writer, marker);
return;
}
if (typeof value === 'string') {
writeJsonString(writer, truncateTraversalString(value));
return;
}
if (typeof value === 'bigint') {
writeJsonString(writer, '[Unsupported:bigint]');
return;
}
if (value === undefined) {
writer.append('null');
return;
}
if (value === null || typeof value !== 'object') {
writer.append(JSON.stringify(value) ?? 'null');
return;
}
if (ancestors.has(value)) {
writeJsonString(writer, '[Circular]');
return;
}
ancestors.add(value);
if (value instanceof Date) {
const time = value.getTime();
writeJsonString(writer, Number.isFinite(time) ? value.toISOString() : INVALID_DATE_MARKER);
ancestors.delete(value);
return;
}
const indent = ' '.repeat(depth + 1);
const closingIndent = ' '.repeat(depth);
if (Array.isArray(value)) {
if (value.length > MAX_CRON_LIVE_TRAVERSAL_NODES - state.nodes) {
writeJsonString(writer, NODE_MARKER);
ancestors.delete(value);
return;
}
writer.append('[');
for (let index = 0; index < value.length && !writer.full; index += 1) {
writer.append(`${index === 0 ? '\n' : ',\n'}${indent}`);
const property = readProperty(value, String(index));
if ('marker' in property) {
writeJsonString(writer, property.marker);
} else {
writeStableJson(writer, property.value, depth + 1, state, ancestors);
}
}
if (value.length > 0) writer.append(`\n${closingIndent}`);
writer.append(']');
} else {
const boundedKeys = collectBoundedKeys(value, state);
if ('marker' in boundedKeys) {
writeJsonString(writer, boundedKeys.marker);
ancestors.delete(value);
return;
}
writer.append('{');
let written = 0;
for (const key of boundedKeys.keys) {
if (writer.full) break;
const property = readProperty(value, key);
const child = 'marker' in property ? property.marker : property.value;
if (child === undefined) continue;
const index = written;
written += 1;
writer.append(`${index === 0 ? '\n' : ',\n'}${indent}`);
writeJsonString(writer, key);
writer.append(': ');
if ('marker' in property) {
writeJsonString(writer, property.marker);
} else {
writeStableJson(writer, child, depth + 1, state, ancestors);
}
}
if (written > 0) writer.append(`\n${closingIndent}`);
writer.append('}');
}
ancestors.delete(value);
}
function truncateStart(value: string, limit = MAX_CRON_LIVE_ITEM_DETAIL_CHARS): string {
return value.length <= limit ? value : value.slice(0, limit);
}
function truncateEnd(value: string, limit: number): string {
return value.length <= limit ? value : value.slice(-limit);
}
function encodeTuple(parts: readonly string[]): string {
return `${parts.length}|${parts.map((part) => `${part.length}:${part}`).join('')}`;
}
function isBoundedIdentityComponent(value: unknown): value is string {
return typeof value === 'string'
&& value.length > 0
&& value.length <= MAX_CRON_LIVE_ITEM_DETAIL_CHARS;
}
function processIdentityComponent(event: ChatRuntimeEvent): string | undefined {
if (event.type === 'tool.started' || event.type === 'tool.updated' || event.type === 'tool.completed') {
return event.toolCallId;
}
if (event.type === 'command.output') {
return event.itemId ?? event.toolCallId ?? event.name ?? 'command';
}
if (event.type === 'patch.completed') {
return event.itemId ?? event.toolCallId ?? event.name ?? 'patch';
}
if (event.type === 'approval.updated') {
return event.itemId ?? event.toolCallId ?? event.kind ?? 'approval';
}
return undefined;
}
function hasBoundedEventIdentity(event: ChatRuntimeEvent): event is ChatRuntimeEvent & { sessionKey: string } {
if (!isBoundedIdentityComponent(event.sessionKey) || !isBoundedIdentityComponent(event.runId)) return false;
const itemIdentity = processIdentityComponent(event);
return itemIdentity === undefined || isBoundedIdentityComponent(itemIdentity);
}
function stableDetail(value: unknown): string | undefined {
if (value === undefined) return undefined;
if (typeof value === 'string') return truncateTraversalString(value);
try {
const writer = new LimitedStringWriter(MAX_CRON_LIVE_ITEM_DETAIL_CHARS);
writeStableJson(writer, value, 0, { nodes: 0, keys: 0 }, new WeakSet<object>());
return writer.toString();
} catch {
return '[Unserializable]';
}
}
function upsertItem(
items: CronLiveRunItem[],
item: CronLiveRunItem,
): void {
const existingIndex = items.findIndex(({ id }) => id === item.id);
if (existingIndex === -1) {
items.push(item);
if (items.length > MAX_CRON_LIVE_ITEMS_PER_RUN) items.splice(0, items.length - MAX_CRON_LIVE_ITEMS_PER_RUN);
} else {
items[existingIndex] = item;
}
}
function commandStatus(event: Extract<ChatRuntimeEvent, { type: 'command.output' }>): 'running' | 'completed' | 'failed' {
if (event.status === 'failed' || event.status === 'error' || (event.exitCode != null && event.exitCode !== 0)) {
return 'failed';
}
if (
event.phase === 'end'
|| event.phase === 'completed'
|| event.status === 'completed'
|| event.status === 'success'
|| event.exitCode === 0
) {
return 'completed';
}
return 'running';
}
function approvalStatus(event: Extract<ChatRuntimeEvent, { type: 'approval.updated' }>): 'running' | 'completed' | 'failed' {
if (event.status === 'denied' || event.status === 'rejected' || event.status === 'failed' || event.status === 'error') {
return 'failed';
}
if (
event.phase === 'resolved'
|| event.phase === 'completed'
|| event.status === 'approved'
|| event.status === 'granted'
|| event.status === 'completed'
) {
return 'completed';
}
return 'running';
}
function cloneSnapshot(snapshot: CronLiveRunOverlaySnapshot): CronLiveRunOverlaySnapshot {
return {
...snapshot,
items: snapshot.items.map((item) => ({ ...item })),
};
}
function compareSnapshots(left: CronLiveRunOverlaySnapshot, right: CronLiveRunOverlaySnapshot): number {
return left.updatedAt - right.updatedAt
|| left.runId.localeCompare(right.runId)
|| left.sourceSessionKey.localeCompare(right.sourceSessionKey);
}
export function reduceCronLiveRunEvent(
snapshot: CronLiveRunOverlaySnapshot,
event: ChatRuntimeEvent,
): CronLiveRunOverlaySnapshot {
const next = cloneSnapshot(snapshot);
next.updatedAt = event.ts ?? snapshot.updatedAt;
if (event.type === 'run.started') {
next.startedAt = event.startedAt ?? next.startedAt;
return next;
}
if (event.type === 'assistant.delta') {
if (event.text !== undefined) {
next.assistantText = event.text;
} else if (event.replace) {
next.assistantText = event.delta ?? '';
} else if (event.delta) {
next.assistantText += event.delta;
}
next.assistantText = truncateEnd(next.assistantText, MAX_CRON_LIVE_ASSISTANT_CHARS);
next.thinking = false;
return next;
}
if (event.type === 'thinking.delta') {
next.thinking = true;
return next;
}
if (event.type === 'tool.started' || event.type === 'tool.updated' || event.type === 'tool.completed') {
const id = encodeTuple([snapshot.runId, 'tool', event.toolCallId]);
const existingItem = next.items.find((item) => item.id === id);
const existing = existingItem?.kind === 'tool' ? existingItem : undefined;
const inputText = event.type === 'tool.started' ? stableDetail(event.args) : existing?.inputText;
const outputValue = event.type === 'tool.updated' ? event.partialResult : event.type === 'tool.completed' ? event.result : undefined;
const outputText = outputValue === undefined ? existing?.outputText : stableDetail(outputValue);
const error = event.type === 'tool.completed' && event.isError ? outputText : undefined;
upsertItem(next.items, {
kind: 'tool',
id,
toolCallId: event.toolCallId,
title: truncateStart(event.name),
status: event.type === 'tool.completed' ? (event.isError ? 'failed' : 'completed') : 'running',
...(inputText === undefined ? {} : { inputText }),
...(outputText === undefined ? {} : { outputText }),
...(error === undefined ? {} : { error }),
});
return next;
}
if (event.type === 'command.output') {
const sourceId = event.itemId ?? event.toolCallId ?? event.name ?? 'command';
const id = encodeTuple([snapshot.runId, 'command', sourceId]);
const existingItem = next.items.find((item) => item.id === id);
const existing = existingItem?.kind === 'command' ? existingItem : undefined;
upsertItem(next.items, {
kind: 'command',
id,
title: truncateStart(event.title ?? existing?.title ?? `${event.name ?? 'Command'} output`),
status: commandStatus(event),
output: truncateEnd(`${existing?.output ?? ''}${event.output ?? ''}`, MAX_CRON_LIVE_ITEM_DETAIL_CHARS),
...(event.exitCode === undefined && existing?.exitCode === undefined
? {}
: { exitCode: event.exitCode ?? existing?.exitCode }),
});
return next;
}
if (event.type === 'patch.completed') {
const sourceId = event.itemId ?? event.toolCallId ?? event.name ?? 'patch';
const id = encodeTuple([snapshot.runId, 'patch', sourceId]);
upsertItem(next.items, {
kind: 'patch',
id,
title: truncateStart(event.title ?? event.name ?? 'Patch'),
...(event.summary === undefined ? {} : { summary: truncateStart(event.summary) }),
...(event.added === undefined ? {} : { added: event.added }),
...(event.modified === undefined ? {} : { modified: event.modified }),
...(event.deleted === undefined ? {} : { deleted: event.deleted }),
});
return next;
}
if (event.type === 'approval.updated') {
const sourceId = event.itemId ?? event.toolCallId ?? event.kind ?? 'approval';
const id = encodeTuple([snapshot.runId, 'approval', sourceId]);
const existingItem = next.items.find((item) => item.id === id);
const existing = existingItem?.kind === 'approval' ? existingItem : undefined;
upsertItem(next.items, {
kind: 'approval',
id,
title: truncateStart(event.title ?? existing?.title ?? 'Approval'),
status: approvalStatus(event),
...(event.message === undefined && existing?.message === undefined
? {}
: { message: truncateStart(event.message ?? existing?.message ?? '') }),
});
}
return next;
}
export class CronLiveRunBroker {
private readonly activeRuns = new Map<string, ActiveCronLiveRun>();
private readonly terminalTombstones = new Set<string>();
private readonly terminalTombstoneOrder: string[] = [];
private revision = 0;
constructor(private readonly now: () => number = Date.now) {}
ingestRuntimeEvent(event: ChatRuntimeEvent): CronLiveRunOverlayChange[] {
if (!hasBoundedEventIdentity(event)) return [];
const parts = parseCronSessionKey(event.sessionKey);
if (!parts?.runSessionId) return [];
const identity = encodeTuple([event.sessionKey, event.runId]);
if (this.terminalTombstones.has(identity)) return [];
const active = this.activeRuns.get(identity);
if (active && Number.isFinite(event.seq) && event.seq! <= (active.snapshot.lastSeq ?? -Infinity)) {
return [];
}
if (event.type === 'run.ended') {
const changes: CronLiveRunOverlayChange[] = [];
if (active) {
this.revision += 1;
changes.push({
kind: 'remove',
revision: this.revision,
canonicalSessionKey: active.snapshot.canonicalSessionKey,
sourceSessionKey: active.snapshot.sourceSessionKey,
runId: active.snapshot.runId,
reason: 'ended',
terminalStatus: event.status,
...(event.error === undefined ? {} : { terminalError: truncateStart(event.error) }),
});
this.activeRuns.delete(identity);
}
this.addTerminalTombstone(identity);
return changes;
}
let fingerprint: string | undefined;
if (!Number.isFinite(event.seq)) {
fingerprint = runtimeEventFingerprint(event);
if (active?.fingerprints.has(fingerprint)) return [];
}
const changes: CronLiveRunOverlayChange[] = [];
if (!active && this.activeRuns.size >= MAX_ACTIVE_CRON_LIVE_RUNS) {
const [evictedIdentity, evicted] = [...this.activeRuns.entries()]
.sort(([, left], [, right]) => compareSnapshots(left.snapshot, right.snapshot))[0];
this.revision += 1;
changes.push({
kind: 'remove',
revision: this.revision,
canonicalSessionKey: evicted.snapshot.canonicalSessionKey,
sourceSessionKey: evicted.snapshot.sourceSessionKey,
runId: evicted.snapshot.runId,
reason: 'evicted',
});
this.activeRuns.delete(evictedIdentity);
}
const current = active?.snapshot ?? {
canonicalSessionKey: getCronSessionBaseKey(event.sessionKey),
sourceSessionKey: event.sessionKey,
runSessionId: parts.runSessionId,
runId: event.runId,
revision: this.revision,
status: 'running',
updatedAt: event.ts ?? this.now(),
assistantText: '',
thinking: false,
items: [],
} satisfies CronLiveRunOverlaySnapshot;
const next = reduceCronLiveRunEvent(current, event);
next.updatedAt = event.ts ?? this.now();
if (Number.isFinite(event.seq)) next.lastSeq = event.seq;
this.revision += 1;
next.revision = this.revision;
const fingerprintOrder = active?.fingerprintOrder ?? [];
const fingerprints = active?.fingerprints ?? new Set<string>();
if (fingerprint) {
fingerprintOrder.push(fingerprint);
fingerprints.add(fingerprint);
if (fingerprintOrder.length > MAX_CRON_LIVE_EVENT_FINGERPRINTS) {
const removed = fingerprintOrder.shift();
if (removed) fingerprints.delete(removed);
}
}
this.activeRuns.set(identity, { snapshot: next, fingerprintOrder, fingerprints });
changes.push({
kind: 'upsert',
revision: this.revision,
snapshot: cloneSnapshot(next),
});
return changes;
}
getSnapshotSet(): CronLiveRunOverlaySnapshotSet {
return {
revision: this.revision,
snapshots: [...this.activeRuns.values()]
.map(({ snapshot }) => cloneSnapshot(snapshot))
.sort(compareSnapshots),
};
}
clear(): CronLiveRunOverlayChange[] {
const changes: CronLiveRunOverlayChange[] = [];
const entries = [...this.activeRuns.entries()]
.sort(([, left], [, right]) => compareSnapshots(left.snapshot, right.snapshot));
for (const [identity, active] of entries) {
this.revision += 1;
changes.push({
kind: 'remove',
revision: this.revision,
canonicalSessionKey: active.snapshot.canonicalSessionKey,
sourceSessionKey: active.snapshot.sourceSessionKey,
runId: active.snapshot.runId,
reason: 'gateway-reset',
});
this.activeRuns.delete(identity);
}
return changes;
}
private addTerminalTombstone(identity: string): void {
this.terminalTombstones.add(identity);
this.terminalTombstoneOrder.push(identity);
if (this.terminalTombstoneOrder.length > MAX_CRON_LIVE_TERMINAL_TOMBSTONES) {
const removed = this.terminalTombstoneOrder.shift();
if (removed) this.terminalTombstones.delete(removed);
}
}
}
export function bindCronLiveRunBroker({
gatewayManager,
broker,
publishChange,
}: {
gatewayManager: GatewayManager;
broker: CronLiveRunBroker;
publishChange: (change: CronLiveRunOverlayChange) => void;
}): void {
let ingestionEnabled = true;
const publishChanges = (changes: CronLiveRunOverlayChange[]) => {
changes.forEach((change) => publishChange(change));
};
gatewayManager.on('chat:runtime-event', (runtimeEvent) => {
if (!ingestionEnabled) return;
publishChanges(broker.ingestRuntimeEvent(runtimeEvent));
});
gatewayManager.on('status', (status) => {
if (status.state === 'running') {
ingestionEnabled = true;
return;
}
ingestionEnabled = false;
publishChanges(broker.clear());
});
gatewayManager.on('exit', () => {
ingestionEnabled = false;
publishChanges(broker.clear());
});
}
+214 -1
View File
@@ -1,17 +1,31 @@
import { execFile } from 'node:child_process';
import { open } from 'node:fs/promises';
import { join } from 'node:path';
import { dirname, join } from 'node:path';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import type { GatewayManager } from '../gateway/manager';
import type { RuntimeManager } from '../runtime/manager';
import type { RuntimeProvider } from '../runtime/types';
import type { CronJob } from '@shared/types/cron';
import { logger } from '../utils/logger';
import { getOpenClawConfigDir } from '../utils/paths';
import { buildGatewayHealthSummary } from '../utils/gateway-health';
import { buildChannelAccountsView, getChannelStatusDiagnostics } from './channels-api';
import { getAcpTraceSnapshot, recordRendererAcpTrace } from './acp-trace';
import {
getCcConnectBinaryPath,
getCcConnectCodexHomeDir,
getCcConnectConfigPath,
getCcConnectManagedDir,
getCcConnectProviderProfilePath,
} from '../runtime/cc-connect-paths';
import { getCodexBundle } from '../runtime/codex-paths';
import { getCcConnectCodexOAuthStatus } from '../runtime/cc-connect-provider-profile';
const DEFAULT_TAIL_LINES = 200;
type DiagnosticsApiContext = {
gatewayManager: GatewayManager;
runtimeManager?: RuntimeManager;
};
async function readTail(filePath: string, tailLines = DEFAULT_TAIL_LINES): Promise<string> {
@@ -46,6 +60,204 @@ async function readTail(filePath: string, tailLines = DEFAULT_TAIL_LINES): Promi
}
}
async function readJsonFile(filePath: string): Promise<Record<string, unknown> | null> {
try {
const file = await open(filePath, 'r');
try {
const stat = await file.stat();
if (stat.size <= 0 || stat.size > 1024 * 1024) return null;
const buffer = Buffer.allocUnsafe(stat.size);
const { bytesRead } = await file.read(buffer, 0, stat.size, 0);
const parsed = JSON.parse(buffer.subarray(0, bytesRead).toString('utf8')) as unknown;
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? parsed as Record<string, unknown>
: null;
} finally {
await file.close();
}
} catch {
return null;
}
}
async function runVersionCommand(binaryPath: string): Promise<Record<string, unknown>> {
return await new Promise((resolve) => {
execFile(binaryPath, ['--version'], { timeout: 5_000 }, (error, stdout, stderr) => {
const output = `${stdout || ''}${stderr ? `\n${stderr}` : ''}`.trim();
if (error) {
resolve({
success: false,
command: `${binaryPath} --version`,
error: error.message,
output,
});
return;
}
resolve({
success: true,
command: `${binaryPath} --version`,
output,
version: output.split('\n')[0]?.trim() || undefined,
});
});
});
}
async function buildBinaryDiagnostics(binaryPath: string, manifestPath: string): Promise<Record<string, unknown>> {
const [manifest, versionCommand] = await Promise.all([
readJsonFile(manifestPath),
runVersionCommand(binaryPath),
]);
return {
binaryPath,
manifestPath,
manifest,
versionCommand,
};
}
async function probeCcConnectManagement(activeProvider: ReturnType<RuntimeManager['getActiveProvider']> | undefined) {
if (!activeProvider?.getControlUi) {
return { success: false, error: 'cc-connect control UI route is unavailable' };
}
try {
const control = await activeProvider.getControlUi();
if (!control.success || !control.url) {
return {
success: false,
port: control.port,
error: control.error || 'cc-connect control UI route is unavailable',
};
}
const url = new URL('/api/v1/status', control.url);
const response = await fetch(url, {
headers: control.token ? { Authorization: `Bearer ${control.token}` } : undefined,
});
const text = await response.text();
return {
success: response.ok,
port: control.port,
status: response.status,
body: text.trim().slice(0, 2_000),
...(response.ok ? {} : { error: text.trim() || `HTTP ${response.status}` }),
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
};
}
}
async function buildCcConnectCronDiagnostics(activeProvider: RuntimeProvider | undefined): Promise<Record<string, unknown>> {
const knownGaps = [
'scheduled-prompt-delivery-unproven',
'heartbeat-unproven',
'external-channel-delivery-targets-unproven',
'muted-scheduled-delivery-behavior-unproven',
];
if (!activeProvider?.rpc) {
return {
success: false,
knownGaps,
error: 'active runtime provider RPC is unavailable',
};
}
try {
const jobs = await activeProvider.rpc<CronJob[]>('cron.list');
const list = Array.isArray(jobs) ? jobs : [];
return {
success: true,
jobCount: list.length,
jobs: list.slice(0, 50).map((job) => ({
id: job.id,
name: job.name,
agentId: job.agentId,
enabled: job.enabled,
deliveryMode: job.delivery?.mode,
hasPrompt: Boolean(job.message && !job.exec),
hasExec: Boolean(job.exec),
sessionMode: job.sessionMode,
timeoutMins: job.timeoutMins,
mute: job.mute,
nextRun: job.nextRun,
lastRun: job.lastRun ? {
time: job.lastRun.time,
success: job.lastRun.success,
hasError: Boolean(job.lastRun.error),
duration: job.lastRun.duration,
} : undefined,
})),
truncated: list.length > 50,
knownGaps,
};
} catch (error) {
return {
success: false,
knownGaps,
error: error instanceof Error ? error.message : String(error),
};
}
}
async function buildRuntimeDiagnostics(ctx: DiagnosticsApiContext) {
const runtimeStatus = ctx.runtimeManager?.getStatus();
const activeProvider = ctx.runtimeManager?.getActiveProvider();
const base = {
activeKind: activeProvider?.kind ?? runtimeStatus?.runtimeKind ?? 'openclaw',
status: runtimeStatus,
operationCapabilities: activeProvider?.listOperationCapabilities?.(),
};
if ((activeProvider?.kind ?? runtimeStatus?.runtimeKind) !== 'cc-connect') {
return base;
}
const managedDir = getCcConnectManagedDir();
const configPath = getCcConnectConfigPath();
const providerProfilePath = getCcConnectProviderProfilePath();
const ccConnectBinaryPath = getCcConnectBinaryPath();
const codexBundle = getCodexBundle();
const [oauth, providerProfile, runtimeLogs, ccConnectBinary, codexBinary, managementApi, cron] = await Promise.all([
getCcConnectCodexOAuthStatus().catch((error) => ({
success: false,
error: error instanceof Error ? error.message : String(error),
})),
readJsonFile(providerProfilePath),
activeProvider?.listLogs?.().catch((error) => ({
content: `Failed to read cc-connect logs: ${String(error)}`,
})),
buildBinaryDiagnostics(ccConnectBinaryPath, join(dirname(ccConnectBinaryPath), 'manifest.json')),
buildBinaryDiagnostics(codexBundle.binaryPath, join(codexBundle.baseDir, 'manifest.json')),
probeCcConnectManagement(activeProvider),
buildCcConnectCronDiagnostics(activeProvider),
]);
const codexHomeDir = providerProfile
&& typeof providerProfile === 'object'
&& typeof (providerProfile as Record<string, unknown>).codexHomeDir === 'string'
? (providerProfile as Record<string, string>).codexHomeDir
: getCcConnectCodexHomeDir();
return {
...base,
ccConnect: {
managedDir,
configPath,
codexHomeDir,
providerProfilePath,
oauth,
providerProfile,
binaries: {
ccConnect: ccConnectBinary,
codex: codexBinary,
},
managementApi,
cron,
logTail: runtimeLogs?.content ?? '',
},
};
}
export function createDiagnosticsApi(ctx: DiagnosticsApiContext): CompleteHostServiceRegistry['diagnostics'] {
return {
gatewaySnapshot: async () => {
@@ -74,6 +286,7 @@ export function createDiagnosticsApi(ctx: DiagnosticsApiContext): CompleteHostSe
capturedAt: Date.now(),
platform: process.platform,
gateway,
runtime: await buildRuntimeDiagnostics(ctx),
channels,
clawxLogTail: await logger.readLogFile(DEFAULT_TAIL_LINES),
gatewayLogTail: await readTail(join(openClawDir, 'logs', 'gateway.log')),
+50 -15
View File
@@ -29,7 +29,9 @@ import {
FILE_PREVIEW_MAX_TEXT_BYTES,
} from '@shared/file-preview/limits';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import { expandPath, resolveOpenClawStateDir } from '../utils/paths';
import type { RuntimeManager } from '../runtime/manager';
import { expandPath } from '../utils/paths';
import { getRuntimeOutboundMediaDir } from '../utils/runtime-media-paths';
import {
resolveClawXStagingDir,
type AttachmentAccess,
@@ -138,6 +140,7 @@ type WorkspaceFs = {
type FilesApiDependencies = {
workspaceFs?: WorkspaceFs;
runtimeManager?: Pick<RuntimeManager, 'getStatus'>;
attachmentAccess?: AttachmentAccess;
openWith?: AttachmentOpenWithService;
stagedAttachments?: StagedAttachmentRegistry;
@@ -376,7 +379,7 @@ function getWorkspaceBinaryCap(value: unknown): number {
return Math.max(1, Math.min(maxBytes ?? FILE_PREVIEW_MAX_BINARY_BYTES, FILE_PREVIEW_MAX_BINARY_BYTES));
}
function getFilePreviewWriteRoots(): string[] {
function getFilePreviewWriteRoots(runtimeManager?: Pick<RuntimeManager, 'getStatus'>): string[] {
const roots: string[] = [];
roots.push(resolve(join(homedir(), '.openclaw')));
try {
@@ -385,12 +388,14 @@ function getFilePreviewWriteRoots(): string[] {
// ignore
}
roots.push(resolve(resolveClawXStagingDir()));
roots.push(resolve(getRuntimeOutboundMediaDir(runtimeManager)));
return roots;
}
async function resolveSandboxedPath(
input: string,
mode: 'read' | 'write' = 'read',
runtimeManager?: Pick<RuntimeManager, 'getStatus'>,
): Promise<ResolvedSandboxedPath> {
if (!input.trim()) {
throw new Error('outsideSandbox');
@@ -403,7 +408,7 @@ async function resolveSandboxedPath(
} catch {
real = resolve(expanded);
}
const writeRoots = getFilePreviewWriteRoots();
const writeRoots = getFilePreviewWriteRoots(runtimeManager);
if (writeRoots.some((root) => isPathInside(real, root))) {
return { realPath: real, readOnly: false };
}
@@ -478,7 +483,17 @@ export function createFilesApi(dependencies: FilesApiDependencies = {}): Complet
return pinned;
};
const stateDir = await ensureDirectory(resolveOpenClawStateDir());
const runtimeOutboundDir = resolve(getRuntimeOutboundMediaDir(dependencies.runtimeManager));
const runtimeStateDir = dirname(dirname(runtimeOutboundDir));
const isCcConnect = dependencies.runtimeManager?.getStatus().runtimeKind === 'cc-connect';
const stateDir = isCcConnect
? await (async () => {
const dataRootPath = dirname(dirname(runtimeStateDir));
const dataRoot = await ensureDirectory(dataRootPath);
const runtimesDir = await ensureDirectory(join(dataRoot.canonicalPath, 'runtimes'), dataRoot);
return ensureDirectory(runtimeStateDir, runtimesDir);
})()
: await ensureDirectory(runtimeStateDir);
const mediaDir = await ensureDirectory(join(stateDir.canonicalPath, 'media'), stateDir);
const outboundDir = await ensureDirectory(join(mediaDir.canonicalPath, 'outbound'), mediaDir);
const stagingRoot = await ensureDirectory(join(outboundDir.canonicalPath, 'clawx-staging'), outboundDir);
@@ -612,16 +627,12 @@ 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: canonicalPath,
stagedPath: filePath,
preview: null,
});
continue;
@@ -848,7 +859,11 @@ export function createFilesApi(dependencies: FilesApiDependencies = {}): Complet
},
readText: async (payload) => {
try {
const { realPath: real, readOnly } = await resolveSandboxedPath(requirePath(payload), 'read');
const { realPath: real, readOnly } = await resolveSandboxedPath(
requirePath(payload),
'read',
dependencies.runtimeManager,
);
const fsP = await import('node:fs/promises');
const stat = await fsP.stat(real);
if (!stat.isFile()) return { ok: false, error: 'notFound' };
@@ -873,7 +888,11 @@ export function createFilesApi(dependencies: FilesApiDependencies = {}): Complet
try {
const body = isRecord(payload) ? payload as PathPayload : {};
const opts = getBinaryOptions(body.opts);
const { realPath: real, readOnly } = await resolveSandboxedPath(requirePath(payload), 'read');
const { realPath: real, readOnly } = await resolveSandboxedPath(
requirePath(payload),
'read',
dependencies.runtimeManager,
);
const fsP = await import('node:fs/promises');
const stat = await fsP.stat(real);
if (!stat.isFile()) return { ok: false, error: 'notFound' };
@@ -903,7 +922,11 @@ export function createFilesApi(dependencies: FilesApiDependencies = {}): Complet
if (Buffer.byteLength(body.content, 'utf8') > FILE_PREVIEW_MAX_TEXT_BYTES) {
return { ok: false, error: 'tooLarge' };
}
const { realPath: real } = await resolveSandboxedPath(requirePath(payload), 'write');
const { realPath: real } = await resolveSandboxedPath(
requirePath(payload),
'write',
dependencies.runtimeManager,
);
const fsP = await import('node:fs/promises');
let stat;
try {
@@ -923,7 +946,11 @@ export function createFilesApi(dependencies: FilesApiDependencies = {}): Complet
},
stat: async (payload) => {
try {
const { realPath: real, readOnly } = await resolveSandboxedPath(requirePath(payload), 'read');
const { realPath: real, readOnly } = await resolveSandboxedPath(
requirePath(payload),
'read',
dependencies.runtimeManager,
);
const fsP = await import('node:fs/promises');
const stat = await fsP.stat(real);
return {
@@ -943,7 +970,11 @@ export function createFilesApi(dependencies: FilesApiDependencies = {}): Complet
},
listDir: async (payload) => {
try {
const { realPath: real } = await resolveSandboxedPath(requirePath(payload), 'read');
const { realPath: real } = await resolveSandboxedPath(
requirePath(payload),
'read',
dependencies.runtimeManager,
);
const fsP = await import('node:fs/promises');
const dirents = await fsP.readdir(real, { withFileTypes: true });
const entries = await Promise.all(dirents.map(async (entry) => {
@@ -973,7 +1004,11 @@ export function createFilesApi(dependencies: FilesApiDependencies = {}): Complet
try {
const body = isRecord(payload) ? payload as PathPayload : {};
const opts = getTreeOptions(body.opts);
const { realPath: real } = await resolveSandboxedPath(requirePath(payload), 'read');
const { realPath: real } = await resolveSandboxedPath(
requirePath(payload),
'read',
dependencies.runtimeManager,
);
const fsP = await import('node:fs/promises');
const stat = await fsP.stat(real);
if (!stat.isDirectory()) return { ok: false, error: 'notDirectory' };
+26 -21
View File
@@ -1,17 +1,17 @@
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';
import { logger } from '../utils/logger';
import { buildOpenClawControlUiUrl } from '../utils/openclaw-control-ui';
import { getSetting } from '../utils/store';
import type { RuntimeManager } from '../runtime/manager';
import { isRecord } from './payload-utils';
type HealthPayload = {
probe?: unknown;
};
type ControlUiPayload = {
view?: unknown;
};
type RpcPayload = {
method?: unknown;
params?: unknown;
@@ -27,36 +27,41 @@ function parseTimeoutMs(timeoutMs: unknown): number | undefined {
}
export function createGatewayApi(
gatewayManager: GatewayManager,
runtimeManager: RuntimeManager,
gatewayRpcBackpressure: GatewayRpcBackpressure,
gatewayManager?: GatewayManager,
): CompleteHostServiceRegistry['gateway'] {
return {
status: () => gatewayManager.getStatus(),
status: () => runtimeManager.getStatus(),
start: async () => {
await gatewayManager.start();
await runtimeManager.start();
return { success: true };
},
stop: async () => {
await gatewayManager.stop();
await runtimeManager.stop();
return { success: true };
},
restart: async () => {
await gatewayManager.restart();
await runtimeManager.restart();
return { success: true };
},
health: async (payload) => {
const body = isRecord(payload) ? payload as HealthPayload : {};
return gatewayManager.checkHealth({ probe: body.probe === true });
return runtimeManager.checkHealth({ probe: body.probe === true });
},
controlUi: async () => {
const status = gatewayManager.getStatus();
const token = await getSetting('gatewayToken');
const port = status.port || PORTS.OPENCLAW_GATEWAY;
const url = buildOpenClawControlUiUrl(port, token);
void approvePendingLocalDeviceRequests(gatewayManager).catch((error) => {
logger.debug(`[gateway] Control UI device auto-approve skipped: ${String(error)}`);
});
return { success: true, url, token, port };
controlUi: async (payload) => {
const status = runtimeManager.getStatus();
const body = isRecord(payload) ? payload as ControlUiPayload : {};
const view = body.view === 'dreams' ? 'dreams' : undefined;
const provider = runtimeManager.getActiveProvider();
if (!status.capabilities?.controlUi || !provider.getControlUi) {
return {
success: false,
error: `${status.runtimeKind ?? 'runtime'} runtime does not support Control UI`,
};
}
void gatewayManager;
return provider.getControlUi(view ? { view } : {});
},
rpc: async (payload) => {
const body = isRecord(payload) ? payload as RpcPayload : {};
@@ -69,7 +74,7 @@ export function createGatewayApi(
method,
body.params,
timeoutMs,
(rpcMethod, rpcParams, rpcTimeoutMs) => gatewayManager.rpc(rpcMethod, rpcParams, rpcTimeoutMs),
(rpcMethod, rpcParams, rpcTimeoutMs) => runtimeManager.rpc(rpcMethod, rpcParams, rpcTimeoutMs),
);
},
};
+35 -1
View File
@@ -2,9 +2,11 @@ import { dialog, nativeImage } from 'electron';
import { homedir } from 'node:os';
import { join } from 'node:path';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import type { RuntimeManager } from '../runtime/manager';
import type { AttachmentFileRef } from '@shared/host-api/contract';
import { resolveOutgoingMediaAttachment, type AttachmentAccess } from './attachment-access';
import { resolveOpenClawStateDir } from '../utils/paths';
import { getRuntimeOutgoingMediaRecordDirs } from '../utils/runtime-media-paths';
import {
CLAWX_OPENAI_IMAGE_DEFAULT_MODEL,
CLAWX_OPENAI_IMAGE_PROVIDER_KEY,
@@ -28,6 +30,7 @@ type ThumbnailEntry = {
};
type MediaApiDependencies = {
runtimeManager?: Pick<RuntimeManager, 'getStatus'>;
attachmentAccess?: Pick<AttachmentAccess, 'resolveAttachment' | 'readAttachmentBinary'>;
};
@@ -99,6 +102,37 @@ function normalizeThumbnailEntries(payload: unknown): ThumbnailEntry[] {
return Array.isArray(value) ? value as ThumbnailEntry[] : [];
}
async function resolveRuntimeOutgoingMediaUrl(
gatewayUrl: string,
runtimeManager?: Pick<RuntimeManager, 'getStatus'>,
): Promise<{ path: string; mimeType: string } | null> {
try {
const match = gatewayUrl.match(/\/api\/chat\/media\/outgoing\/[^/]+\/([^/]+)\//);
if (!match) return null;
const attachmentId = decodeURIComponent(match[1]);
if (!/^[A-Za-z0-9._-]+$/.test(attachmentId)) return null;
const fsP = await import('node:fs/promises');
for (const recordDir of getRuntimeOutgoingMediaRecordDirs(runtimeManager)) {
try {
const raw = await fsP.readFile(join(recordDir, `${attachmentId}.json`), 'utf8');
const record = JSON.parse(raw) as {
original?: { path?: string; contentType?: string };
};
if (!record.original?.path) continue;
return {
path: record.original.path,
mimeType: record.original.contentType || 'application/octet-stream',
};
} catch {
// Continue across current and historical runtime media roots.
}
}
} catch {
// Treat malformed or unavailable runtime media records as missing.
}
return null;
}
export function createMediaApi(dependencies: MediaApiDependencies = {}): CompleteHostServiceRegistry['media'] {
return {
thumbnails: async (payload) => {
@@ -157,7 +191,7 @@ export function createMediaApi(dependencies: MediaApiDependencies = {}): Complet
const resolved = await resolveOutgoingMediaAttachment({
uri: entry.gatewayUrl,
stateDir: resolveOpenClawStateDir(),
});
}) ?? await resolveRuntimeOutgoingMediaUrl(entry.gatewayUrl, dependencies.runtimeManager);
if (!resolved) {
results[entry.gatewayUrl] = { preview: null, fileSize: 0 };
continue;
+201 -42
View File
@@ -2,6 +2,7 @@ import type { BrowserWindow } from 'electron';
import type { HostApiContract } from '@shared/host-api/contract';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import type { GatewayManager } from '../gateway/manager';
import type { RuntimeManager } from '../runtime/manager';
import type { ProviderConfig } from '../utils/secure-storage';
import { browserOAuthManager, type BrowserOAuthProviderType } from '../utils/browser-oauth';
import { deviceOAuthManager, type OAuthProviderType } from '../utils/device-oauth';
@@ -22,9 +23,15 @@ import {
import { validateApiKeyWithProvider } from './providers/provider-validation';
import type { ProviderAccount } from '../shared/providers/types';
import { isRecord } from './payload-utils';
import {
getCcConnectCodexOAuthStatus,
importUserCodexOAuthToManagedHome,
logoutCcConnectCodexOAuth,
} from '../runtime/cc-connect-provider-profile';
type ProvidersApiContext = {
gatewayManager: GatewayManager;
runtimeManager?: RuntimeManager;
mainWindow: BrowserWindow;
};
@@ -34,7 +41,6 @@ type ProviderPayload<Action extends keyof HostApiContract['providers']> =
type ValidationOptions = {
baseUrl?: string;
apiProtocol?: string;
modelId?: string;
};
function hasObjectChanges<T extends Record<string, unknown>>(
@@ -151,6 +157,96 @@ function getSavePayload(payload: unknown): { config: ProviderConfig; apiKey?: st
};
}
async function syncActiveRuntimeProviderProfile(
ctx: Pick<ProvidersApiContext, 'runtimeManager'>,
payload: { providerId?: string; reason: string },
): Promise<boolean> {
const provider = ctx.runtimeManager?.getActiveProvider();
if (!provider?.syncProviderProfile) return false;
await provider.syncProviderProfile(payload);
return true;
}
async function syncProviderApiKeyToActiveRuntime(
providerType: string,
providerId: string,
apiKey: string,
ctx: Pick<ProvidersApiContext, 'runtimeManager'>,
): Promise<void> {
if (await syncActiveRuntimeProviderProfile(ctx, { providerId, reason: 'api-key' })) {
return;
}
await syncProviderApiKeyToRuntime(providerType, providerId, apiKey);
}
async function syncSavedProviderToActiveRuntime(
config: ProviderConfig,
apiKey: string | undefined,
ctx: Pick<ProvidersApiContext, 'gatewayManager' | 'runtimeManager'>,
): Promise<void> {
if (await syncActiveRuntimeProviderProfile(ctx, { providerId: config.id, reason: 'save' })) {
return;
}
await syncSavedProviderToRuntime(config, apiKey, ctx.gatewayManager);
}
async function syncUpdatedProviderToActiveRuntime(
config: ProviderConfig,
apiKey: string | undefined,
ctx: Pick<ProvidersApiContext, 'gatewayManager' | 'runtimeManager'>,
reason = 'update',
): Promise<void> {
if (await syncActiveRuntimeProviderProfile(ctx, { providerId: config.id, reason })) {
return;
}
await syncUpdatedProviderToRuntime(config, apiKey, ctx.gatewayManager);
}
async function syncDeletedProviderToActiveRuntime(
provider: ProviderConfig | null,
providerId: string,
ctx: Pick<ProvidersApiContext, 'gatewayManager' | 'runtimeManager'>,
runtimeProviderKey?: string,
): Promise<void> {
if (await syncActiveRuntimeProviderProfile(ctx, { providerId, reason: 'delete' })) {
return;
}
await syncDeletedProviderToRuntime(provider, providerId, ctx.gatewayManager, runtimeProviderKey);
}
async function syncDeletedProviderApiKeyToActiveRuntime(
provider: ProviderConfig | null,
providerId: string,
ctx: Pick<ProvidersApiContext, 'runtimeManager'>,
runtimeProviderKey?: string,
): Promise<void> {
if (await syncActiveRuntimeProviderProfile(ctx, { providerId, reason: 'delete-api-key' })) {
return;
}
await syncDeletedProviderApiKeyToRuntime(provider, providerId, runtimeProviderKey);
}
async function syncDefaultProviderToActiveRuntime(
providerId: string,
ctx: Pick<ProvidersApiContext, 'gatewayManager' | 'runtimeManager'>,
): Promise<void> {
if (await syncActiveRuntimeProviderProfile(ctx, { providerId, reason: 'set-default' })) {
return;
}
await syncDefaultProviderToRuntime(providerId, ctx.gatewayManager);
}
async function removeProviderFromActiveRuntime(
providerKey: string,
ctx: Pick<ProvidersApiContext, 'runtimeManager'>,
providerId: string,
): Promise<void> {
if (await syncActiveRuntimeProviderProfile(ctx, { providerId, reason: 'remove-provider' })) {
return;
}
await removeProviderFromOpenClaw(providerKey);
}
async function validateKey(payload: ProviderPayload<'validateKey'>): Promise<{ valid: boolean; error?: string }> {
try {
const body = getPayloadRecord(payload, 'validateKey');
@@ -181,18 +277,16 @@ 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) };
}
}
async function saveProvider(payload: ProviderPayload<'save'>, gatewayManager?: GatewayManager) {
async function saveProvider(payload: ProviderPayload<'save'>, ctx: ProvidersApiContext) {
const providerService = getProviderService();
const { config, apiKey } = getSavePayload(payload);
try {
@@ -201,44 +295,44 @@ async function saveProvider(payload: ProviderPayload<'save'>, gatewayManager?: G
const trimmedKey = apiKey.trim();
if (trimmedKey) {
await providerService._setProviderApiKeyInternal(config.id, trimmedKey);
await syncProviderApiKeyToRuntime(config.type, config.id, trimmedKey);
await syncProviderApiKeyToActiveRuntime(config.type, config.id, trimmedKey, ctx);
}
}
await syncSavedProviderToRuntime(config, apiKey, gatewayManager);
await syncSavedProviderToActiveRuntime(config, apiKey, ctx);
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
}
}
async function deleteProvider(payload: ProviderPayload<'delete'>, gatewayManager?: GatewayManager) {
async function deleteProvider(payload: ProviderPayload<'delete'>, ctx: ProvidersApiContext) {
const providerService = getProviderService();
const providerId = getProviderId(payload, 'delete');
try {
const existing = await providerService._getProviderInternal(providerId);
await providerService._deleteProviderInternal(providerId);
await syncDeletedProviderToRuntime(existing, providerId, gatewayManager);
await syncDeletedProviderToActiveRuntime(existing, providerId, ctx);
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
}
}
async function setProviderApiKey(payload: ProviderPayload<'setApiKey'>) {
async function setProviderApiKey(payload: ProviderPayload<'setApiKey'>, ctx: ProvidersApiContext) {
const providerService = getProviderService();
const { providerId, apiKey } = getApiKeyPayload(payload, 'setApiKey');
try {
await providerService._setProviderApiKeyInternal(providerId, apiKey);
const provider = await providerService._getProviderInternal(providerId);
const providerType = provider?.type || providerId;
await syncProviderApiKeyToRuntime(providerType, providerId, apiKey);
await syncProviderApiKeyToActiveRuntime(providerType, providerId, apiKey, ctx);
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
}
}
async function updateProviderWithKey(payload: ProviderPayload<'updateWithKey'>, gatewayManager?: GatewayManager) {
async function updateProviderWithKey(payload: ProviderPayload<'updateWithKey'>, ctx: ProvidersApiContext) {
const providerService = getProviderService();
const { providerId, updates, apiKey } = getProviderUpdatePayload(payload);
const existing = await providerService._getProviderInternal(providerId);
@@ -262,24 +356,26 @@ async function updateProviderWithKey(payload: ProviderPayload<'updateWithKey'>,
const trimmedKey = apiKey.trim();
if (trimmedKey) {
await providerService._setProviderApiKeyInternal(providerId, trimmedKey);
await syncProviderApiKeyToRuntime(nextConfig.type, providerId, trimmedKey);
await syncProviderApiKeyToActiveRuntime(nextConfig.type, providerId, trimmedKey, ctx);
} else {
await providerService._deleteProviderApiKeyInternal(providerId);
await removeProviderFromOpenClaw(ock);
await removeProviderFromActiveRuntime(ock, ctx, providerId);
}
}
await syncUpdatedProviderToRuntime(nextConfig, apiKey, gatewayManager);
await syncUpdatedProviderToActiveRuntime(nextConfig, apiKey, ctx);
return { success: true };
} catch (error) {
try {
await providerService._saveProviderInternal(existing);
if (previousKey) {
await providerService._setProviderApiKeyInternal(providerId, previousKey);
await saveProviderKeyToOpenClaw(previousOck, previousKey);
if (!await syncActiveRuntimeProviderProfile(ctx, { providerId, reason: 'rollback' })) {
await saveProviderKeyToOpenClaw(previousOck, previousKey);
}
} else {
await providerService._deleteProviderApiKeyInternal(providerId);
await removeProviderFromOpenClaw(previousOck);
await removeProviderFromActiveRuntime(previousOck, ctx, providerId);
}
} catch (rollbackError) {
logger.warn('Failed to rollback provider updateWithKey:', rollbackError);
@@ -288,32 +384,32 @@ async function updateProviderWithKey(payload: ProviderPayload<'updateWithKey'>,
}
}
async function deleteProviderApiKey(payload: ProviderPayload<'deleteApiKey'>) {
async function deleteProviderApiKey(payload: ProviderPayload<'deleteApiKey'>, ctx: ProvidersApiContext) {
const providerService = getProviderService();
const providerId = getProviderId(payload, 'deleteApiKey');
try {
await providerService._deleteProviderApiKeyInternal(providerId);
const provider = await providerService._getProviderInternal(providerId);
await syncDeletedProviderApiKeyToRuntime(provider, providerId);
await syncDeletedProviderApiKeyToActiveRuntime(provider, providerId, ctx);
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
}
}
async function setDefaultProvider(payload: ProviderPayload<'setDefault'>, gatewayManager?: GatewayManager) {
async function setDefaultProvider(payload: ProviderPayload<'setDefault'>, ctx: ProvidersApiContext) {
const providerService = getProviderService();
const providerId = getProviderId(payload, 'setDefault');
try {
await providerService._setDefaultProviderInternal(providerId);
await syncDefaultProviderToRuntime(providerId, gatewayManager);
await syncDefaultProviderToActiveRuntime(providerId, ctx);
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
}
}
async function createAccount(payload: ProviderPayload<'createAccount'>, gatewayManager?: GatewayManager) {
async function createAccount(payload: ProviderPayload<'createAccount'>, ctx: ProvidersApiContext) {
const providerService = getProviderService();
const body = getPayloadRecord(payload, 'createAccount');
if (!isRecord(body.account)) {
@@ -322,14 +418,14 @@ async function createAccount(payload: ProviderPayload<'createAccount'>, gatewayM
const apiKey = typeof body.apiKey === 'string' ? body.apiKey : undefined;
try {
const account = await providerService.createAccount(body.account as unknown as ProviderAccount, apiKey);
await syncSavedProviderToRuntime(providerAccountToConfig(account), apiKey, gatewayManager);
await syncSavedProviderToActiveRuntime(providerAccountToConfig(account), apiKey, ctx);
return { success: true, account };
} catch (error) {
return { success: false, error: String(error) };
}
}
async function updateAccount(payload: ProviderPayload<'updateAccount'>, gatewayManager?: GatewayManager) {
async function updateAccount(payload: ProviderPayload<'updateAccount'>, ctx: ProvidersApiContext) {
const providerService = getProviderService();
const body = getPayloadRecord(payload, 'updateAccount');
const accountId = typeof body.accountId === 'string' ? body.accountId.trim() : '';
@@ -348,7 +444,7 @@ async function updateAccount(payload: ProviderPayload<'updateAccount'>, gatewayM
return { success: true, noChange: true, account: existing };
}
const account = await providerService.updateAccount(accountId, updates, apiKey);
await syncUpdatedProviderToRuntime(providerAccountToConfig(account), apiKey, gatewayManager);
await syncUpdatedProviderToActiveRuntime(providerAccountToConfig(account), apiKey, ctx);
return { success: true, account };
} catch (error) {
return { success: false, error: String(error) };
@@ -357,7 +453,7 @@ async function updateAccount(payload: ProviderPayload<'updateAccount'>, gatewayM
async function deleteAccount(
payload: ProviderPayload<'deleteAccount'> & { apiKeyOnly?: boolean },
gatewayManager?: GatewayManager,
ctx: ProvidersApiContext,
) {
const providerService = getProviderService();
const body = getPayloadRecord(payload, 'deleteAccount');
@@ -373,9 +469,10 @@ async function deleteAccount(
: undefined;
if (apiKeyOnly) {
await providerService._deleteProviderApiKeyInternal(accountId);
await syncDeletedProviderApiKeyToRuntime(
await syncDeletedProviderApiKeyToActiveRuntime(
existing ? providerAccountToConfig(existing) : null,
accountId,
ctx,
runtimeProviderKey,
);
return { success: true };
@@ -388,12 +485,12 @@ async function deleteAccount(
await providerService.deleteAccount(accountId);
if (replacementDefault) {
await providerService.setDefaultAccount(replacementDefault.id);
await syncDefaultProviderToRuntime(replacementDefault.id);
await syncDefaultProviderToActiveRuntime(replacementDefault.id, ctx);
}
await syncDeletedProviderToRuntime(
await syncDeletedProviderToActiveRuntime(
existing ? providerAccountToConfig(existing) : null,
accountId,
gatewayManager,
ctx,
runtimeProviderKey,
);
return { success: true };
@@ -402,7 +499,7 @@ async function deleteAccount(
}
}
async function setDefaultAccount(payload: ProviderPayload<'setDefaultAccount'>, gatewayManager?: GatewayManager) {
async function setDefaultAccount(payload: ProviderPayload<'setDefaultAccount'>, ctx: ProvidersApiContext) {
const providerService = getProviderService();
const accountId = getAccountId(payload, 'setDefaultAccount');
try {
@@ -411,7 +508,7 @@ async function setDefaultAccount(payload: ProviderPayload<'setDefaultAccount'>,
return { success: true, noChange: true };
}
await providerService.setDefaultAccount(accountId);
await syncDefaultProviderToRuntime(accountId, gatewayManager);
await syncDefaultProviderToActiveRuntime(accountId, ctx);
return { success: true };
} catch (error) {
return { success: false, error: String(error) };
@@ -467,10 +564,69 @@ async function submitOAuth(payload: ProviderPayload<'submitOAuth'>) {
}
}
async function codexOAuthStatus(payload?: ProviderPayload<'codexOAuthStatus'>) {
try {
const accountId = payloadString(payload, 'accountId');
return await getCcConnectCodexOAuthStatus({ accountId });
} catch (error) {
logger.error('providers.codexOAuthStatus failed', error);
return { success: false, error: String(error) };
}
}
async function importCodexOAuth(
payload: ProviderPayload<'importCodexOAuth'> | undefined,
ctx: Pick<ProvidersApiContext, 'runtimeManager'>,
) {
try {
const accountId = payloadString(payload, 'accountId');
const result = await importUserCodexOAuthToManagedHome({ accountId });
await syncActiveRuntimeProviderProfile(ctx, {
providerId: result.provider?.accountId ?? accountId,
reason: 'codex-oauth-import',
});
return result;
} catch (error) {
logger.error('providers.importCodexOAuth failed', error);
return { success: false, error: String(error) };
}
}
async function logoutCodexOAuth(
payload: ProviderPayload<'logoutCodexOAuth'> | undefined,
ctx: Pick<ProvidersApiContext, 'runtimeManager'>,
) {
try {
const accountId = payloadString(payload, 'accountId');
const managedOnly = isRecord(payload) && payload.managedOnly === true;
const result = await logoutCcConnectCodexOAuth({ accountId, managedOnly });
await syncActiveRuntimeProviderProfile(ctx, {
providerId: result.provider?.accountId ?? accountId,
reason: 'codex-oauth-logout',
});
return result;
} catch (error) {
logger.error('providers.logoutCodexOAuth failed', error);
return { success: false, error: String(error) };
}
}
export function createProvidersApi(ctx: ProvidersApiContext): CompleteHostServiceRegistry['providers'] {
const providerService = getProviderService();
deviceOAuthManager.setWindow(ctx.mainWindow);
browserOAuthManager.setWindow(ctx.mainWindow);
browserOAuthManager.setSuccessHandler(async ({ accountId }) => {
const account = await providerService.getAccount(accountId);
if (!account) {
throw new Error(`Provider account not found after OAuth success: ${accountId}`);
}
await syncUpdatedProviderToActiveRuntime(
providerAccountToConfig(account),
undefined,
ctx,
'oauth',
);
});
return {
list: async () => providerService._listProvidersWithKeyInfoInternal(),
@@ -479,12 +635,12 @@ export function createProvidersApi(ctx: ProvidersApiContext): CompleteHostServic
hasApiKey: async (payload) => providerService._hasProviderApiKeyInternal(getProviderId(payload, 'hasApiKey')),
getApiKey: async (payload) => providerService._getProviderApiKeyInternal(getProviderId(payload, 'getApiKey')),
validateKey,
save: async (payload) => saveProvider(payload, ctx.gatewayManager),
delete: async (payload) => deleteProvider(payload, ctx.gatewayManager),
setApiKey: setProviderApiKey,
updateWithKey: async (payload) => updateProviderWithKey(payload, ctx.gatewayManager),
deleteApiKey: deleteProviderApiKey,
setDefault: async (payload) => setDefaultProvider(payload, ctx.gatewayManager),
save: async (payload) => saveProvider(payload, ctx),
delete: async (payload) => deleteProvider(payload, ctx),
setApiKey: async (payload) => setProviderApiKey(payload, ctx),
updateWithKey: async (payload) => updateProviderWithKey(payload, ctx),
deleteApiKey: async (payload) => deleteProviderApiKey(payload, ctx),
setDefault: async (payload) => setDefaultProvider(payload, ctx),
accounts: async () => providerService.listAccounts(),
vendors: async () => providerService.listVendors(),
accountKeyInfo: async () => providerService.listAccountsKeyInfo(),
@@ -492,13 +648,16 @@ export function createProvidersApi(ctx: ProvidersApiContext): CompleteHostServic
getAccount: async (payload) => providerService.getAccount(getAccountId(payload, 'getAccount')),
getAccountApiKey: async (payload) => providerService.getAccountApiKey(getAccountId(payload, 'getAccountApiKey')),
hasAccountApiKey: async (payload) => providerService.hasAccountApiKey(getAccountId(payload, 'hasAccountApiKey')),
createAccount: async (payload) => createAccount(payload, ctx.gatewayManager),
updateAccount: async (payload) => updateAccount(payload, ctx.gatewayManager),
deleteAccount: async (payload) => deleteAccount(payload, ctx.gatewayManager),
deleteAccountApiKey: async (payload) => deleteAccount({ accountId: getAccountId(payload, 'deleteAccountApiKey'), apiKeyOnly: true }, ctx.gatewayManager),
setDefaultAccount: async (payload) => setDefaultAccount(payload, ctx.gatewayManager),
createAccount: async (payload) => createAccount(payload, ctx),
updateAccount: async (payload) => updateAccount(payload, ctx),
deleteAccount: async (payload) => deleteAccount(payload, ctx),
deleteAccountApiKey: async (payload) => deleteAccount({ accountId: getAccountId(payload, 'deleteAccountApiKey'), apiKeyOnly: true }, ctx),
setDefaultAccount: async (payload) => setDefaultAccount(payload, ctx),
requestOAuth,
cancelOAuth,
submitOAuth,
codexOAuthStatus,
importCodexOAuth: async (payload) => importCodexOAuth(payload, ctx),
logoutCodexOAuth: async (payload) => logoutCodexOAuth(payload, ctx),
};
}
@@ -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.6-sol`;
const OPENAI_OAUTH_DEFAULT_MODEL_REF = `${OPENAI_OAUTH_RUNTIME_PROVIDER}/gpt-5.5`;
/**
* Provider types that are not in the built-in provider registry (no `providerConfig.api`).
@@ -196,7 +196,6 @@ async function validateOpenAiCompatibleKey(
apiKey: string,
apiProtocol: 'openai-completions' | 'openai-responses',
baseUrl?: string,
modelId?: string,
): Promise<ValidationResult> {
const trimmedBaseUrl = baseUrl?.trim();
if (!trimmedBaseUrl) {
@@ -204,7 +203,6 @@ 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);
@@ -213,9 +211,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, probeModel);
return await performResponsesProbe(providerType, probeUrl, headers);
}
return await performChatCompletionsProbe(providerType, probeUrl, headers, probeModel);
return await performChatCompletionsProbe(providerType, probeUrl, headers);
}
return modelsResult;
@@ -225,7 +223,6 @@ async function performResponsesProbe(
providerLabel: string,
url: string,
headers: Record<string, string>,
modelId: string,
): Promise<ValidationResult> {
try {
logValidationRequest(providerLabel, 'POST', url, headers);
@@ -233,7 +230,7 @@ async function performResponsesProbe(
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({
model: modelId,
model: 'validation-probe',
input: 'hi',
}),
});
@@ -252,7 +249,6 @@ async function performChatCompletionsProbe(
providerLabel: string,
url: string,
headers: Record<string, string>,
modelId: string,
): Promise<ValidationResult> {
try {
logValidationRequest(providerLabel, 'POST', url, headers);
@@ -260,7 +256,7 @@ async function performChatCompletionsProbe(
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({
model: modelId,
model: 'validation-probe',
messages: [{ role: 'user', content: 'hi' }],
max_tokens: 1,
}),
@@ -357,7 +353,7 @@ async function validateOpenRouterKey(
export async function validateApiKeyWithProvider(
providerType: string,
apiKey: string,
options?: { baseUrl?: string; apiProtocol?: string; modelId?: string },
options?: { baseUrl?: string; apiProtocol?: string },
): Promise<ValidationResult> {
const profile = getValidationProfile(providerType, options);
const resolvedBaseUrl = options?.baseUrl || getProviderConfig(providerType)?.baseUrl;
@@ -379,7 +375,6 @@ export async function validateApiKeyWithProvider(
trimmedKey,
'openai-completions',
resolvedBaseUrl,
options?.modelId,
);
case 'openai-responses':
return await validateOpenAiCompatibleKey(
@@ -387,7 +382,6 @@ export async function validateApiKeyWithProvider(
trimmedKey,
'openai-responses',
resolvedBaseUrl,
options?.modelId,
);
case 'google-query-key':
return await validateGoogleQueryKey(providerType, trimmedKey, resolvedBaseUrl);
@@ -1,3 +1,6 @@
import { app } from 'electron';
import { getClawXDataLayout, resolveClawXDataRoot } from '../../utils/clawx-data-layout';
// Lazy-load electron-store (ESM module) from the main process only.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let providerStore: any = null;
@@ -7,6 +10,7 @@ export async function getClawXProviderStore() {
const Store = (await import('electron-store')).default;
providerStore = new Store({
name: 'clawx-providers',
cwd: getClawXDataLayout(resolveClawXDataRoot(process.env, app.getPath('userData'))).appDir,
defaults: {
schemaVersion: 0,
providers: {} as Record<string, unknown>,
@@ -0,0 +1,177 @@
import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from 'node:crypto';
import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { app, safeStorage } from 'electron';
import type { ProviderSecret } from '../../shared/providers/types';
import { getClawXDataLayout, resolveClawXDataRoot } from '../../utils/clawx-data-layout';
const VAULT_SCHEMA = 'clawx-credential-vault';
const VAULT_VERSION = 1;
let credentialMutationQueue: Promise<void> = Promise.resolve();
type CredentialVaultDocument = {
schema: typeof VAULT_SCHEMA;
version: typeof VAULT_VERSION;
secrets: Record<string, ProviderSecret>;
channelSecrets: Record<string, Record<string, string>>;
};
export interface CredentialCipher {
isEncryptionAvailable(): boolean;
encryptString(value: string): Buffer;
decryptString(value: Buffer): string;
}
function credentialPaths() {
const layout = getClawXDataLayout(resolveClawXDataRoot(process.env, app.getPath('userData')));
return {
vaultPath: join(layout.credentialsDir, 'secrets.enc'),
indexPath: join(layout.credentialsDir, 'index.json'),
};
}
function e2eCredentialCipher(secret: string): CredentialCipher {
const key = createHash('sha256').update(secret).digest();
return {
isEncryptionAvailable: () => true,
encryptString: (value) => {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
return Buffer.concat([iv, cipher.getAuthTag(), encrypted]);
},
decryptString: (value) => {
const iv = value.subarray(0, 12);
const authTag = value.subarray(12, 28);
const encrypted = value.subarray(28);
const decipher = createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8');
},
};
}
function defaultCredentialCipher(): CredentialCipher {
const e2eKey = process.env.CLAWX_E2E_CREDENTIAL_KEY?.trim();
if (process.env.CLAWX_E2E === '1' && e2eKey) return e2eCredentialCipher(e2eKey);
return safeStorage;
}
function emptyVault(): CredentialVaultDocument {
return { schema: VAULT_SCHEMA, version: VAULT_VERSION, secrets: {}, channelSecrets: {} };
}
async function writeAtomic(path: string, content: string | Buffer, mode = 0o600): Promise<void> {
await mkdir(dirname(path), { recursive: true });
const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
await writeFile(temporaryPath, content, { mode });
await chmod(temporaryPath, mode).catch(() => {});
await rename(temporaryPath, path);
await chmod(path, mode).catch(() => {});
}
function serializeCredentialMutation<T>(mutation: () => Promise<T>): Promise<T> {
const result = credentialMutationQueue.then(mutation, mutation);
credentialMutationQueue = result.then(() => undefined, () => undefined);
return result;
}
export async function readCredentialVault(
cipher: CredentialCipher = defaultCredentialCipher(),
): Promise<CredentialVaultDocument> {
const { vaultPath } = credentialPaths();
let encrypted: Buffer;
try {
encrypted = await readFile(vaultPath);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return emptyVault();
throw error;
}
if (!cipher.isEncryptionAvailable()) {
throw new Error('OS credential encryption is unavailable; refusing to read ClawX provider secrets');
}
const parsed = JSON.parse(cipher.decryptString(encrypted)) as Partial<CredentialVaultDocument>;
if (parsed.schema !== VAULT_SCHEMA || parsed.version !== VAULT_VERSION || !parsed.secrets) {
throw new Error('Unsupported or invalid ClawX credential vault');
}
return {
...(parsed as CredentialVaultDocument),
channelSecrets: parsed.channelSecrets ?? {},
};
}
export async function writeCredentialVault(
document: CredentialVaultDocument,
cipher: CredentialCipher = defaultCredentialCipher(),
): Promise<void> {
if (!cipher.isEncryptionAvailable()) {
throw new Error('OS credential encryption is unavailable; refusing to persist provider secrets');
}
const { vaultPath, indexPath } = credentialPaths();
const encrypted = cipher.encryptString(JSON.stringify(document));
await writeAtomic(vaultPath, encrypted);
await writeAtomic(indexPath, `${JSON.stringify({
schema: 'clawx-credential-index',
version: 1,
accountIds: Object.keys(document.secrets).sort(),
channelCredentialIds: Object.keys(document.channelSecrets).sort(),
updatedAt: new Date().toISOString(),
}, null, 2)}\n`);
}
export async function getVaultSecret(
accountId: string,
cipher: CredentialCipher = defaultCredentialCipher(),
): Promise<ProviderSecret | null> {
return (await readCredentialVault(cipher)).secrets[accountId] ?? null;
}
export async function setVaultSecret(
secret: ProviderSecret,
cipher: CredentialCipher = defaultCredentialCipher(),
): Promise<void> {
await serializeCredentialMutation(async () => {
const document = await readCredentialVault(cipher);
document.secrets[secret.accountId] = secret;
await writeCredentialVault(document, cipher);
});
}
export async function deleteVaultSecret(
accountId: string,
cipher: CredentialCipher = defaultCredentialCipher(),
): Promise<void> {
await serializeCredentialMutation(async () => {
const document = await readCredentialVault(cipher);
if (!(accountId in document.secrets)) return;
delete document.secrets[accountId];
if (Object.keys(document.secrets).length === 0 && Object.keys(document.channelSecrets).length === 0) {
const { vaultPath, indexPath } = credentialPaths();
await Promise.all([rm(vaultPath, { force: true }), rm(indexPath, { force: true })]);
return;
}
await writeCredentialVault(document, cipher);
});
}
export async function getChannelVaultSecrets(
cipher: CredentialCipher = defaultCredentialCipher(),
): Promise<Record<string, Record<string, string>>> {
return (await readCredentialVault(cipher)).channelSecrets;
}
export async function replaceChannelVaultSecrets(
channelSecrets: Record<string, Record<string, string>>,
cipher: CredentialCipher = defaultCredentialCipher(),
): Promise<void> {
await serializeCredentialMutation(async () => {
const document = await readCredentialVault(cipher);
document.channelSecrets = channelSecrets;
if (Object.keys(document.secrets).length === 0 && Object.keys(channelSecrets).length === 0) {
const { vaultPath, indexPath } = credentialPaths();
await Promise.all([rm(vaultPath, { force: true }), rm(indexPath, { force: true })]);
return;
}
await writeCredentialVault(document, cipher);
});
}
+45 -19
View File
@@ -1,5 +1,6 @@
import type { ProviderSecret } from '../../shared/providers/types';
import { getClawXProviderStore } from '../providers/store-instance';
import { deleteVaultSecret, getVaultSecret, setVaultSecret } from './credential-vault';
export interface SecretStore {
get(accountId: string): Promise<ProviderSecret | null>;
@@ -9,10 +10,19 @@ export interface SecretStore {
export class ElectronStoreSecretStore implements SecretStore {
async get(accountId: string): Promise<ProviderSecret | null> {
const encrypted = await getVaultSecret(accountId);
if (encrypted) {
const store = await getClawXProviderStore();
await this.clearLegacySecret(store, accountId);
return encrypted;
}
const store = await getClawXProviderStore();
const secrets = (store.get('providerSecrets') ?? {}) as Record<string, ProviderSecret>;
const secret = secrets[accountId];
if (secret) {
await setVaultSecret(secret);
await this.clearLegacySecret(store, accountId);
return secret;
}
@@ -22,37 +32,32 @@ export class ElectronStoreSecretStore implements SecretStore {
return null;
}
return {
const migrated: ProviderSecret = {
type: 'api_key',
accountId,
apiKey,
};
await setVaultSecret(migrated);
await this.clearLegacySecret(store, accountId);
return migrated;
}
async set(secret: ProviderSecret): Promise<void> {
await setVaultSecret(secret);
const store = await getClawXProviderStore();
const secrets = (store.get('providerSecrets') ?? {}) as Record<string, ProviderSecret>;
secrets[secret.accountId] = secret;
store.set('providerSecrets', secrets);
// Keep legacy apiKeys in sync until the rest of the app moves to account-based secrets.
const apiKeys = (store.get('apiKeys') ?? {}) as Record<string, string>;
if (secret.type === 'api_key') {
apiKeys[secret.accountId] = secret.apiKey;
} else if (secret.type === 'local') {
if (secret.apiKey) {
apiKeys[secret.accountId] = secret.apiKey;
} else {
delete apiKeys[secret.accountId];
}
} else {
delete apiKeys[secret.accountId];
}
store.set('apiKeys', apiKeys);
await this.clearLegacySecret(store, secret.accountId);
}
async delete(accountId: string): Promise<void> {
await deleteVaultSecret(accountId);
const store = await getClawXProviderStore();
await this.clearLegacySecret(store, accountId);
}
private async clearLegacySecret(store: {
get(key: string): unknown;
set(key: string, value: unknown): void;
}, accountId: string): Promise<void> {
const secrets = (store.get('providerSecrets') ?? {}) as Record<string, ProviderSecret>;
delete secrets[accountId];
store.set('providerSecrets', secrets);
@@ -63,6 +68,27 @@ export class ElectronStoreSecretStore implements SecretStore {
}
}
export async function migrateLegacyProviderSecretsToVault(): Promise<number> {
const store = await getClawXProviderStore();
const legacySecrets = (store.get('providerSecrets') ?? {}) as Record<string, ProviderSecret>;
const legacyApiKeys = (store.get('apiKeys') ?? {}) as Record<string, string>;
const accountIds = new Set([...Object.keys(legacyApiKeys), ...Object.keys(legacySecrets)]);
if (accountIds.size === 0) return 0;
for (const accountId of accountIds) {
const existing = await getVaultSecret(accountId);
if (existing) continue;
const secret = legacySecrets[accountId] ?? (legacyApiKeys[accountId]
? { type: 'api_key' as const, accountId, apiKey: legacyApiKeys[accountId] }
: undefined);
if (secret) await setVaultSecret(secret);
}
store.set('providerSecrets', {});
store.set('apiKeys', {});
return accountIds.size;
}
const secretStore = new ElectronStoreSecretStore();
export function getSecretStore(): SecretStore {
+22 -3
View File
@@ -2,6 +2,7 @@ import { openSync, closeSync, fstatSync, readSync } from 'node:fs';
import { access } from 'node:fs/promises';
import { join } from 'node:path';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import type { RuntimeManager } from '../runtime/manager';
import { stripAcpWorkingDirectoryPrefix } from '@shared/chat/session-title';
import { isOpenClawHeartbeatPollText } from '@shared/chat/openclaw-internal';
import type { RawMessage } from '@shared/chat/types';
@@ -473,7 +474,7 @@ async function loadSessionSummary(sessionKey: string, workspacePath: string | nu
}
}
export async function loadSessionTranscriptByKey(sessionKey: string, limit: number): Promise<RawMessage[] | null> {
async function loadSessionTranscriptByKey(sessionKey: string, limit: number): Promise<RawMessage[] | null> {
const parsed = parseSessionKey(sessionKey);
if (!parsed) return null;
@@ -621,9 +622,15 @@ async function renameSession(sessionKey: string, label: string): Promise<{ succe
return { success: true };
}
export function createSessionsApi(): CompleteHostServiceRegistry['sessions'] {
export function createSessionsApi(runtimeManager?: RuntimeManager): CompleteHostServiceRegistry['sessions'] {
return {
delete: async (payload) => deleteSession(getSessionKey(payload)),
delete: async (payload) => {
const provider = runtimeManager?.getActiveProvider();
if (provider?.listCapabilities().sessions) {
return provider.deleteSession(payload);
}
return deleteSession(getSessionKey(payload));
},
rename: async (payload) => {
const body = isRecord(payload) ? payload as SessionPayload : {};
const sessionKey = getSessionKey(payload);
@@ -631,9 +638,17 @@ export function createSessionsApi(): CompleteHostServiceRegistry['sessions'] {
if (typeof label !== 'string') {
throw new Error('Label cannot be empty');
}
const provider = runtimeManager?.getActiveProvider();
if (provider?.listCapabilities().sessions) {
return provider.rpc('sessions.rename', { sessionKey, label }) as Promise<{ success: boolean; error?: string }>;
}
return renameSession(sessionKey, label);
},
summaries: async (payload) => {
const provider = runtimeManager?.getActiveProvider();
if (provider?.listCapabilities().sessions) {
return provider.listSessions(payload) as ReturnType<CompleteHostServiceRegistry['sessions']['summaries']>;
}
const body = isRecord(payload) ? payload as SessionPayload : {};
const sessionKeys = Array.isArray(body.sessionKeys)
? body.sessionKeys.filter((value): value is string => typeof value === 'string' && value.startsWith('agent:'))
@@ -648,6 +663,10 @@ export function createSessionsApi(): CompleteHostServiceRegistry['sessions'] {
};
},
history: async (payload) => {
const provider = runtimeManager?.getActiveProvider();
if (provider?.listCapabilities().history) {
return provider.loadHistory(payload) as ReturnType<CompleteHostServiceRegistry['sessions']['history']>;
}
const body = isRecord(payload) ? payload as SessionPayload : {};
const limit = getLimit(payload);
+12 -3
View File
@@ -1,5 +1,7 @@
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import type { GatewayManager } from '../gateway/manager';
import type { RuntimeManager } from '../runtime/manager';
import type { RuntimeKind } from '@shared/types/gateway';
import { syncLaunchAtStartupSettingFromStore } from '../main/launch-at-startup';
import { createMenu } from '../main/menu';
import { applyProxySettings } from '../main/proxy';
@@ -86,7 +88,11 @@ async function handleProxySettingsChange(gatewayManager: GatewayManager): Promis
async function runSettingsSideEffects(
gatewayManager: GatewayManager,
patch: Partial<AppSettings>,
runtimeManager?: RuntimeManager,
): Promise<void> {
if (typeof patch.runtimeKind === 'string' && runtimeManager) {
await runtimeManager.setActiveKind(patch.runtimeKind as RuntimeKind);
}
if (patchTouchesProxy(patch)) {
await handleProxySettingsChange(gatewayManager);
}
@@ -98,7 +104,10 @@ async function runSettingsSideEffects(
}
}
export function createSettingsApi(gatewayManager: GatewayManager): CompleteHostServiceRegistry['settings'] {
export function createSettingsApi(
gatewayManager: GatewayManager,
runtimeManager?: RuntimeManager,
): CompleteHostServiceRegistry['settings'] {
return {
getAll: () => getAllSettings(),
get: async (payload) => {
@@ -109,7 +118,7 @@ export function createSettingsApi(gatewayManager: GatewayManager): CompleteHostS
const body = payload as SetPayload | undefined;
const key = await requireSettingKey(body);
await setSetting(key as never, body?.value as never);
await runSettingsSideEffects(gatewayManager, { [key]: body?.value } as Partial<AppSettings>);
await runSettingsSideEffects(gatewayManager, { [key]: body?.value } as Partial<AppSettings>, runtimeManager);
return { success: true };
},
setMany: async (payload) => {
@@ -118,7 +127,7 @@ export function createSettingsApi(gatewayManager: GatewayManager): CompleteHostS
for (const [key, value] of entries) {
await setSetting(key, value as never);
}
await runSettingsSideEffects(gatewayManager, patch);
await runSettingsSideEffects(gatewayManager, patch, runtimeManager);
return { success: true };
},
reset: async () => {
+69 -5
View File
@@ -1,7 +1,12 @@
import type { GatewayManager } from '../gateway/manager';
import type { RuntimeManager } from '../runtime/manager';
import type { ClawHubService, ClawHubInstallParams, ClawHubSearchParams, ClawHubUninstallParams } from '../gateway/clawhub';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import { join } from 'node:path';
import { readFile } from 'node:fs/promises';
import { getCcConnectCodexHomeDir, getCcConnectProviderProfilePath } from '../runtime/cc-connect-paths';
import { getAllSkillConfigs, getSkillConfig, updateSkillConfig, updateSkillConfigs } from '../utils/skill-config';
import { getOpenClawSkillsDir } from '../utils/paths';
import {
collectQuickAccessSkills,
filterEnabledQuickAccessSkills,
@@ -86,12 +91,50 @@ function getConfigUpdates(payload: unknown): NormalizedSkillConfigUpdate[] {
export function createSkillsApi({
clawHubService,
gatewayManager,
runtimeManager,
}: {
clawHubService: ClawHubService;
gatewayManager: GatewayManager;
runtimeManager?: RuntimeManager;
}): CompleteHostServiceRegistry['skills'] {
const runtimeSupportsSkills = () => runtimeManager?.listCapabilities().skills === true;
const refreshCcConnectSkills = async () => {
if (runtimeManager?.getActiveProvider().kind === 'cc-connect') {
await runtimeManager.rpc('skills.update', {});
}
};
return {
local: async () => ({ success: true, skills: await listLocalSkills() }),
target: async () => {
const sourceDir = getOpenClawSkillsDir();
const activeKind = await runtimeManager?.getActiveKind();
if (activeKind === 'cc-connect') {
const profile: { codexHomeDir?: unknown } = await readFile(getCcConnectProviderProfilePath(), 'utf8')
.then((content) => JSON.parse(content) as { codexHomeDir?: unknown })
.catch(() => ({} as { codexHomeDir?: unknown }));
const codexHomeDir = typeof profile.codexHomeDir === 'string'
? profile.codexHomeDir
: getCcConnectCodexHomeDir();
const runtimeDir = join(codexHomeDir, 'skills');
return {
success: true,
runtimeKind: 'cc-connect',
sourceDir,
openDir: runtimeDir,
runtimeDir,
manifestPath: join(runtimeDir, 'manifest.json'),
mirrorMode: 'runtime-mirror',
};
}
return {
success: true,
runtimeKind: 'openclaw',
sourceDir,
openDir: sourceDir,
runtimeDir: sourceDir,
mirrorMode: 'source',
};
},
configs: async () => getAllSkillConfigs(),
allConfigs: async () => getAllSkillConfigs(),
getConfig: async (payload) => {
@@ -100,11 +143,23 @@ export function createSkillsApi({
},
updateConfig: async (payload) => {
const { skillKey, ...updates } = getConfigUpdate(payload);
return updateSkillConfig(skillKey, updates);
const result = await updateSkillConfig(skillKey, updates);
await refreshCcConnectSkills();
return result;
},
updateConfigs: async (payload) => {
const result = await updateSkillConfigs(getConfigUpdates(payload));
await refreshCcConnectSkills();
return result;
},
status: async () => {
if (runtimeSupportsSkills()) return await runtimeManager!.rpc('skills.status');
return gatewayManager.rpc('skills.status');
},
update: async (payload) => {
if (runtimeSupportsSkills()) return await runtimeManager!.rpc('skills.update', isRecord(payload) ? payload : {});
return gatewayManager.rpc('skills.update', isRecord(payload) ? payload : {});
},
updateConfigs: async (payload) => updateSkillConfigs(getConfigUpdates(payload)),
status: async () => gatewayManager.rpc('skills.status'),
update: async (payload) => gatewayManager.rpc('skills.update', isRecord(payload) ? payload : {}),
quickAccess: async (payload) => {
const body = isRecord(payload) ? payload as QuickAccessPayload : {};
const [scannedSkills, configs] = await Promise.all([
@@ -114,7 +169,14 @@ export function createSkillsApi({
getAllSkillConfigs(),
]);
let runtimeSkills: QuickAccessRuntimeSkillStatus[] | undefined;
if (gatewayManager.getStatus().state === 'running') {
if (runtimeSupportsSkills()) {
try {
const runtimeStatus = await runtimeManager!.rpc<{ skills?: QuickAccessRuntimeSkillStatus[] }>('skills.status');
runtimeSkills = runtimeStatus.skills || [];
} catch {
runtimeSkills = undefined;
}
} else if (gatewayManager.getStatus().state === 'running') {
try {
const runtimeStatus = await gatewayManager.rpc<{ skills?: QuickAccessRuntimeSkillStatus[] }>('skills.status');
runtimeSkills = runtimeStatus.skills || [];
@@ -151,6 +213,7 @@ export function createSkillsApi({
clawhubInstall: async (payload) => {
try {
await clawHubService.install((isRecord(payload) ? payload : {}) as ClawHubInstallParams);
await refreshCcConnectSkills();
return { success: true };
} catch (error) {
return { success: false, error: errorMessage(error) };
@@ -159,6 +222,7 @@ export function createSkillsApi({
clawhubUninstall: async (payload) => {
try {
await clawHubService.uninstall((isRecord(payload) ? payload : {}) as ClawHubUninstallParams);
await refreshCcConnectSkills();
return { success: true };
} catch (error) {
return { success: false, error: errorMessage(error) };
+44 -3
View File
@@ -1,9 +1,13 @@
import { getRecentTokenUsageHistory } from '../utils/token-usage';
import type { TokenUsageHistoryEntry } from '../utils/token-usage-core';
import type { CompleteHostServiceRegistry } from '../main/ipc/host-contract';
import type { RuntimeManager } from '../runtime/manager';
import type { RuntimeKind } from '@shared/types/gateway';
import { isRecord } from './payload-utils';
import { toTokenUsageHistoryEntry } from '../runtime/usage';
type RecentTokenHistoryPayload = {
limit?: unknown;
runtimeKind?: unknown;
};
function getSafeLimit(payload: unknown): number | undefined {
@@ -20,8 +24,45 @@ function getSafeLimit(payload: unknown): number | undefined {
return undefined;
}
export function createUsageApi(): CompleteHostServiceRegistry['usage'] {
function getExplicitRuntimeKind(payload: unknown): RuntimeKind | undefined {
return isRecord(payload) && (payload.runtimeKind === 'openclaw' || payload.runtimeKind === 'cc-connect')
? payload.runtimeKind
: undefined;
}
function getActiveRuntimeKind(runtimeManager?: RuntimeManager): RuntimeKind | undefined {
return runtimeManager?.getActiveProvider().kind;
}
async function getRuntimeTokenHistory(
limit: number | undefined,
runtimeKind: RuntimeKind,
runtimeManager: RuntimeManager | undefined,
): Promise<TokenUsageHistoryEntry[]> {
const provider = runtimeManager?.getProvider(runtimeKind);
if (!provider) return [];
if (runtimeKind === 'cc-connect' && provider !== runtimeManager?.getActiveProvider()) return [];
const result = await provider.listUsage({ ...(limit !== undefined ? { limit } : {}) });
if (!result.success) return [];
const entries = result.records.map(toTokenUsageHistoryEntry);
entries.sort((left, right) => Date.parse(right.timestamp) - Date.parse(left.timestamp));
return entries.slice(0, limit ?? entries.length);
}
export async function getRecentTokenHistoryForRuntime(
payload?: unknown,
runtimeManager?: RuntimeManager,
) {
const limit = getSafeLimit(payload);
const runtimeKind = getExplicitRuntimeKind(payload) ?? getActiveRuntimeKind(runtimeManager);
if (!runtimeKind) return [];
return getRuntimeTokenHistory(limit, runtimeKind, runtimeManager);
}
export function createUsageApi(runtimeManager?: RuntimeManager): CompleteHostServiceRegistry['usage'] {
return {
recentTokenHistory: async (payload) => getRecentTokenUsageHistory(getSafeLimit(payload)),
recentTokenHistory: async (payload) => {
return getRecentTokenHistoryForRuntime(payload, runtimeManager);
},
};
}
+20 -6
View File
@@ -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 { normalizeWebBrowserHtmlFileUrl } from '../../shared/web-browser';
import { normalizeWebBrowserTopLevelUrl } 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 = normalizeWebBrowserHtmlFileUrl(url);
const normalizedUrl = normalizeWebBrowserTopLevelUrl(url);
if (!normalizedUrl) {
throw new Error('Only local HTML file URLs are allowed');
throw new Error('Web browser URL is not allowed');
}
return normalizedUrl;
}
@@ -34,7 +34,7 @@ function isAbortedLoad(error: unknown): boolean {
export function createWebBrowserApi(
dependencies: WebBrowserApiDependencies,
): CompleteHostServiceRegistry['webBrowser'] {
const { registry } = dependencies;
const { browserSession, registry } = dependencies;
const openExternal = dependencies.openExternal ?? ((url: string) => shell.openExternal(url));
return {
@@ -48,8 +48,22 @@ export function createWebBrowserApi(
}
},
async openExternal({ url }) {
await openExternal(requireAllowedUrl(url));
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()));
},
};
}
+28 -168
View File
@@ -1,190 +1,50 @@
export type ModelInputModality = 'text' | 'image';
type ContextWindowRule = {
/** Human-readable family label; kept so the table reads as documentation. */
label: string;
pattern: RegExp;
contextWindow: number;
};
/**
* Context-window defaults for well-known model families, applied to model rows
* that would otherwise carry no `contextWindow`.
* Conservative context-window defaults for well-known model families, applied
* to custom-provider model rows that would otherwise carry no `contextWindow`.
*
* Why this matters: when a model row has neither `contextTokens` nor
* `contextWindow`, OpenClaw's embedded runner skips preemptive compaction and
* context-window guarding entirely, so long sessions only fail at the provider
* with "Context overflow: prompt too large" instead of being compacted early.
*
* Accuracy matters in both directions. Under-reporting is not the safe choice:
* it makes the runner start preflight compaction long before it is needed, and
* a compaction that times out aborts the whole turn. Over-reporting pushes the
* failure to the provider as a hard overflow. Prefer the vendor's published
* figure for the family rather than a defensive guess.
*
* Ordering contract: rules are evaluated top-down and the first match wins, so
* a specific variant MUST appear above its family fallback. Note that `\b`
* treats `.` and `-` as boundaries, so /\bgpt-5\b/ also matches `gpt-5.6-sol`;
* the generation-specific rules above it are what keep that correct.
*/
const CONTEXT_WINDOW_RULES: ContextWindowRule[] = [
// ── OpenAI ──────────────────────────────────────────────────────────────
{ label: 'GPT-5.6 Luna (low-latency tier)', pattern: /\bgpt-5\.6-luna\b/, contextWindow: 272_000 },
{ label: 'GPT-5.6 Sol / Terra', pattern: /\bgpt-5\.6\b/, contextWindow: 1_050_000 },
{ label: 'GPT-5.5', pattern: /\bgpt-5\.5\b/, contextWindow: 1_000_000 },
{ label: 'GPT-5 lightweight variants', pattern: /\bgpt-5[\w.]*-(?:mini|nano|turbo)\b/, contextWindow: 272_000 },
{ label: 'GPT-5 flagship', pattern: /\bgpt-5\b/, contextWindow: 400_000 },
{ label: 'GPT-4.x and o-series', pattern: /\b(?:gpt-4\.1|gpt-4o|o[134])\b/, contextWindow: 128_000 },
// ── Anthropic ───────────────────────────────────────────────────────────
{ label: 'Claude Fable 5 / Opus 5 / Sonnet 5', pattern: /\bclaude-(?:fable|opus|sonnet)-5\b/, contextWindow: 1_000_000 },
{ label: 'Claude Opus 4.8+', pattern: /\bclaude-opus-4[.-][89]\b/, contextWindow: 1_000_000 },
{ label: 'Claude Sonnet 4.6+', pattern: /\bclaude-sonnet-4[.-][6-9]\b/, contextWindow: 1_000_000 },
{ label: 'Claude Haiku and legacy Claude', pattern: /\bclaude\b|\bclaude-/, contextWindow: 200_000 },
// ── Google ──────────────────────────────────────────────────────────────
{ label: 'Gemini 1.0 (pre-million era)', pattern: /\bgemini-1\.0\b/, contextWindow: 32_768 },
{ label: 'Gemini 1.5 and newer', pattern: /\bgemini\b/, contextWindow: 1_048_576 },
// ── DeepSeek ────────────────────────────────────────────────────────────
// `deepseek-chat` / `deepseek-reasoner` are compatibility aliases that route
// to V4-Flash, so they inherit the V4 window rather than the V3 one.
{ label: 'DeepSeek V3 / R1', pattern: /\bdeepseek-(?:v3|r1)\b/, contextWindow: 128_000 },
{ label: 'DeepSeek V4 and aliases', pattern: /\bdeepseek\b/, contextWindow: 1_000_000 },
// ── Moonshot / Kimi ─────────────────────────────────────────────────────
// Only K3 reached a million tokens; K2.x tops out at 262,144.
{ label: 'Kimi K3', pattern: /\bkimi-k3\b/, contextWindow: 1_000_000 },
{ label: 'Kimi K2.x and other Moonshot', pattern: /\bkimi\b|moonshot/, contextWindow: 262_144 },
// ── Alibaba Qwen ────────────────────────────────────────────────────────
{ label: 'Qwen-Long (bulk document tier)', pattern: /\bqwen-long\b/, contextWindow: 10_000_000 },
{ label: 'Qwen 3.6+ hosted API', pattern: /\bqwen-?3\.[6-9]\b/, contextWindow: 1_000_000 },
{ label: 'Qwen 3.5 / Qwen3-Next', pattern: /\bqwen-?3\.5\b|\bqwen3-next\b/, contextWindow: 262_144 },
{ label: 'Qwen open-weight base', pattern: /\bqwen/, contextWindow: 131_072 },
// ── Z.AI GLM ────────────────────────────────────────────────────────────
{ label: 'GLM-5.2+', pattern: /\bglm-5\.[2-9]\b/, contextWindow: 1_000_000 },
{ label: 'GLM-5.0 / 5.1', pattern: /\bglm-5(?:\.[01])?\b/, contextWindow: 200_000 },
{ label: 'GLM-4.x', pattern: /\bglm-4/, contextWindow: 200_000 },
// ── MiniMax ─────────────────────────────────────────────────────────────
{ label: 'MiniMax M3+', pattern: /\bminimax-m[3-9]\b/, contextWindow: 524_288 },
{ label: 'MiniMax M2.x and earlier', pattern: /minimax/, contextWindow: 204_800 },
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 },
];
/**
* 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;
/** Safe floor for unknown custom models: high enough to avoid compaction spam. */
export const DEFAULT_CUSTOM_MODEL_CONTEXT_WINDOW = 131_072;
/**
* 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);
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 Math.min(DEFAULT_CUSTOM_MODEL_CONTEXT_WINDOW, ceiling);
return DEFAULT_CUSTOM_MODEL_CONTEXT_WINDOW;
}
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 supportsImageInput = VISION_MODEL_PATTERNS.some((pattern) => matchesModelId(pattern, modelId));
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)
);
return supportsImageInput ? ['text', 'image'] : ['text'];
}
+4 -4
View File
@@ -31,11 +31,11 @@ export const PROVIDER_DEFINITIONS: ProviderDefinition[] = [
requiresApiKey: true,
category: 'official',
envVar: 'OPENAI_API_KEY',
defaultModelId: 'gpt-5.6-sol',
defaultModelId: 'gpt-5.5',
isOAuth: true,
supportsApiKey: true,
showModelId: true,
modelIdPlaceholder: 'gpt-5.6-sol',
modelIdPlaceholder: 'gpt-5.5',
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: 262144,
contextWindow: 256000,
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: 262144,
contextWindow: 256000,
maxTokens: 8192,
},
],
+1
View File
@@ -207,6 +207,7 @@ export type ProviderSecret =
accountId: string;
accessToken: string;
refreshToken: string;
idToken?: string;
expiresAt: number;
scopes?: string[];
email?: string;
+24 -9
View File
@@ -1,6 +1,7 @@
import { access, copyFile, mkdir, readdir, rm } from 'fs/promises';
import { constants } from 'fs';
import { join, normalize } from 'path';
import { app } from 'electron';
import { deleteAgentChannelAccounts, listConfiguredChannels, readOpenClawConfig, writeOpenClawConfig } from './channel-config';
import type { OpenClawConfig } from './channel-config';
import { withConfigLock } from './config-mutex';
@@ -8,11 +9,15 @@ import { expandPath, getOpenClawConfigDir } from './paths';
import * as logger from './logger';
import { toUiChannelType } from './channel-alias';
import { ensureClawXIdentityFile } from './openclaw-workspace';
import {
listCcConnectAgentPermissionModes,
listCcConnectAgentProviderBindings,
} from '../runtime/cc-connect-agent-bindings';
import { getClawXDataLayout, resolveClawXDataRoot } from './clawx-data-layout';
const MAIN_AGENT_ID = 'main';
const MAIN_AGENT_NAME = 'Main Agent';
const DEFAULT_ACCOUNT_ID = 'default';
const DEFAULT_WORKSPACE_PATH = '~/.openclaw/workspace';
const AGENT_BOOTSTRAP_FILES = [
'AGENTS.md',
'SOUL.md',
@@ -166,7 +171,13 @@ function getDefaultWorkspacePath(config: AgentConfigDocument): string {
: undefined);
return typeof defaults?.workspace === 'string' && defaults.workspace.trim()
? defaults.workspace
: DEFAULT_WORKSPACE_PATH;
: getClawXManagedWorkspacePath(MAIN_AGENT_ID);
}
function getClawXManagedWorkspacePath(agentId: string): string {
const safeAgentId = agentId.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-') || MAIN_AGENT_ID;
const layout = getClawXDataLayout(resolveClawXDataRoot(process.env, app.getPath('userData')));
return join(layout.agentWorkspacesDir, safeAgentId);
}
function getDefaultAgentDirPath(agentId: string): string {
@@ -350,10 +361,8 @@ function trimTrailingSeparators(path: string): string {
}
function getManagedWorkspaceDirectory(agent: AgentListEntry): string | null {
if (agent.id === MAIN_AGENT_ID) return null;
const configuredWorkspace = expandPath(agent.workspace || `~/.openclaw/workspace-${agent.id}`);
const managedWorkspace = join(getOpenClawConfigDir(), `workspace-${agent.id}`);
const configuredWorkspace = expandPath(agent.workspace || getClawXManagedWorkspacePath(agent.id));
const managedWorkspace = getClawXManagedWorkspacePath(agent.id);
const normalizedConfigured = trimTrailingSeparators(normalize(configuredWorkspace));
const normalizedManaged = trimTrailingSeparators(normalize(managedWorkspace));
@@ -411,7 +420,7 @@ async function provisionAgentFilesystem(
const { entries } = normalizeAgentsConfig(config);
const mainEntry = entries.find((entry) => entry.id === MAIN_AGENT_ID) ?? createImplicitMainEntry(config);
const sourceWorkspace = expandPath(mainEntry.workspace || getDefaultWorkspacePath(config));
const targetWorkspace = expandPath(agent.workspace || `~/.openclaw/workspace-${agent.id}`);
const targetWorkspace = expandPath(agent.workspace || getClawXManagedWorkspacePath(agent.id));
const sourceAgentDir = expandPath(mainEntry.agentDir || getDefaultAgentDirPath(MAIN_AGENT_ID));
const targetAgentDir = expandPath(agent.agentDir || getDefaultAgentDirPath(agent.id));
const targetSessionsDir = join(getOpenClawConfigDir(), 'agents', agent.id, 'sessions');
@@ -465,6 +474,10 @@ async function buildSnapshotFromConfig(config: AgentConfigDocument, preloadedCha
const defaultAgentIdNorm = normalizeAgentIdForBinding(defaultAgentId);
const channelOwners: Record<string, string> = {};
const channelAccountOwners: Record<string, string> = {};
const [providerBindings, permissionModes] = await Promise.all([
listCcConnectAgentProviderBindings(),
listCcConnectAgentPermissionModes(),
]);
// Build per-agent channel lists from account-scoped bindings
const agentChannelSets = new Map<string, Set<string>>();
@@ -522,8 +535,10 @@ async function buildSnapshotFromConfig(config: AgentConfigDocument, preloadedCha
modelDisplay: modelLabel,
modelRef: explicitModelRef || defaultModelRef || null,
overrideModelRef: explicitModelRef,
providerAccountId: providerBindings[entry.id] ?? null,
permissionMode: permissionModes[entry.id] ?? 'full-auto',
inheritedModel,
workspace: entry.workspace || (entry.id === MAIN_AGENT_ID ? getDefaultWorkspacePath(config) : `~/.openclaw/workspace-${entry.id}`),
workspace: entry.workspace || getClawXManagedWorkspacePath(entry.id),
agentDir: entry.agentDir || getDefaultAgentDirPath(entry.id),
mainSessionKey: buildAgentMainSessionKey(config, entry.id),
channelTypes: configuredChannels
@@ -607,7 +622,7 @@ export async function createAgent(
const newAgent: AgentListEntry = {
id: nextId,
name: normalizedName,
workspace: `~/.openclaw/workspace-${nextId}`,
workspace: getClawXManagedWorkspacePath(nextId),
agentDir: getDefaultAgentDirPath(nextId),
};
+23 -52
View File
@@ -4,12 +4,6 @@ import { logger } from './logger';
import { loginOpenAICodexOAuth, type OpenAICodexOAuthCredentials } from './openai-codex-oauth';
import { getProviderService } from '../services/providers/provider-service';
import { getSecretStore } from '../services/secrets/secret-store';
import {
ensureOpenClawProviderAgentRuntimePins,
OPENAI_CODEX_OAUTH_PROVIDER_CONFIG,
saveOAuthTokenToOpenClaw,
setOpenClawDefaultModelWithOverride,
} from './openclaw-auth';
// Google was removed: OpenClaw's `google-gemini-cli` OAuth integration is an
// unofficial third-party flow that requires the `gemini` CLI binary to be on
@@ -17,22 +11,33 @@ import {
// account suspensions. ClawX does not bundle that binary, so the only
// browser-OAuth provider we currently expose end-to-end is OpenAI Codex.
export type BrowserOAuthProviderType = 'openai';
export type BrowserOAuthSuccessPayload = {
provider: BrowserOAuthProviderType;
accountId: string;
};
const OPENAI_RUNTIME_PROVIDER_ID = 'openai';
const OPENAI_OAUTH_DEFAULT_MODEL = 'gpt-5.6-sol';
const OPENAI_OAUTH_DEFAULT_MODEL = 'gpt-5.5';
class BrowserOAuthManager extends EventEmitter {
export class BrowserOAuthManager extends EventEmitter {
private activeAccountId: string | null = null;
private activeLabel: string | null = null;
private active = false;
private mainWindow: BrowserWindow | null = null;
private pendingManualCodeResolve: ((value: string) => void) | null = null;
private pendingManualCodeReject: ((reason?: unknown) => void) | null = null;
private successHandler: ((payload: BrowserOAuthSuccessPayload) => Promise<void>) | null = null;
setWindow(window: BrowserWindow) {
this.mainWindow = window;
}
setSuccessHandler(
handler: ((payload: BrowserOAuthSuccessPayload) => Promise<void>) | null,
): void {
this.successHandler = handler;
}
async startFlow(
provider: BrowserOAuthProviderType,
options?: { accountId?: string; label?: string },
@@ -125,12 +130,6 @@ class BrowserOAuthManager extends EventEmitter {
) {
const accountId = this.activeAccountId || providerType;
const accountLabel = this.activeLabel;
this.active = false;
this.activeAccountId = null;
this.activeLabel = null;
this.pendingManualCodeResolve = null;
this.pendingManualCodeReject = null;
logger.info(`[BrowserOAuth] Successfully completed OAuth for ${providerType}`);
const providerService = getProviderService();
const existing = await providerService.getAccount(accountId);
@@ -175,49 +174,21 @@ class BrowserOAuthManager extends EventEmitter {
accountId,
accessToken: token.access,
refreshToken: token.refresh,
idToken: token.idToken,
expiresAt: token.expires,
email: oauthTokenEmail,
subject: oauthTokenSubject,
});
await saveOAuthTokenToOpenClaw(runtimeProviderId, {
access: token.access,
refresh: token.refresh,
expires: token.expires,
email: oauthTokenEmail,
projectId: oauthTokenSubject,
accountId: oauthTokenSubject,
});
const modelId = normalizedExistingModel || defaultModel;
const modelRef = `${runtimeProviderId}/${modelId}`;
const fallbackModelRefs = (nextAccount.fallbackModels ?? [])
.map((fallback) => fallback.trim())
.filter(Boolean)
.map((fallback) => (
fallback.replace(/^openai-codex\//, `${runtimeProviderId}/`).startsWith(`${runtimeProviderId}/`)
? fallback.replace(/^openai-codex\//, `${runtimeProviderId}/`)
: `${runtimeProviderId}/${fallback}`
));
try {
await setOpenClawDefaultModelWithOverride(
runtimeProviderId,
modelRef,
{
baseUrl: OPENAI_CODEX_OAUTH_PROVIDER_CONFIG.baseUrl,
api: OPENAI_CODEX_OAUTH_PROVIDER_CONFIG.api,
},
fallbackModelRefs,
);
await ensureOpenClawProviderAgentRuntimePins();
logger.info(`[BrowserOAuth] Registered ${runtimeProviderId} in openclaw.json (default model: ${modelRef})`);
} catch (err) {
logger.warn('[BrowserOAuth] Failed to register OpenAI OAuth provider in openclaw.json:', err);
throw err;
}
this.emit('oauth:success', { provider: providerType, accountId: nextAccount.id });
const successPayload = { provider: providerType, accountId: nextAccount.id };
await this.successHandler?.(successPayload);
this.active = false;
this.activeAccountId = null;
this.activeLabel = null;
this.pendingManualCodeResolve = null;
this.pendingManualCodeReject = null;
logger.info(`[BrowserOAuth] Successfully completed OAuth for ${providerType}`);
this.emit('oauth:success', successPayload);
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
this.mainWindow.webContents.send('oauth:success', {
provider: providerType,
+147 -11
View File
@@ -12,6 +12,9 @@ import { getOpenClawResolvedDir } from './paths';
import * as logger from './logger';
import { proxyAwareFetch } from './proxy-fetch';
import { withConfigLock } from './config-mutex';
import { readClawXRuntimeConfig, writeClawXRuntimeConfig } from './clawx-runtime-config';
import { getChannelVaultSecrets, replaceChannelVaultSecrets } from '../services/secrets/credential-vault';
import { getSetting } from './store';
import {
OPENCLAW_WECHAT_CHANNEL_TYPE,
isWechatChannelType,
@@ -453,6 +456,95 @@ export interface OpenClawConfig {
[key: string]: unknown;
}
const CHANNEL_SECRET_FIELDS = new Set([
'accessToken',
'appPassword',
'appSecret',
'appToken',
'botSecret',
'botToken',
'callbackAesKey',
'callbackToken',
'channelAccessToken',
'channelSecret',
'channelToken',
'clientSecret',
'corpSecret',
'encryptKey',
'password',
'secret',
'serviceAccountKey',
'token',
]);
function cloneConfig(config: OpenClawConfig): OpenClawConfig {
return JSON.parse(JSON.stringify(config)) as OpenClawConfig;
}
function channelCredentialId(channelType: string, accountId: string): string {
return `${channelType}:${accountId}`;
}
function stripChannelSecrets(config: OpenClawConfig): {
config: OpenClawConfig;
secrets: Record<string, Record<string, string>>;
found: boolean;
} {
const sanitized = cloneConfig(config);
const secrets: Record<string, Record<string, string>> = {};
let found = false;
for (const [channelType, section] of Object.entries(sanitized.channels ?? {})) {
const accounts = section.accounts && typeof section.accounts === 'object'
? section.accounts as Record<string, ChannelConfigData>
: null;
const defaultAccountId = typeof section.defaultAccount === 'string' && section.defaultAccount.trim()
? section.defaultAccount.trim()
: 'default';
const entries: Array<[string, ChannelConfigData]> = [
[defaultAccountId, section],
...Object.entries(accounts ?? {}),
];
for (const [accountId, account] of entries) {
const accountSecrets: Record<string, string> = {};
for (const field of CHANNEL_SECRET_FIELDS) {
const value = account[field];
if (typeof value !== 'string' || !value) continue;
accountSecrets[field] = value;
delete account[field];
found = true;
}
if (Object.keys(accountSecrets).length > 0) {
const credentialId = channelCredentialId(channelType, accountId);
secrets[credentialId] = { ...(secrets[credentialId] ?? {}), ...accountSecrets };
}
}
}
return { config: sanitized, secrets, found };
}
function hydrateChannelSecrets(
config: OpenClawConfig,
secrets: Record<string, Record<string, string>>,
): OpenClawConfig {
const hydrated = cloneConfig(config);
for (const [channelType, section] of Object.entries(hydrated.channels ?? {})) {
const accounts = section.accounts && typeof section.accounts === 'object'
? section.accounts as Record<string, ChannelConfigData>
: null;
const defaultAccountId = typeof section.defaultAccount === 'string' && section.defaultAccount.trim()
? section.defaultAccount.trim()
: 'default';
const entries: Array<[string, ChannelConfigData]> = [
[defaultAccountId, section],
...Object.entries(accounts ?? {}),
];
for (const [accountId, account] of entries) {
Object.assign(account, secrets[channelCredentialId(channelType, accountId)] ?? {});
}
}
return hydrated;
}
// ── Config I/O ───────────────────────────────────────────────────
async function ensureConfigDir(): Promise<void> {
@@ -461,7 +553,7 @@ async function ensureConfigDir(): Promise<void> {
}
}
export async function readOpenClawConfig(): Promise<OpenClawConfig> {
async function readOpenClawCompatibilityConfig(): Promise<OpenClawConfig> {
await ensureConfigDir();
if (!(await fileExists(CONFIG_FILE))) {
@@ -478,9 +570,21 @@ export async function readOpenClawConfig(): Promise<OpenClawConfig> {
}
}
export async function writeOpenClawConfig(config: OpenClawConfig): Promise<void> {
await ensureConfigDir();
export async function readOpenClawConfig(): Promise<OpenClawConfig> {
const config = await readClawXRuntimeConfig({
readOpenClawCompatibility: readOpenClawCompatibilityConfig,
openClawConfigPath: CONFIG_FILE,
});
const stripped = stripChannelSecrets(config);
if (stripped.found) {
await replaceChannelVaultSecrets(stripped.secrets);
await writeClawXRuntimeConfig(stripped.config);
return config;
}
return hydrateChannelSecrets(config, await getChannelVaultSecrets());
}
export async function writeOpenClawConfig(config: OpenClawConfig): Promise<void> {
try {
// Enable graceful in-process reload authorization for SIGUSR1 flows.
const commands =
@@ -490,7 +594,12 @@ export async function writeOpenClawConfig(config: OpenClawConfig): Promise<void>
commands.restart = true;
config.commands = commands;
await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');
const stripped = stripChannelSecrets(config);
await replaceChannelVaultSecrets(stripped.secrets);
await writeClawXRuntimeConfig(stripped.config);
if (await getSetting('runtimeKind').catch(() => 'openclaw') === 'openclaw') {
await writeOpenClawCompatibilityProjection(config);
}
} catch (error) {
logger.error('Failed to write OpenClaw config', error);
console.error('Failed to write OpenClaw config:', error);
@@ -498,6 +607,12 @@ export async function writeOpenClawConfig(config: OpenClawConfig): Promise<void>
}
}
export async function writeOpenClawCompatibilityProjection(config?: OpenClawConfig): Promise<void> {
await ensureConfigDir();
const projected = config ?? await readOpenClawConfig();
await writeFile(CONFIG_FILE, JSON.stringify(projected, null, 2), { encoding: 'utf8', mode: 0o600 });
}
// ── Channel operations ───────────────────────────────────────────
async function ensurePluginAllowlist(currentConfig: OpenClawConfig, channelType: string): Promise<void> {
@@ -688,14 +803,26 @@ function transformChannelConfig(
}
}
if (channelType === 'feishu') {
const adminUsers = transformedConfig.adminUsers;
delete transformedConfig.adminUsers;
if (typeof adminUsers === 'string') {
const admins = adminUsers.split(',').map((value) => value.trim()).filter(Boolean);
transformedConfig.adminFrom = admins.length > 0
? admins
: existingAccountConfig.adminFrom;
}
}
if (channelType === 'feishu' || channelType === 'wecom') {
const existingDmPolicy = existingAccountConfig.dmPolicy === 'pairing' ? 'open' : existingAccountConfig.dmPolicy;
transformedConfig.dmPolicy = transformedConfig.dmPolicy ?? existingDmPolicy ?? 'open';
const hasExplicitAllowFrom = transformedConfig.allowFrom !== undefined;
let allowFrom = (transformedConfig.allowFrom ?? existingAccountConfig.allowFrom ?? ['*']) as string[];
if (!Array.isArray(allowFrom)) {
allowFrom = [allowFrom] as string[];
}
transformedConfig.dmPolicy = transformedConfig.dmPolicy
?? (hasExplicitAllowFrom && !allowFrom.includes('*') ? 'allowlist' : existingDmPolicy ?? 'open');
if (transformedConfig.dmPolicy === 'open' && !allowFrom.includes('*')) {
allowFrom = [...allowFrom, '*'];
@@ -751,6 +878,9 @@ function migrateLegacyChannelConfigToAccounts(
channelSection: ChannelConfigData,
defaultAccountId: string = DEFAULT_ACCOUNT_ID,
): void {
const targetAccountId = typeof channelSection.defaultAccount === 'string' && channelSection.defaultAccount.trim()
? channelSection.defaultAccount.trim()
: defaultAccountId;
const legacyPayload = getLegacyChannelPayload(channelSection);
const legacyKeys = Object.keys(legacyPayload);
const existingAccounts = getChannelAccountsMap(channelSection);
@@ -758,15 +888,15 @@ function migrateLegacyChannelConfigToAccounts(
if (legacyKeys.length === 0) {
if (hasAccounts && typeof channelSection.defaultAccount !== 'string') {
channelSection.defaultAccount = defaultAccountId;
channelSection.defaultAccount = targetAccountId;
}
return;
}
const accounts = ensureChannelAccountsMap(channelSection);
const existingDefaultAccount = accounts[defaultAccountId] ?? {};
const existingDefaultAccount = accounts[targetAccountId] ?? {};
accounts[defaultAccountId] = {
accounts[targetAccountId] = {
...(channelSection.enabled !== undefined ? { enabled: channelSection.enabled } : {}),
...legacyPayload,
...existingDefaultAccount,
@@ -775,7 +905,7 @@ function migrateLegacyChannelConfigToAccounts(
channelSection.defaultAccount =
typeof channelSection.defaultAccount === 'string' && channelSection.defaultAccount.trim()
? channelSection.defaultAccount
: defaultAccountId;
: targetAccountId;
for (const key of legacyKeys) {
delete channelSection[key];
@@ -852,7 +982,10 @@ export async function saveChannelConfig(
}
const channelSection = currentConfig.channels[resolvedChannelType];
migrateLegacyChannelConfigToAccounts(channelSection, DEFAULT_ACCOUNT_ID);
const currentDefaultAccountId = typeof channelSection.defaultAccount === 'string' && channelSection.defaultAccount.trim()
? channelSection.defaultAccount.trim()
: DEFAULT_ACCOUNT_ID;
migrateLegacyChannelConfigToAccounts(channelSection, currentDefaultAccountId);
// Guard: reject if this bot/app credential is already used by another account.
assertNoDuplicateCredential(resolvedChannelType, config, channelSection, resolvedAccountId);
@@ -984,6 +1117,9 @@ function extractFormValues(channelType: string, saved: ChannelConfigData): Recor
}
}
} else {
if (channelType === 'feishu' && Array.isArray(saved.adminFrom)) {
values.adminUsers = saved.adminFrom.join(', ');
}
for (const [key, value] of Object.entries(saved)) {
if (typeof value === 'string' && key !== 'enabled') {
values[key] = value;
+137
View File
@@ -0,0 +1,137 @@
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
export const CLAWX_DATA_VERSION = 1;
export interface ClawXDataLayout {
root: string;
stateDir: string;
dataVersionPath: string;
migrationJournalPath: string;
locksDir: string;
writerLockPath: string;
appDir: string;
credentialsDir: string;
skillsDir: string;
workspacesDir: string;
agentWorkspacesDir: string;
runtimesDir: string;
ccConnectRuntimeDir: string;
openClawRuntimeDir: string;
electronUserDataDir: string;
logsDir: string;
backupsDir: string;
cacheDir: string;
}
export interface ClawXDataVersionFile {
schema: 'clawx-data';
version: number;
createdAt: string;
updatedAt: string;
}
function cleanOverride(value: string | undefined): string | undefined {
const cleaned = value?.trim();
return cleaned ? resolve(cleaned) : undefined;
}
export function resolveClawXDataRoot(
env: NodeJS.ProcessEnv = process.env,
electronUserDataFallback?: string,
): string {
const fallback = cleanOverride(electronUserDataFallback);
const fallbackRoot = fallback
&& basename(fallback) === 'electron'
&& basename(dirname(fallback)) === 'system'
? resolve(fallback, '..', '..')
: fallback;
return cleanOverride(env.CLAWX_DATA_HOME)
?? cleanOverride(env.CLAWX_USER_DATA_DIR)
?? fallbackRoot
?? join(homedir(), '.clawx');
}
export function getClawXDataLayout(
root = resolveClawXDataRoot(),
env: NodeJS.ProcessEnv = process.env,
): ClawXDataLayout {
const resolvedRoot = resolve(root);
const stateDir = join(resolvedRoot, 'state');
const locksDir = join(resolvedRoot, 'locks');
const runtimesDir = join(resolvedRoot, 'runtimes');
const workspacesDir = join(resolvedRoot, 'workspaces');
const explicitElectronUserData = cleanOverride(env.CLAWX_USER_DATA_DIR);
const flatCompatibility = Boolean(explicitElectronUserData && !cleanOverride(env.CLAWX_DATA_HOME));
return {
root: resolvedRoot,
stateDir,
dataVersionPath: join(stateDir, 'data-version.json'),
migrationJournalPath: join(stateDir, 'migration-journal.jsonl'),
locksDir,
writerLockPath: join(locksDir, 'writer.lock'),
appDir: flatCompatibility ? resolvedRoot : join(resolvedRoot, 'app'),
credentialsDir: join(resolvedRoot, 'credentials'),
skillsDir: join(resolvedRoot, 'skills'),
workspacesDir,
agentWorkspacesDir: join(workspacesDir, 'agents'),
runtimesDir,
ccConnectRuntimeDir: join(runtimesDir, 'cc-connect'),
openClawRuntimeDir: join(runtimesDir, 'openclaw'),
electronUserDataDir: explicitElectronUserData ?? join(resolvedRoot, 'system', 'electron'),
logsDir: join(resolvedRoot, 'logs'),
backupsDir: join(resolvedRoot, 'backups'),
cacheDir: join(resolvedRoot, 'cache'),
};
}
function writeJsonAtomic(path: string, value: unknown): void {
mkdirSync(dirname(path), { recursive: true });
const temporaryPath = `${path}.${process.pid}.${Date.now()}.tmp`;
writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
renameSync(temporaryPath, path);
}
export function initializeClawXDataLayout(layout = getClawXDataLayout()): ClawXDataVersionFile {
for (const dir of [
layout.stateDir,
layout.locksDir,
layout.appDir,
layout.credentialsDir,
layout.skillsDir,
layout.agentWorkspacesDir,
layout.ccConnectRuntimeDir,
layout.openClawRuntimeDir,
layout.electronUserDataDir,
layout.logsDir,
layout.backupsDir,
layout.cacheDir,
]) {
mkdirSync(dir, { recursive: true });
}
if (existsSync(layout.dataVersionPath)) {
const current = JSON.parse(readFileSync(layout.dataVersionPath, 'utf8')) as Partial<ClawXDataVersionFile>;
if (current.schema !== 'clawx-data' || !Number.isInteger(current.version)) {
throw new Error(`Invalid ClawX data version file: ${layout.dataVersionPath}`);
}
if ((current.version ?? 0) > CLAWX_DATA_VERSION) {
throw new Error(
`ClawX data version ${current.version} is newer than supported version ${CLAWX_DATA_VERSION}; refusing to write`,
);
}
return current as ClawXDataVersionFile;
}
const now = new Date().toISOString();
const versionFile: ClawXDataVersionFile = {
schema: 'clawx-data',
version: CLAWX_DATA_VERSION,
createdAt: now,
updatedAt: now,
};
writeJsonAtomic(layout.dataVersionPath, versionFile);
return versionFile;
}
+100
View File
@@ -0,0 +1,100 @@
import { cp, lstat, mkdir, readFile, readdir, realpath, stat, writeFile } from 'node:fs/promises';
import { basename, dirname, join, resolve } from 'node:path';
import type { ClawXDataLayout } from './clawx-data-layout';
export interface ClawXLegacyMigrationResult {
skipped: boolean;
copied: string[];
source: string;
target: string;
}
const LEGACY_ELECTRON_PROFILE_PATHS = [
'Local Storage',
'IndexedDB',
join('Partitions', 'clawx-web-browser'),
] as const;
async function exists(path: string): Promise<boolean> {
return stat(path).then(() => true).catch(() => false);
}
async function copyIfMissing(source: string, target: string, copied: string[]): Promise<void> {
if (!(await exists(source))) return;
if (await exists(target)) {
const targetStat = await stat(target);
if (!targetStat.isDirectory() || (await readdir(target)).length > 0) return;
}
await mkdir(dirname(target), { recursive: true });
await cp(source, target, {
recursive: true,
errorOnExist: false,
force: false,
filter: async (sourcePath) => {
const entry = await lstat(sourcePath);
return entry.isDirectory() || entry.isFile() || entry.isSymbolicLink();
},
});
copied.push(target);
}
async function canonicalPath(path: string): Promise<string> {
return realpath(path).catch(() => resolve(path));
}
async function appendJournal(layout: ClawXDataLayout, record: Record<string, unknown>): Promise<void> {
await mkdir(layout.stateDir, { recursive: true });
const previous = await readFile(layout.migrationJournalPath, 'utf8').catch(() => '');
await writeFile(layout.migrationJournalPath, `${previous}${JSON.stringify(record)}\n`, {
encoding: 'utf8',
mode: 0o600,
});
}
export async function migrateLegacyClawXData(options: {
legacyElectronUserDataDir: string;
layout: ClawXDataLayout;
}): Promise<ClawXLegacyMigrationResult> {
const source = await canonicalPath(options.legacyElectronUserDataDir);
const target = await canonicalPath(options.layout.root);
const electronUserDataDir = await canonicalPath(options.layout.electronUserDataDir);
if (
source === electronUserDataDir
|| source === target
|| source.startsWith(`${target}/`)
) {
return { skipped: true, copied: [], source, target };
}
const copied: string[] = [];
for (const fileName of ['settings.json', 'clawx-providers.json']) {
await copyIfMissing(join(source, fileName), join(options.layout.appDir, fileName), copied);
}
for (const fileName of ['window-state.json', 'clawx-device-identity.json']) {
await copyIfMissing(join(source, fileName), join(options.layout.electronUserDataDir, fileName), copied);
}
for (const relativePath of LEGACY_ELECTRON_PROFILE_PATHS) {
await copyIfMissing(
join(source, relativePath),
join(options.layout.electronUserDataDir, relativePath),
copied,
);
}
await copyIfMissing(
join(source, 'runtimes', 'cc-connect'),
options.layout.ccConnectRuntimeDir,
copied,
);
await copyIfMissing(join(source, 'logs'), options.layout.logsDir, copied);
await appendJournal(options.layout, {
schema: 'clawx-data-migration',
version: 1,
migration: 'legacy-electron-user-data-import',
source,
target,
copied: copied.map((path) => basename(path)),
completedAt: new Date().toISOString(),
});
return { skipped: false, copied, source, target };
}
+71
View File
@@ -0,0 +1,71 @@
import { randomUUID } from 'node:crypto';
import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { app } from 'electron';
import { getClawXDataLayout, resolveClawXDataRoot } from './clawx-data-layout';
type RuntimeConfigDocument<T> = {
schema: 'clawx-runtime-config';
version: 1;
importedFromOpenClawAt?: string;
updatedAt: string;
config: T;
};
function runtimeConfigPath(): string {
const layout = getClawXDataLayout(resolveClawXDataRoot(process.env, app.getPath('userData')));
return join(layout.appDir, 'runtime-config.json');
}
async function writeAtomic(path: string, value: unknown): Promise<void> {
await mkdir(dirname(path), { recursive: true });
const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
await writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
await chmod(temporaryPath, 0o600).catch(() => {});
await rename(temporaryPath, path);
await chmod(path, 0o600).catch(() => {});
}
async function readDocument<T>(): Promise<RuntimeConfigDocument<T> | null> {
try {
const parsed = JSON.parse(await readFile(runtimeConfigPath(), 'utf8')) as Partial<RuntimeConfigDocument<T>>;
if (parsed.schema === 'clawx-runtime-config' && parsed.version === 1 && parsed.config) {
return parsed as RuntimeConfigDocument<T>;
}
} catch {
// Missing canonical config is imported from the compatibility source.
}
return null;
}
export async function readClawXRuntimeConfig<T extends Record<string, unknown>>(options: {
readOpenClawCompatibility: () => Promise<T>;
openClawConfigPath: string;
}): Promise<T> {
const canonicalPath = runtimeConfigPath();
const document = await readDocument<T>();
if (document) return document.config;
const config = await options.readOpenClawCompatibility();
await writeAtomic(canonicalPath, {
schema: 'clawx-runtime-config',
version: 1,
importedFromOpenClawAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
config,
} satisfies RuntimeConfigDocument<T>);
return config;
}
export async function writeClawXRuntimeConfig<T extends Record<string, unknown>>(config: T): Promise<void> {
await writeAtomic(runtimeConfigPath(), {
schema: 'clawx-runtime-config',
version: 1,
updatedAt: new Date().toISOString(),
config,
} satisfies RuntimeConfigDocument<T>);
}
export function getClawXRuntimeConfigPath(): string {
return runtimeConfigPath();
}
+23 -3
View File
@@ -11,6 +11,7 @@ import { app } from 'electron';
import { join } from 'path';
import { existsSync, mkdirSync, appendFileSync } from 'fs';
import { appendFile, open, readdir, stat } from 'fs/promises';
import { getClawXDataLayout } from './clawx-data-layout';
/**
* Log levels
@@ -80,8 +81,27 @@ function flushBufferSync(): void {
writeBuffer = [];
}
// Ensure all buffered data reaches disk before the process exits.
process.on('exit', flushBufferSync);
type LoggerGlobalState = typeof globalThis & {
__clawxLoggerExitFlushers?: Set<() => void>;
__clawxLoggerExitHandlerRegistered?: boolean;
};
const loggerGlobalState = globalThis as LoggerGlobalState;
const loggerExitFlushers = loggerGlobalState.__clawxLoggerExitFlushers ?? new Set<() => void>();
loggerGlobalState.__clawxLoggerExitFlushers = loggerExitFlushers;
loggerExitFlushers.add(flushBufferSync);
// Ensure all buffered data reaches disk before the process exits. Vitest can
// reload this module many times, so keep one process listener and fan out to
// each module instance's buffer flusher.
if (!loggerGlobalState.__clawxLoggerExitHandlerRegistered) {
process.on('exit', () => {
for (const flush of loggerExitFlushers) {
flush();
}
});
loggerGlobalState.__clawxLoggerExitHandlerRegistered = true;
}
// ── Initialisation ───────────────────────────────────────────────
@@ -95,7 +115,7 @@ export function initLogger(): void {
currentLevel = LogLevel.INFO;
}
logDir = join(app.getPath('userData'), 'logs');
logDir = getClawXDataLayout().logsDir;
if (!existsSync(logDir)) {
mkdirSync(logDir, { recursive: true });
+5 -1
View File
@@ -26,6 +26,7 @@ const SUCCESS_HTML = `<!doctype html>
export interface OpenAICodexOAuthCredentials {
access: string;
refresh: string;
idToken?: string;
expires: number;
accountId: string;
email?: string;
@@ -219,7 +220,7 @@ function startLocalOAuthServer(state: string): Promise<OpenAICodexLocalServer |
async function exchangeAuthorizationCode(
code: string,
verifier: string,
): Promise<{ access: string; refresh: string; expires: number }> {
): Promise<{ access: string; refresh: string; idToken?: string; expires: number }> {
const response = await proxyAwareFetch(TOKEN_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
@@ -240,6 +241,7 @@ async function exchangeAuthorizationCode(
const json = await response.json() as {
access_token?: string;
refresh_token?: string;
id_token?: string;
expires_in?: number;
};
if (!json.access_token || !json.refresh_token || typeof json.expires_in !== 'number') {
@@ -249,6 +251,7 @@ async function exchangeAuthorizationCode(
return {
access: json.access_token,
refresh: json.refresh_token,
idToken: typeof json.id_token === 'string' && json.id_token.trim() ? json.id_token.trim() : undefined,
expires: Date.now() + json.expires_in * 1000,
};
}
@@ -306,6 +309,7 @@ export async function loginOpenAICodexOAuth(options: {
return {
access: token.access,
refresh: token.refresh,
idToken: token.idToken,
expires: token.expires,
accountId,
email: getEmailFromAccessToken(token.access),
+14 -48
View File
@@ -29,13 +29,9 @@ import {
} from './provider-keys';
import { normalizePiAiModelCost, type PiAiModelCostRates } from '../shared/pi-ai-model-cost';
import { withConfigLock } from './config-mutex';
import {
ensureMemorySearchFtsDefault,
hasUserMemorySearchConfig,
MEMORY_SEARCH_FTS_MIGRATION_VERSION,
} from './openclaw-memory-search';
import { ensureMemorySearchDisabledDefault, hasUserMemorySearchConfig } from './openclaw-memory-search';
import { PORTS } from './config';
import { getSetting, setSetting } from './store';
import { getSetting } from './store';
import {
assertValidApiProtocol,
normalizeOpenClawApiProtocol,
@@ -926,10 +922,7 @@ function backfillCustomProviderModelContextWindows(config: Record<string, unknow
for (const row of rows) {
if (!isPlainRecord(row) || typeof row.id !== 'string' || !row.id) continue;
if (typeof row.contextWindow === 'number' || typeof row.contextTokens === 'number') continue;
row.contextWindow = inferCustomModelContextWindow(row.id, {
providerKey,
apiProtocol: typeof entry.api === 'string' ? entry.api : undefined,
});
row.contextWindow = inferCustomModelContextWindow(row.id);
backfilled.push(`${providerKey}/${row.id}`);
}
}
@@ -1922,10 +1915,7 @@ function upsertOpenClawProviderEntry(
input: inferCustomModelInputModalities(id),
// Without an explicit contextWindow OpenClaw cannot budget compaction
// for custom providers and long sessions die with context overflow.
contextWindow: inferCustomModelContextWindow(id, {
providerKey: provider,
apiProtocol: options.api,
}),
contextWindow: inferCustomModelContextWindow(id),
}
: {}),
}));
@@ -2723,31 +2713,16 @@ export async function batchSyncConfigFields(token: string): Promise<void> {
}
// ── Memory search default ──
// OpenClaw 2026.7.1 supports provider=none as an explicit FTS-only mode.
// Migrate ClawX's exact legacy disabled default once, and otherwise seed
// FTS only when the user has no memorySearch config or OpenAI embedding key.
const memorySearchMigrationVersion = Number(
await getSetting('memorySearchFtsMigrationVersion'),
) || 0;
const shouldMigrateLegacyMemorySearch =
memorySearchMigrationVersion < MEMORY_SEARCH_FTS_MIGRATION_VERSION;
let memorySearchDefaultResult = shouldMigrateLegacyMemorySearch
&& hasUserMemorySearchConfig(config)
? ensureMemorySearchFtsDefault(config, true)
: 'unchanged';
if (memorySearchDefaultResult === 'unchanged'
&& !hasUserMemorySearchConfig(config)
&& !(await getProviderApiKeyFromOpenClaw('openai'))) {
memorySearchDefaultResult = ensureMemorySearchFtsDefault(config);
}
if (memorySearchDefaultResult !== 'unchanged') {
// OpenClaw defaults to the openai embedding provider; without a key that
// yields doctor errors and a broken memory_search tool. Seed enabled=false
// only when the user has no memorySearch config anywhere AND no OpenAI key
// (i.e. the default embedding model is unusable). Existing user config is
// never modified.
if (!hasUserMemorySearchConfig(config)
&& !(await getProviderApiKeyFromOpenClaw('openai'))
&& ensureMemorySearchDisabledDefault(config)) {
modified = true;
console.log(
`[batch-sync] ${memorySearchDefaultResult === 'migrated' ? 'Migrated' : 'Seeded'} `
+ 'agents.defaults.memorySearch to FTS-only mode',
);
console.log('[batch-sync] Seeded agents.defaults.memorySearch.enabled=false (no embedding provider configured)');
}
// ── Custom provider contextWindow backfill ──
@@ -2761,12 +2736,6 @@ export async function batchSyncConfigFields(token: string): Promise<void> {
await writeOpenClawJson(config);
console.log('Synced gateway token, browser config, web_fetch SSRF policy, and session idle to openclaw.json');
}
if (shouldMigrateLegacyMemorySearch) {
await setSetting(
'memorySearchFtsMigrationVersion',
MEMORY_SEARCH_FTS_MIGRATION_VERSION,
);
}
});
}
@@ -2825,10 +2794,7 @@ async function updateModelsJsonProviderEntriesForAgents(
&& typeof base.contextWindow !== 'number'
&& typeof base.contextTokens !== 'number'
) {
base.contextWindow = inferCustomModelContextWindow(m.id, {
providerKey: providerType,
apiProtocol: entry.api,
});
base.contextWindow = inferCustomModelContextWindow(m.id);
}
return {
...base,
+13 -1
View File
@@ -5,11 +5,23 @@
* (`#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 url = new URL('/', `http://127.0.0.1:${port}`);
const path = options.view ? CONTROL_UI_VIEW_PATHS[options.view] : '/';
const url = new URL(path, `http://127.0.0.1:${port}`);
const trimmedToken = token.trim();
if (trimmedToken) {
+14 -32
View File
@@ -1,15 +1,14 @@
/**
* Memory search default seeding for openclaw.json.
*
* OpenClaw defaults to the `openai` embedding provider. When no OpenAI key is
* available, ClawX explicitly selects OpenClaw's keyword-only FTS provider so
* memory_search remains useful without making an embedding request.
* 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.
*/
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);
}
@@ -30,35 +29,18 @@ export function hasUserMemorySearchConfig(config: Record<string, unknown>): bool
}
/**
* 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.
* 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.
*/
export function ensureMemorySearchFtsDefault(
config: Record<string, unknown>,
migrateLegacyDisabledDefault = false,
): MemorySearchDefaultResult {
export function ensureMemorySearchDisabledDefault(config: Record<string, unknown>): boolean {
if (hasUserMemorySearchConfig(config)) return false;
const agents = (isRecord(config.agents) ? config.agents : {}) as Record<string, unknown>;
const list = Array.isArray(agents.list) ? agents.list : [];
if (list.some((entry) => isRecord(entry) && entry.memorySearch !== undefined)) {
return 'unchanged';
}
const defaults = (isRecord(agents.defaults) ? agents.defaults : {}) as Record<string, unknown>;
const memorySearch = defaults.memorySearch;
if (memorySearch !== undefined) {
const isLegacyDisabledDefault = isRecord(memorySearch)
&& Object.keys(memorySearch).length === 1
&& memorySearch.enabled === false;
if (!migrateLegacyDisabledDefault || !isLegacyDisabledDefault) {
return 'unchanged';
}
}
defaults.memorySearch = { enabled: true, provider: 'none' };
defaults.memorySearch = { enabled: false };
agents.defaults = defaults;
config.agents = agents;
return memorySearch === undefined ? 'seeded' : 'migrated';
return true;
}
+4 -3
View File
@@ -6,6 +6,7 @@ import { createRequire } from 'node:module';
import { dirname, join, resolve } from 'path';
import { homedir } from 'os';
import { existsSync, mkdirSync, readFileSync, realpathSync } from 'fs';
import { getClawXDataLayout, resolveClawXDataRoot } from './clawx-data-layout';
const require = createRequire(import.meta.url);
@@ -79,21 +80,21 @@ export function getOpenClawSkillsDir(): string {
* Get ClawX config directory
*/
export function getClawXConfigDir(): string {
return join(homedir(), '.clawx');
return resolveClawXDataRoot();
}
/**
* Get ClawX logs directory
*/
export function getLogsDir(): string {
return join(getElectronApp().getPath('userData'), 'logs');
return getClawXDataLayout().logsDir;
}
/**
* Get ClawX data directory
*/
export function getDataDir(): string {
return getElectronApp().getPath('userData');
return resolveClawXDataRoot();
}
/**
+5 -6
View File
@@ -7,13 +7,12 @@
*/
import { app } from 'electron';
import path from 'node:path';
import { existsSync, cpSync, copyFileSync, statSync, lstatSync, mkdirSync, readFileSync, writeFileSync, readdirSync, realpathSync, symlinkSync, unlinkSync } from 'node:fs';
import { existsSync, cpSync, copyFileSync, statSync, lstatSync, mkdirSync, rmSync, readFileSync, writeFileSync, readdirSync, realpathSync, symlinkSync, unlinkSync } from 'node:fs';
import { readdir, stat, copyFile, mkdir } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { logger } from './logger';
import { getOpenClawResolvedDir } from './paths';
import { safeRmSync } from './safe-fs';
import {
upsertPluginInstallRecordsIntoSqlite,
removePluginInstallRecordsFromSqlite,
@@ -492,7 +491,7 @@ export function repairPluginOpenClawPeerLink(
logger.warn(`[plugin] Cannot replace non-OpenClaw peer directory at ${linkPath}`);
return false;
}
safeRmSync(fsPath(linkPath));
rmSync(fsPath(linkPath), { recursive: true, force: true });
} else {
logger.warn(`[plugin] Cannot replace non-directory OpenClaw peer at ${linkPath}`);
return false;
@@ -665,7 +664,7 @@ export function copyPluginFromNodeModules(npmPkgPath: string, targetDir: string,
}
// 1. Copy plugin package itself
safeRmSync(fsPath(targetDir));
rmSync(fsPath(targetDir), { recursive: true, force: true });
mkdirSync(fsPath(targetDir), { recursive: true });
cpSyncSafe(realPath, targetDir);
@@ -765,7 +764,7 @@ export function ensurePluginInstalled(
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
mkdirSync(fsPath(extensionsRoot), { recursive: true });
safeRmSync(fsPath(targetDir));
rmSync(fsPath(targetDir), { recursive: true, force: true });
cpSyncSafe(sourceDir, targetDir);
if (!existsSync(fsPath(join(targetDir, 'openclaw.plugin.json')))) {
return { installed: false, warning: `Failed to install ${pluginLabel} plugin mirror (manifest missing).` };
@@ -779,7 +778,7 @@ export function ensurePluginInstalled(
attempts.push({ attempt, ...diagnostic });
if (attempt < maxAttempts) {
try {
safeRmSync(fsPath(targetDir));
rmSync(fsPath(targetDir), { recursive: true, force: true });
} catch {
// Ignore cleanup failures before retry.
}
+44
View File
@@ -0,0 +1,44 @@
import { homedir } from 'node:os';
import { join } from 'node:path';
import type { RuntimeKind } from '@shared/types/gateway';
import { getCcConnectManagedDir } from '../runtime/cc-connect-paths';
type RuntimeStatusReader = {
getStatus?: () => { runtimeKind?: RuntimeKind };
};
function getActiveRuntimeKind(runtimeManager?: RuntimeStatusReader | null): RuntimeKind {
try {
return runtimeManager?.getStatus?.().runtimeKind === 'cc-connect' ? 'cc-connect' : 'openclaw';
} catch {
return 'openclaw';
}
}
export function getOpenClawMediaDir(): string {
return join(homedir(), '.openclaw', 'media');
}
export function getCcConnectMediaDir(): string {
return join(getCcConnectManagedDir(), 'media');
}
export function getRuntimeMediaDir(runtimeManager?: RuntimeStatusReader | null): string {
return getActiveRuntimeKind(runtimeManager) === 'cc-connect'
? getCcConnectMediaDir()
: getOpenClawMediaDir();
}
export function getRuntimeOutboundMediaDir(runtimeManager?: RuntimeStatusReader | null): string {
return join(getRuntimeMediaDir(runtimeManager), 'outbound');
}
export function getRuntimeOutgoingMediaRecordDirs(runtimeManager?: RuntimeStatusReader | null): string[] {
const active = getRuntimeMediaDir(runtimeManager);
const ccConnect = getCcConnectMediaDir();
const fallback = active === ccConnect ? getOpenClawMediaDir() : ccConnect;
return [
join(active, 'outgoing', 'records'),
join(fallback, 'outgoing', 'records'),
];
}
-128
View File
@@ -1,128 +0,0 @@
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);
}
+15 -16
View File
@@ -35,10 +35,6 @@ import { getOpenClawProviderKeyForType } from './provider-keys';
export async function storeApiKey(providerId: string, apiKey: string): Promise<boolean> {
try {
await ensureProviderStoreMigrated();
const s = await getClawXProviderStore();
const keys = (s.get('apiKeys') || {}) as Record<string, string>;
keys[providerId] = apiKey;
s.set('apiKeys', keys);
await setProviderSecret({
type: 'api_key',
accountId: providerId,
@@ -65,9 +61,7 @@ export async function getApiKey(providerId: string): Promise<string | null> {
return secret.apiKey ?? null;
}
const s = await getClawXProviderStore();
const keys = (s.get('apiKeys') || {}) as Record<string, string>;
return keys[providerId] || null;
return null;
} catch (error) {
console.error('Failed to retrieve API key:', error);
return null;
@@ -80,10 +74,6 @@ export async function getApiKey(providerId: string): Promise<string | null> {
export async function deleteApiKey(providerId: string): Promise<boolean> {
try {
await ensureProviderStoreMigrated();
const s = await getClawXProviderStore();
const keys = (s.get('apiKeys') || {}) as Record<string, string>;
delete keys[providerId];
s.set('apiKeys', keys);
await deleteProviderSecret(providerId);
return true;
} catch (error) {
@@ -102,9 +92,7 @@ export async function hasApiKey(providerId: string): Promise<boolean> {
return true;
}
const s = await getClawXProviderStore();
const keys = (s.get('apiKeys') || {}) as Record<string, string>;
return providerId in keys;
return secret?.type === 'local' && Boolean(secret.apiKey);
}
/**
@@ -113,8 +101,19 @@ export async function hasApiKey(providerId: string): Promise<boolean> {
export async function listStoredKeyIds(): Promise<string[]> {
await ensureProviderStoreMigrated();
const s = await getClawXProviderStore();
const keys = (s.get('apiKeys') || {}) as Record<string, string>;
return Object.keys(keys);
const legacyKeys = (s.get('apiKeys') || {}) as Record<string, string>;
const accountIds = new Set([
...Object.keys(legacyKeys),
...(await listProviderAccounts()).map((account) => account.id),
]);
const stored: string[] = [];
for (const accountId of accountIds) {
const secret = await getProviderSecret(accountId);
if (secret?.type === 'api_key' || (secret?.type === 'local' && secret.apiKey)) {
stored.push(accountId);
}
}
return stored.sort();
}
// ==================== Provider Configuration ====================
+5 -2
View File
@@ -7,6 +7,8 @@ import { randomBytes } from 'crypto';
import { app } from 'electron';
import { resolveSupportedLanguage } from '@shared/language';
import { DEFAULT_WORKSPACE_CWD } from '@shared/workspace';
import type { RuntimeKind } from '@shared/types/gateway';
import { getClawXDataLayout, resolveClawXDataRoot } from './clawx-data-layout';
// Lazy-load electron-store (ESM module)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -34,6 +36,7 @@ export interface AppSettings {
// Gateway
gatewayAutoStart: boolean;
runtimeKind: RuntimeKind;
gatewayPort: number;
gatewayToken: string;
proxyEnabled: boolean;
@@ -42,7 +45,6 @@ export interface AppSettings {
proxyHttpsServer: string;
proxyAllServer: string;
proxyBypassRules: string;
memorySearchFtsMigrationVersion: number;
// Update
updateChannel: 'stable' | 'beta' | 'dev';
@@ -89,6 +91,7 @@ function createDefaultSettings(): AppSettings {
// Gateway
gatewayAutoStart: true,
runtimeKind: 'openclaw',
gatewayPort: 18789,
gatewayToken: generateToken(),
proxyEnabled: false,
@@ -97,7 +100,6 @@ function createDefaultSettings(): AppSettings {
proxyHttpsServer: '',
proxyAllServer: '',
proxyBypassRules: '<local>;localhost;127.0.0.1;::1',
memorySearchFtsMigrationVersion: 0,
// Update
updateChannel: 'stable',
@@ -127,6 +129,7 @@ async function getSettingsStore() {
const Store = (await import('electron-store')).default;
settingsStoreInstance = new Store<AppSettings>({
name: 'settings',
cwd: getClawXDataLayout(resolveClawXDataRoot(process.env, app.getPath('userData'))).appDir,
defaults: createDefaultSettings(),
});
}
+234 -54
View File
@@ -1,19 +1,32 @@
export interface TokenUsageHistoryEntry {
runtimeKind?: 'openclaw' | 'cc-connect';
timestamp: string;
sessionId: string;
runtimeSessionId?: string;
agentId: string;
providerAccountId?: string;
model?: string;
provider?: string;
content?: string;
turnId?: string;
usageStatus: 'available' | 'missing' | 'error';
inputTokens: number;
outputTokens: number;
cacheReadTokens: number;
cacheWriteTokens: number;
reasoningTokens?: number;
totalTokens: number;
costUsd?: number;
}
type UsageParseContext = {
sessionId: string;
agentId: string;
runtimeKind?: TokenUsageHistoryEntry['runtimeKind'];
model?: string;
provider?: string;
};
export function extractSessionIdFromTranscriptFileName(fileName: string): string | undefined {
if (!fileName.endsWith('.jsonl') && !fileName.includes('.jsonl.reset.')) return undefined;
return fileName
@@ -37,6 +50,8 @@ interface TranscriptUsageShape {
total_tokens?: number;
cache_read?: number;
cache_write?: number;
cachedInputTokens?: number;
cached_input_tokens?: number;
prompt_tokens?: number;
completion_tokens?: number;
cache_read_tokens?: number;
@@ -54,9 +69,24 @@ interface TranscriptUsageShape {
cacheReadTokenCount?: number;
cacheReadTokens?: number;
cache_write_token_count?: number;
cost?: {
reasoningTokens?: number;
reasoning_tokens?: number;
reasoningOutputTokens?: number;
reasoning_output_tokens?: number;
cost?: number | string | {
total?: number;
usd?: number;
total_usd?: number;
totalUsd?: number;
amount?: number;
};
costUsd?: number;
cost_usd?: number;
costUSD?: number;
totalCost?: number;
total_cost?: number;
totalCostUsd?: number;
total_cost_usd?: number;
}
type UsageRecordStatus = 'available' | 'missing' | 'error';
@@ -66,6 +96,7 @@ interface ParsedUsageTokens {
outputTokens: number;
cacheReadTokens: number;
cacheWriteTokens: number;
reasoningTokens?: number;
totalTokens: number;
costUsd?: number;
usageStatus: UsageRecordStatus;
@@ -96,6 +127,32 @@ function firstUsageNumber(usage: TranscriptUsageShape | undefined, candidates: s
return undefined;
}
function parseUsageCostUsd(usage: TranscriptUsageShape): number | undefined {
const direct = firstUsageNumber(usage, [
'costUsd',
'cost_usd',
'costUSD',
'totalCostUsd',
'total_cost_usd',
'totalCost',
'total_cost',
'cost',
]);
if (direct !== undefined) return direct;
if (usage.cost && typeof usage.cost === 'object' && !Array.isArray(usage.cost)) {
return firstUsageNumber(usage.cost as TranscriptUsageShape, [
'total',
'usd',
'total_usd',
'totalUsd',
'amount',
]);
}
return undefined;
}
function parseUsageFromShape(usage: unknown): ParsedUsageTokens | undefined {
if (usage === undefined) {
return undefined;
@@ -141,6 +198,8 @@ function parseUsageFromShape(usage: unknown): ParsedUsageTokens | undefined {
'cache_read_tokens',
'cacheReadTokenCount',
'cache_read_token_count',
'cachedInputTokens',
'cached_input_tokens',
]);
const cacheWriteTokens = firstUsageNumber(usageShape, [
'cacheWrite',
@@ -157,14 +216,21 @@ function parseUsageFromShape(usage: unknown): ParsedUsageTokens | undefined {
'totalTokenCount',
'total_token_count',
]);
const reasoningTokens = firstUsageNumber(usageShape, [
'reasoningTokens',
'reasoning_tokens',
'reasoningOutputTokens',
'reasoning_output_tokens',
]);
const hasUsageValue =
inputTokens !== undefined
|| outputTokens !== undefined
|| cacheReadTokens !== undefined
|| cacheWriteTokens !== undefined
|| reasoningTokens !== undefined
|| explicitTotalTokens !== undefined
|| normalizeUsageNumber(usageShape.cost?.total) !== undefined;
|| parseUsageCostUsd(usageShape) !== undefined;
if (!hasUsageValue) {
return {
@@ -180,8 +246,6 @@ function parseUsageFromShape(usage: unknown): ParsedUsageTokens | undefined {
const totalTokens = explicitTotalTokens ?? (
(inputTokens ?? 0)
+ (outputTokens ?? 0)
+ (cacheReadTokens ?? 0)
+ (cacheWriteTokens ?? 0)
);
return {
@@ -190,8 +254,9 @@ function parseUsageFromShape(usage: unknown): ParsedUsageTokens | undefined {
outputTokens: outputTokens ?? 0,
cacheReadTokens: cacheReadTokens ?? 0,
cacheWriteTokens: cacheWriteTokens ?? 0,
...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
totalTokens,
costUsd: normalizeUsageNumber(usageShape.cost?.total),
costUsd: parseUsageCostUsd(usageShape),
};
}
@@ -214,8 +279,25 @@ interface TranscriptLineShape {
};
};
};
payload?: {
type?: string;
model?: string;
model_provider?: string;
info?: {
last_token_usage?: TranscriptUsageShape;
total_token_usage?: TranscriptUsageShape;
};
};
}
type UsageMessageShape = NonNullable<TranscriptLineShape['message']> & {
id?: string;
timestamp?: string | number;
created_at?: string | number;
createdAt?: string | number;
content?: unknown;
};
function normalizeUsageContent(value: unknown): string | undefined {
if (typeof value === 'string') {
const trimmed = value.trim();
@@ -257,13 +339,155 @@ function normalizeUsageContent(value: unknown): string | undefined {
return undefined;
}
function normalizeUsageTimestamp(value: unknown): string | undefined {
if (typeof value === 'string' && value.trim()) {
const parsed = Date.parse(value);
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : value;
}
if (typeof value === 'number' && Number.isFinite(value)) {
return new Date(value < 1e12 ? value * 1000 : value).toISOString();
}
return undefined;
}
function usageEntryFromMessage(
message: UsageMessageShape | undefined,
timestamp: string | undefined,
context: UsageParseContext,
): TokenUsageHistoryEntry | null {
if (!message || !timestamp) return null;
if (message.role === 'assistant' && 'usage' in message) {
const usage = parseUsageFromShape(message.usage);
if (!usage) return null;
const contentText = normalizeUsageContent((message as Record<string, unknown>).content);
return {
timestamp,
...(context.runtimeKind ? { runtimeKind: context.runtimeKind } : {}),
sessionId: context.sessionId,
agentId: context.agentId,
model: message.model ?? message.modelRef,
provider: message.provider,
...(contentText ? { content: contentText } : {}),
...(message.id ? { turnId: message.id } : {}),
...usage,
};
}
if (message.role !== 'toolResult' && message.role !== 'toolresult') {
return null;
}
const details = message.details;
if (!details || !('usage' in details)) {
return null;
}
const usage = parseUsageFromShape(details.usage);
if (!usage) return null;
const provider = details.provider ?? details.externalContent?.provider ?? message.provider;
const model = details.model ?? message.model ?? message.modelRef;
const contentText = normalizeUsageContent(details.content)
?? normalizeUsageContent((message as Record<string, unknown>).content);
return {
timestamp,
...(context.runtimeKind ? { runtimeKind: context.runtimeKind } : {}),
sessionId: context.sessionId,
agentId: context.agentId,
model,
provider,
...(contentText ? { content: contentText } : {}),
...(message.id ? { turnId: message.id } : {}),
...usage,
};
}
function usageEntryFromCodexTokenCount(
record: TranscriptLineShape,
timestamp: string | undefined,
context: UsageParseContext,
): TokenUsageHistoryEntry | null {
if (!timestamp || record.type !== 'event_msg' || record.payload?.type !== 'token_count') {
return null;
}
const usage = parseUsageFromShape(record.payload.info?.last_token_usage ?? record.payload.info?.total_token_usage);
if (!usage || usage.usageStatus !== 'available') {
return null;
}
return {
timestamp,
...(context.runtimeKind ? { runtimeKind: context.runtimeKind } : {}),
sessionId: context.sessionId,
agentId: context.agentId,
...(context.model ? { model: context.model } : {}),
provider: context.provider ?? 'codex',
...usage,
};
}
function usageContextWithJsonlMetadata(lines: string[], context: UsageParseContext): UsageParseContext {
let model = context.model;
let provider = context.provider;
for (const line of lines) {
let parsed: TranscriptLineShape;
try {
parsed = JSON.parse(line) as TranscriptLineShape;
} catch {
continue;
}
if (parsed.type !== 'session_meta' && parsed.type !== 'turn_context') continue;
const payload = parsed.payload as Record<string, unknown> | undefined;
if (!payload || typeof payload !== 'object') continue;
if (!model && typeof payload.model === 'string' && payload.model.trim()) {
model = payload.model.trim();
}
if (!provider && typeof payload.model_provider === 'string' && payload.model_provider.trim()) {
provider = payload.model_provider.trim();
}
if (model && provider) break;
}
return {
...context,
...(model ? { model } : {}),
...(provider ? { provider } : {}),
};
}
export function parseUsageEntriesFromMessages(
messages: unknown[],
context: UsageParseContext,
limit?: number,
): TokenUsageHistoryEntry[] {
const entries: TokenUsageHistoryEntry[] = [];
const maxEntries = typeof limit === 'number' && Number.isFinite(limit)
? Math.max(Math.floor(limit), 0)
: Number.POSITIVE_INFINITY;
for (let i = messages.length - 1; i >= 0 && entries.length < maxEntries; i -= 1) {
const item = messages[i];
if (!item || typeof item !== 'object' || Array.isArray(item)) continue;
const message = item as UsageMessageShape;
const timestamp = normalizeUsageTimestamp(message.timestamp ?? message.created_at ?? message.createdAt);
const entry = usageEntryFromMessage(message, timestamp, context);
if (entry) entries.push(entry);
}
return entries;
}
export function parseUsageEntriesFromJsonl(
content: string,
context: { sessionId: string; agentId: string },
context: UsageParseContext,
limit?: number,
): TokenUsageHistoryEntry[] {
const entries: TokenUsageHistoryEntry[] = [];
const lines = content.split(/\r?\n/).filter(Boolean);
const enrichedContext = usageContextWithJsonlMetadata(lines, context);
const maxEntries = typeof limit === 'number' && Number.isFinite(limit)
? Math.max(Math.floor(limit), 0)
: Number.POSITIVE_INFINITY;
@@ -276,54 +500,10 @@ export function parseUsageEntriesFromJsonl(
continue;
}
const message = parsed.message;
if (!message || !parsed.timestamp) {
continue;
}
if (message.role === 'assistant' && 'usage' in message) {
const usage = parseUsageFromShape(message.usage);
if (!usage) continue;
const contentText = normalizeUsageContent((message as Record<string, unknown>).content);
entries.push({
timestamp: parsed.timestamp,
sessionId: context.sessionId,
agentId: context.agentId,
model: message.model ?? message.modelRef,
provider: message.provider,
...(contentText ? { content: contentText } : {}),
...usage,
});
continue;
}
if (message.role !== 'toolResult') {
continue;
}
const details = message.details;
if (!details || !('usage' in details)) {
continue;
}
const usage = parseUsageFromShape(details.usage);
if (!usage) continue;
const provider = details.provider ?? details.externalContent?.provider ?? message.provider;
const model = details.model ?? message.model ?? message.modelRef;
const contentText = normalizeUsageContent(details.content)
?? normalizeUsageContent((message as Record<string, unknown>).content);
entries.push({
timestamp: parsed.timestamp,
sessionId: context.sessionId,
agentId: context.agentId,
model,
provider,
...(contentText ? { content: contentText } : {}),
...usage,
});
const timestamp = normalizeUsageTimestamp(parsed.timestamp);
const entry = usageEntryFromMessage(parsed.message, timestamp, enrichedContext)
?? usageEntryFromCodexTokenCount(parsed, timestamp, enrichedContext);
if (entry) entries.push(entry);
}
return entries;
+37 -8
View File
@@ -7,6 +7,7 @@ import {
parseUsageEntriesFromJsonl,
type TokenUsageHistoryEntry,
} from './token-usage-core';
import type { RuntimeKind } from '@shared/types/gateway';
import { listConfiguredAgentIds } from './agent-config';
export {
@@ -15,6 +16,14 @@ export {
type TokenUsageHistoryEntry,
} from './token-usage-core';
type RecentUsageSourceFile = {
filePath: string;
sessionId: string;
agentId: string;
mtimeMs: number;
source: 'openclaw-jsonl';
};
async function listAgentIdsWithSessionDirs(): Promise<string[]> {
const openclawDir = getOpenClawConfigDir();
const agentsDir = join(openclawDir, 'agents');
@@ -48,13 +57,13 @@ async function listAgentIdsWithSessionDirs(): Promise<string[]> {
return [...agentIds];
}
async function listRecentSessionFiles(): Promise<Array<{ filePath: string; sessionId: string; agentId: string; mtimeMs: number }>> {
async function listRecentSessionFiles(): Promise<RecentUsageSourceFile[]> {
const openclawDir = getOpenClawConfigDir();
const agentsDir = join(openclawDir, 'agents');
try {
const agentEntries = await listAgentIdsWithSessionDirs();
const files: Array<{ filePath: string; sessionId: string; agentId: string; mtimeMs: number }> = [];
const files: RecentUsageSourceFile[] = [];
for (const agentId of agentEntries) {
const sessionsDir = join(agentsDir, agentId, 'sessions');
@@ -72,6 +81,7 @@ async function listRecentSessionFiles(): Promise<Array<{ filePath: string; sessi
sessionId,
agentId,
mtimeMs: fileStat.mtimeMs,
source: 'openclaw-jsonl',
});
} catch {
continue;
@@ -89,21 +99,40 @@ async function listRecentSessionFiles(): Promise<Array<{ filePath: string; sessi
}
}
export async function getRecentTokenUsageHistory(limit?: number): Promise<TokenUsageHistoryEntry[]> {
const files = await listRecentSessionFiles();
export type TokenUsageHistoryOptions = {
limit?: number;
runtimeKind?: RuntimeKind;
};
function normalizeTokenUsageOptions(input?: number | TokenUsageHistoryOptions): TokenUsageHistoryOptions {
if (typeof input === 'number') return { limit: input };
return input ?? {};
}
function matchesRuntimeKind(file: RecentUsageSourceFile, runtimeKind?: RuntimeKind): boolean {
if (!runtimeKind) return true;
return runtimeKind === 'openclaw' && file.source === 'openclaw-jsonl';
}
export async function getRecentTokenUsageHistory(input?: number | TokenUsageHistoryOptions): Promise<TokenUsageHistoryEntry[]> {
const options = normalizeTokenUsageOptions(input);
if (options.runtimeKind === 'cc-connect') return [];
const files = (await listRecentSessionFiles())
.filter((file) => matchesRuntimeKind(file, options.runtimeKind))
.sort((a, b) => b.mtimeMs - a.mtimeMs);
const results: TokenUsageHistoryEntry[] = [];
const maxEntries = typeof limit === 'number' && Number.isFinite(limit)
? Math.max(Math.floor(limit), 0)
const maxEntries = typeof options.limit === 'number' && Number.isFinite(options.limit)
? Math.max(Math.floor(options.limit), 0)
: Number.POSITIVE_INFINITY;
for (const file of files) {
if (results.length >= maxEntries) break;
try {
const content = await readFile(file.filePath, 'utf8');
const entries = parseUsageEntriesFromJsonl(content, {
sessionId: file.sessionId,
agentId: file.agentId,
}, Number.isFinite(maxEntries) ? maxEntries - results.length : undefined);
runtimeKind: 'openclaw',
});
results.push(...entries);
} catch (error) {
logger.debug(`Failed to read token usage transcript ${file.filePath}:`, error);
@@ -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`, `fix-acp-directory-attachments`, `unify-acp-file-cards`
Related tasks: `acp-media-attachments`, `acp-attachment-open-with`, `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 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:
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:
- `workspace`: the canonical target is inside the active ACP workspace root. Relative references resolve from the registered execution cwd.
- `openclaw-media`: the canonical target is outside the workspace. This legacy scope name does not imply containment under an OpenClaw media root.
- `staging`: when a staging id is supplied, it must match the exact canonical file or selected directory in the Main-owned staging record. The same target may also resolve from an explicit path without claiming staging identity.
- `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.
- `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 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.
- Require an existing regular file and canonicalize the target. Symlink targets and files outside the workspace are allowed after canonical resolution.
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.
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.
## 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 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.
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.
Every attachment preview carries an attachment-scoped file reference. Preview components and rich viewers use the attachment text or binary read operations and must not fall back to a naked path or general workspace read. Attachment previews omit trusted workspace-browser reveal or folder actions.
The later shared-card implementation supersedes the original attachment-local card/menu ownership. `src/pages/Chat/AcpFileCard.tsx` now owns the common `AcpFileCard` shell and target-aware `AcpFileOpenWith` menu for distinct `attachment` and `workspace` references. This sharing is presentation only: attachment authorization remains session/generation scoped, while tool-derived file activity uses independently validated workspace-scoped operations. The two reference types must never be converted into each other. Eligible local HTML menus put an action first that opens the already-authorized target in the existing right-side Preview tab; this file-only preview path is separate from native attachment operations.
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.
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, 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.
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.
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.
+3 -10
View File
@@ -1,12 +1,12 @@
# ACP Chat Architecture And Timeline
Status: current architecture reference, reviewed 2026-08-05.
Status: current architecture reference, reviewed 2026-07-15.
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`, `render-cron-run-live-status`
Related tasks: `acp-native-chat`, `acp-media-attachments`, `filter-openclaw-heartbeat-session`
## Ownership
@@ -21,8 +21,6 @@ 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.
The only live assistant/process exception is the bounded cron overlay documented in `harness/reference/acp-cron-live-overlay.md`. Main accepts strict run-scoped cron identities only and keeps Gateway progress in a memory-only view model rendered beside, never inside, the ACP timeline. This exception is prohibited for ordinary non-cron messages, channel sessions, heartbeats, historical replay, and arbitrary Gateway content.
## Identity And Race Protection
Renderer-visible session identity is the OpenClaw Gateway session key. Main may hold a different ACP session id returned by `newSession`; it rewrites downstream routing to the matching Gateway session key. Loads on the shared ACP connection are serialized. A routing envelope carries the session key and the Main-owned generation token for the matching load or live prompt. Renderer uses a separate local request sequence to reject stale load completions; preparing a local-only session must not advance the ACP generation. Renderer ignores updates, permission requests, and asynchronous hydration results whose session or generation matches neither the selected session nor a retained live prompt. Generation is an in-memory race token rather than a durable sequence; Main may restore the previous value when a load fails, so code must compare it together with session and current-operation state rather than assume global monotonicity.
@@ -39,8 +37,6 @@ OpenClaw emits replay through ordinary `session/update` notifications and comple
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.
The cron live overlay is not a transcript-derived supplement or a third history source. Its exact Main bounds are 32 active runs, 128 items per run, 500000 assistant characters, 100000 characters per item detail, 256 sequence-less fingerprints per run, and 128 terminal tombstones. Renderer subscribes to typed changes before fetching the snapshot and rejects older revisions, so late hydration cannot overwrite newer state. Raw thinking text is never retained or shown; only a localized activity indicator is allowed.
## Timeline Model
The Renderer keeps an in-memory `AcpTimelineSnapshot` with ordered item ids, item records, open message segments, tool and permission state, and ACP metadata. The exact TypeScript types in `src/lib/acp/` are authoritative; the stable conceptual item kinds are:
@@ -95,8 +91,7 @@ Available attachment cards contain a primary semantic action with keyboard activ
- The primary Chat view does not render the legacy Execution Graph.
- 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.
- External cron activity never enters ACP sending/cancelling state or exposes ACP Stop, cancellation, or permission controls. When a terminal removal belongs to a run rendered in the currently selected base cron session, Renderer removes the overlay and calls normal `loadAcpSession` exactly once; hidden, evicted, gateway-reset, or already acknowledged removals cannot trigger a delayed reload. The resulting ACP replay, with typed cron-history fallback only when replay is empty, is the completed-content authority.
- 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.
- 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.
- 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
@@ -104,5 +99,3 @@ Available attachment cards contain a primary semantic action with keyboard activ
Key tests live in `tests/unit/acp-*.test.*`, `tests/unit/acp-timeline-groups.test.ts`, `tests/unit/attachment-access.test.ts`, `tests/unit/chat-question-directory.test.tsx`, `tests/e2e/chat-acp-inline-timeline.spec.ts`, and `tests/e2e/chat-acp-attachments.spec.ts`.
This reference consolidates the former ACP native Chat, Chat polish, turn grouping, and question-directory design documents. Later implementation decisions supersede the original no-optimistic-message rule, the assumption that ACP id always equals Gateway session key, and segment-level assistant copy controls.
The cron broker and overlay may be removed only after a distributed OpenClaw package proves through integration tests that loaded ACP sessions receive autonomous cron assistant, thought, and tool updates; generated media arrives as standard ACP content blocks; replay is complete and deduplicated; and external-run lifecycle and cancellation semantics are explicitly exposed. Until all four conditions hold, Gateway progress remains a separate transient authority rather than synthetic ACP.
@@ -1,88 +0,0 @@
# ACP Cron Live Overlay
Status: approved architecture contract, reviewed 2026-08-05.
Related scenarios: `gateway-backend-communication`, `acp-chat-experience`
Related rules: `acp-chat-state-and-history`, `acp-compatibility-content-safety`, `renderer-main-boundary`, `host-api-fallback-policy`, `host-events-fallback-policy`, `ui-i18n-design-tokens`
Related task: `render-cron-run-live-status`
## Authority And Purpose
ACP `session/load` replay remains the primary authority for historical Chat content. When ACP replay for a cron session is empty, the existing typed cron-history fallback remains the only approved historical projection. Gateway runtime events are neither history nor ACP evidence for reconstructing history.
ClawX may expose current progress for an autonomous cron run through one narrow exception: a bounded, Main-owned, running-only overlay composed beside the ACP timeline. It exists only to bridge the upstream period in which autonomous cron activity emits useful Gateway runtime events but does not arrive as complete live ACP updates.
The normative flow is:
```text
Gateway runtime event -> Main bounded cron broker -> explicit live overlay
terminal event -> overlay removal -> authoritative ACP/cron-history reload
```
The overlay is non-historical, memory-only, run-scoped, read-only, and excluded from sidebar unread/busy authority. It is not an `AcpTimelineSnapshot` supplement and cannot survive a terminal event, Gateway reset, broker eviction, process exit, or application restart.
## Admission And Identity
Main accepts only strict run-scoped cron keys shaped as `agent:<agentId>:cron:<jobId>:run:<runSessionId>`, with every identity segment non-empty after trimming. Ordinary sessions, base-only cron keys, channel sessions, malformed suffixes, and heartbeat `:main` events are rejected.
Main is the sole owner of cron key parsing and canonicalization. It maps an admitted run to its exact base cron key for selection while retaining the source run key and run identity. Renderer may select snapshots for the exact current base key, but it must not parse keys, adopt arbitrary runtime sessions, reduce Gateway events, choose transports, or implement protocol fallback.
Every process-item identity is namespaced by `runId`. Repeated `toolCallId`, `itemId`, command names, or approval fallback identities from different runs cannot collide.
## Main Broker Contract
The broker owns runtime-event normalization, type-specific deduplication, reduction, ordering, active snapshots, terminal tombstones, and all memory bounds. It may adopt a valid run mid-flight without observing `run.started`, but a terminal tombstone prevents delayed events from resurrecting a completed run only while that tombstone remains in the bounded FIFO. Gateway reset removals do not create terminal tombstones: the Main binding disables ingestion before clearing, ignores runtime events while disconnected or reconnecting, and re-enables ingestion on `running` so the same identity can be adopted again mid-flight.
The exact bounds are:
- `MAX_ACTIVE_CRON_LIVE_RUNS = 32`
- `MAX_CRON_LIVE_ITEMS_PER_RUN = 128`
- `MAX_CRON_LIVE_ASSISTANT_CHARS = 500_000`
- `MAX_CRON_LIVE_ITEM_DETAIL_CHARS = 100_000`
- `MAX_CRON_LIVE_EVENT_FINGERPRINTS = 256` per run
- `MAX_CRON_LIVE_TERMINAL_TOMBSTONES = 128`
Numeric sequence values are monotonic per run; Main rejects `seq <= lastSeq`. Events without a sequence use bounded, type-specific fingerprints that reject exact repeats while preserving distinct incremental chunks. Structured details are serialized deterministically, tolerate cyclic input, and are truncated before entering the snapshot.
The overlay has only `running` status. Assistant text may be displayed, including bounded snapshot, replacement, and delta convergence. `thinking.delta` content is never retained or displayed; the view model exposes only a boolean that Renderer presents as a localized thinking indicator. Tool, command, patch, and approval items are bounded status rows. Approval rows are read-only and never call ACP permission-response APIs.
Terminal events produce a removal and delete the active snapshot. Renderer applies that removal to its overlay state before starting any authoritative history reload. Terminal content is never retained as a completed overlay. Gateway reset and deterministic capacity eviction also remove snapshots, but do not claim that authoritative history changed.
## Revision And Hydration Safety
Main emits a monotonically increasing broker revision for every upsert, removal, and clear. Every upsert snapshot carries the revision of its emitted change. Snapshot hydration returns the current broker revision even when no active snapshots exist.
Renderer subscribes to the typed change event before requesting the typed snapshot. It applies changes and hydration only when their revision is not older than the current store revision. This ordering prevents a late snapshot response, including an empty response, from replacing newer live events in the subscribe/snapshot revision race. Renderer bounds pending removals and acknowledges each removal by its exact revision so concurrent run completions cannot overwrite one another.
The supported boundary is:
```text
GatewayManager -> Main cron live-run broker -> typed host event / typed host API
Renderer overlay store -> explicit cron overlay component beside ACP timeline
```
No page or component may invoke IPC directly, fetch Gateway HTTP, open a Gateway WebSocket, or switch between transports. Existing raw `chat:runtime-event` forwarding remains unchanged for the legacy runtime graph and image-generation compatibility consumers; broker ingestion is a separate Main listener and must not duplicate raw forwarding.
## ACP And UI Separation
Gateway runtime events must never be converted into `SessionNotification`, `AcpSessionUpdateEnvelope`, `TimelineItem`, or any other synthetic ACP value. `src/lib/acp/reducer.ts`, `src/lib/acp/timeline-types.ts`, and ACP replay semantics remain unchanged. The overlay is rendered as a sibling region and its content never appears inside the ACP timeline DOM.
External cron activity cannot set ACP `sending` or `cancelling`, show Stop, call `cancelAcpSession`, respond to ACP permissions, synthesize a generation, or mutate a retained live prompt. It also cannot create, clear, or reconcile sidebar busy or unread state; Gateway session rows remain the sole sidebar authority.
When a terminal removal identifies a run that was actually rendered for the currently selected base cron session, Renderer keeps that removal pending while an ACP prompt is sending or cancelling, then acknowledges the exact removal and invokes normal `loadAcpSession` exactly once after the ACP lifecycle and existing workspace/load coordination permit it. The resulting ACP replay is authoritative. Only if that replay is empty may the existing typed cron-history fallback populate historical content. A run removed while hidden, an already acknowledged removal, or a removal for `evicted` or `gateway-reset` does not create a delayed reload when the user later returns. Sequence-less and repeated terminal events are suppressed while the corresponding bounded FIFO tombstone is retained, so they cannot duplicate the reload or resurrect the run during that retention window.
The panel and every status label use `react-i18next` with English, Chinese, Japanese, and Russian coverage. Presentation follows `src/styles/globals.css`, including semantic modal/input surfaces, selected-state substitutions, paired light/dark status colors, accessible labels, and reduced-motion behavior. The live panel must be visibly distinct from native ACP cards and the removed legacy Execution Graph.
## Scope And Removal Condition
This exception cannot be generalized to ordinary non-cron messages, channel sessions, heartbeats, historical event replay, or arbitrary Gateway content. It must remain simpler to delete than to expand.
The overlay may be removed only after a distributed OpenClaw package proves through integration tests that loaded ACP sessions receive autonomous cron assistant, thought, and tool updates; generated media arrives as standard ACP content blocks; replay is complete and deduplicated; and external-run lifecycle and cancellation semantics are explicitly exposed. At that point ClawX should remove the broker and overlay rather than retain two live authorities.
## Validation Anchors
Contract validation begins with `tests/unit/harness-specs.test.ts`. Broker identity and reduction are covered by `tests/unit/cron-session-utils.test.ts`, `tests/unit/gateway-event-dispatch.test.ts`, and `tests/unit/cron-live-run-broker.test.ts`. Typed boundaries and revision-safe Renderer state are covered by `tests/unit/host-events.test.ts`, `tests/unit/host-api-facade.test.ts`, `tests/unit/host-services.test.ts`, and `tests/unit/cron-live-run-overlay-store.test.ts`. Presentation and ACP separation are covered by `tests/unit/cron-live-run-overlay.test.tsx`, `tests/unit/chat-acp-page.test.tsx`, and `tests/e2e/cron-run-live-status.spec.ts`.
Communication changes require type checking, lint, Vite build, the focused Electron E2E spec, `pnpm run comms:replay`, `pnpm run comms:compare`, real task-spec validation without `--no-diff`, a task Harness run, and Harness CI.
@@ -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 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.
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.
Both content exceptions use one bounded transcript fetch coordinator, keep projected state in memory, require exact active session and generation identity, and reject stale or ambiguous evidence. Existing-session load reads at most 1000 recent transcript messages. An ordinary successful live prompt performs one immediate read and one retry 1500 milliseconds later. Only an `image_generate` task recorded for that same live prompt extends the coordinator through bounded backoff while waiting for its completion artifact; accepted completion, invalidation, or retry-window exhaustion stops it. These exceptions must be removed when the distributed OpenClaw ACP adapter emits the equivalent standard content.
The same historical coordinator may request metadata-only whole-turn timing from Main. This is necessary because ACP `session/load` supplies replay content and status but not the original timestamps needed to calculate duration. Main derives candidates from bounded transcript JSONL envelopes, and Renderer aligns them with the same normalized user text and duplicate occurrence-from-tail rule. Timing can annotate only an ACP-created turn and never recovers transcript content.
Transcript supplementation must not recover or reconstruct ordinary assistant messages, thoughts, tools, plans, permissions, file activity, or a parallel Chat history. Bare paths and inline prose paths without canonical media facts, unknown URI schemes, incidental tool paths, and directives inside fenced code blocks are not general attachments.
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.
### Image-Generation Completion
@@ -40,13 +40,11 @@ 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.
### Canonical And Explicit MEDIA Attachments
### Explicit MEDIA Attachments
The general attachment extractor considers normalized assistant roles only. Its preferred transcript evidence is OpenClaw's canonical persisted `__openclaw.media` array. Each fact may contribute one ordered `path` or `url` plus bounded filename, content type, and size metadata; the containing assistant message id is retained for Main-side outgoing-record validation. Canonical facts do not authorize access: every reference and metadata value remains untrusted and passes through the existing Main attachment boundary.
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.
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.
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.
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.
@@ -66,13 +64,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 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.
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.
These are the only transcript-derived Chat content supplements. Metadata-only whole-turn timing is also permitted, but it must not become a general recovery mechanism for missing turns, tool cards, file activity, plans, permissions, thoughts, or ordinary messages.
## Rejected Compatibility Alternatives
Main does not manufacture ACP `agent_message_chunk` resource events from transcript evidence because that would misrepresent compatibility data as native protocol replay. The ACP page does not reuse legacy Chat path extraction or rendering because that would restore competing history authorities. Standard-ACP-only behavior is insufficient while the distributed adapter omits assistant media, but the exception remains removable when upstream emits standard resources. Canonical persisted media facts are explicit structured evidence; bare-path or broad prose extraction without those facts remains rejected because false positives would widen the local-file trust surface.
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.
## 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 Local HTML Preview
## Workspace Browser And Web Browser
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.
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.
File icons come only from trusted bundled assets. Selecting a file preserves the existing preview behavior and backend boundary.
Local HTML Preview uses one hardened Electron guest as an implementation detail. The HTML anchor marks the Preview body while the route-stable host mounted by `MainLayout` owns the guest. There is no browser tab, empty guest entry, Home page, or address bar. Stable selectors are `html-preview-anchor`, `html-preview-host`, and `html-preview-webview`. Its file-only security and inert-link contract is documented separately in `harness/reference/web-browser.md`.
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`.
## 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/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`.
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`.
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.
+2 -8
View File
@@ -135,12 +135,6 @@ 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:
@@ -158,7 +152,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, 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.
- PPTX thumbnails, keyboard shortcuts, animation, transitions, media playback, fullscreen, presenter mode, or automatic slide shows.
- 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.
@@ -194,4 +188,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, viewport-filling Preview transitions, 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, the single-mounted-viewer invariant, Host API read routes, and absence of legacy direct IPC.
+153 -24
View File
@@ -1,40 +1,169 @@
# Local HTML Preview Architecture
# Web Browser
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.
Status: implemented contract, reviewed 2026-07-23.
## User flow
Related scenarios: `gateway-backend-communication`, `chat-workspace-and-navigation`
- 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 rule: `web-browser-security-and-lifecycle`
## Link behavior
Related task: `web-browser`
All links are inert:
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.
- 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.
## Scope And Non-Goals
## Renderer flow
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.
HTML entry points build an ordinary `FilePreviewTarget` and call `useArtifactPanel.openPreview`. `FilePreviewBody` renders an HTML anchor in Preview. The route-stable host in `MainLayout` overlays one webview on that anchor and asks `hostApi.webBrowser.navigate` to load the selected file.
The 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.
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.
## Trust Model And Ownership
## Main boundary
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.
`normalizeWebBrowserHtmlFileUrl` accepts only hostless, query-free, fragment-free `file:///` URLs ending in `.html` or `.htm`. The Host API has only:
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()`.
- `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.
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.
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.
## Identity And Session
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.
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:
## Security consequence
```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
```
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.
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.
@@ -10,8 +10,6 @@ appliesTo:
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.
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. 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.
The sole live Gateway exception for cron assistant/process progress is a bounded, Main-reduced overlay for strict run-scoped cron keys. It is memory-only, running-only, read-only, and structurally separate from `SessionNotification`, `AcpSessionUpdateEnvelope`, `TimelineItem`, and `AcpTimelineSnapshot`; it cannot create or supplement history. A terminal event removes the overlay, after which a visible run may trigger exactly one ordinary ACP load or existing typed cron-history fallback. ACP replay remains the authority whenever it is non-empty. The overlay cannot mutate ACP sending, cancelling, Stop, permission, generation, or replay state, and it cannot drive sidebar busy or unread authority. Do not extend this exception to ordinary sessions, base-only cron keys, channels, or heartbeats. See `harness/reference/acp-cron-live-overlay.md`.
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. 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 come from 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. 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,8 +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 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.
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.
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.
A bounded live cron overlay is not compatibility ACP content. It may display current assistant text and read-only process status from strict run-scoped Gateway events only as a separately typed, memory-only, running-only view model. Raw thought text is prohibited, approval rows are never interactive ACP permissions, and no overlay value may be represented as a native or synthetic ACP event, inserted into the ACP timeline, persisted, or retained after terminal removal. Completed content must come from ordinary ACP replay or the existing typed cron-history fallback. This narrow exception must not become a route for ordinary messages, historical reconstruction, or replacement of standard ACP content. See `harness/reference/acp-cron-live-overlay.md`.
@@ -15,6 +15,4 @@ 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
- 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 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.
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.
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.
@@ -0,0 +1,102 @@
---
id: cc-connect-runtime-validation
title: cc-connect Replacement Runtime Validation
type: ai-coding-rule
appliesTo:
- gateway-backend-communication
requiredProfiles:
- fast
- comms
requiredTests:
- pnpm run verify:runtime-bundles
- pnpm run verify:packaged-runtime-resources -- --resources=<target-resources> --platform=<target-platform> --arch=<target-arch>
- pnpm run test:e2e:cc-connect
---
cc-connect runtime changes must preserve one execution boundary: Renderer calls
Host API, Host API calls `RuntimeManager`, and `CcConnectRuntimeProvider` talks
to cc-connect Bridge or Management API. Codex is only a cc-connect child.
Rules:
- ClawX must not spawn Codex or invoke Codex session/chat commands in
cc-connect mode.
- Production chat events, tools, approvals, cancellation, session history, and
usage must come from cc-connect public APIs/events. Codex transcripts may be
test oracles but not production transports.
- Approval, question, and runtime-choice responses must use cc-connect's public
Bridge `card_action` packet and validate against actions offered for the
pending run. A returned select-state card may close the Chat run; navigation
and button cards remain interactive until cc-connect emits a terminal reply,
the user chooses a select state, or the run aborts.
- Proactive runtime media must enter through cc-connect's public Bridge packets.
Host history must preserve every image/file/audio/video attachment, final-event
deduplication must distinguish packet message ids, and execution-graph folding
must not hide runtime-owned `gateway-media` cards.
- Chat cancellation must use cc-connect's public session-scoped `/stop` command
over Bridge. The normal path must close the selected Codex child without
restarting cc-connect; a whole-runtime restart is allowed only when Bridge is
disconnected and the stop command cannot be delivered.
- Agent permission mode must be stored in ClawX-owned runtime metadata, default
to `full-auto`, expose only `full-auto` and `suggest`, and project `suggest`
into the matching cc-connect project without mutating OpenClaw config.
- Managed Codex projects must select cc-connect's `app_server` backend over
`stdio://`; the default `exec` backend is not sufficient evidence for Codex
0.137 custom tool lifecycle parity.
- ClawX must not write cc-connect private session JSON. Unsupported official
mutations remain unsupported or use ClawX logical display metadata.
- cc-connect mode must not mutate OpenClaw config. Existing OpenClaw workspaces
may be referenced as external Agent workspaces.
- New ClawX state belongs under `~/.clawx` through the shared data-layout API.
Runtime code must not derive durable paths from `process.cwd()` or scattered
`app.getPath('userData')` calls.
- Provider bindings are account-specific. OAuth accounts use independent
complete `CODEX_HOME` directories; API keys and OAuth recovery material are
encrypted and never returned to Renderer.
- GUI and Channel Cron operate one cc-connect native scheduler. ClawX must not
emulate `at`, `every`, or scheduled prompts in a second scheduler.
- Tool events must include stable run, turn, event, sequence, session, Agent,
and project identity. Reconnect/replay must not duplicate cards.
- Bridge text previews must render the initial `preview_start`, replace content
on `update_message`, and clear transient text on `delete_message`. Structured
progress deletion must not erase semantic thinking/tool lifecycle from the
shared execution graph.
- Cached input is part of input and reasoning is part of output. Usage totals
must not add either category twice.
- When public cc-connect history exposes a turn without counters, Host API must
return an explicit `missing` usage record for that turn; it must not estimate
counts from cc-connect private state or Codex transcripts.
- Feishu/Lark parity requires a real inbound marker and real outbound reply
through cc-connect, not only config projection or connected status.
- Every user-visible change must include Electron E2E and all locale files.
- Mock, local-real, external-credential, and packaged evidence are separate
rows. One tier must not be used to claim another.
- Packaging must verify both the downloaded bundle and the copied Electron
resources. `afterPack` enforces exact manifest/SHA/permission checks before
signing. Final Windows/Linux resources keep exact SHA equality; signed macOS
resources must match the source bundle's Mach-O section payloads and pass
strict code-signature verification.
- Evidence reports and screenshots must be sanitized. API keys, OAuth tokens,
app secrets, management/bridge tokens, and Authorization headers must never
be written to artifacts or git.
- Replacement readiness stays PARTIAL while any required real-runtime row is
skipped, not run, failed, or only indirectly covered.
Minimum required scenarios:
1. OpenClaw remains the default and rollback path.
2. cc-connect starts from packaged resources with no runtime download.
3. Real API-key and OAuth GUI chat pass through Bridge; a real OAuth native tool
turn shows the execution graph from cc-connect progress-card events.
4. Two Agents with different accounts and workspaces do not cross-contaminate.
5. Named, cross-Agent, Channel, restart, rename, and hard-delete sessions use
public runtime APIs.
6. Usage is per-turn, deduplicated, and attributable to runtime, Agent, account,
model, and logical session.
7. Feishu/Lark inbound, response, session, and usage attribution pass.
8. Channel and GUI native Cron mutations are bidirectionally visible and a
scheduled response returns to the Channel.
9. Doctor, logs, health, crash recovery, port collision, and single-writer lock
produce real evidence.
10. macOS, Windows, and Linux packaged resources/startup/cleanup are checked
before release readiness.
@@ -24,6 +24,4 @@ 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`.
@@ -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 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.
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.
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.
+3 -5
View File
@@ -17,10 +17,8 @@ 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. 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.
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.
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.
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.
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.
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.
@@ -1,25 +1,28 @@
---
id: web-browser-security-and-lifecycle
title: Local HTML preview security and lifecycle
title: Web Browser Security And Lifecycle
type: ai-coding-rule
appliesTo:
- 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
- gateway-backend-communication
- chat-workspace-and-navigation
requiredProfiles:
- e2e
---
# Local HTML preview security and lifecycle
`harness/reference/web-browser.md` is the authoritative implemented contract and rationale. Changes in this area must preserve these enforceable invariants:
- 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.
- 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.
+2 -10
View File
@@ -5,8 +5,6 @@ type: user-visible-flow
ownedPaths:
- shared/acp-chat/**
- shared/host-api/contract.ts
- shared/host-events/contract.ts
- shared/chat/cron-live-run.ts
- shared/file-preview/**
- electron/services/acp-chat-service.ts
- electron/services/acp-session-access-registry.ts
@@ -29,10 +27,6 @@ ownedPaths:
- tests/e2e/chat-acp-inline-timeline.spec.ts
- tests/e2e/chat-acp-attachments.spec.ts
- tests/e2e/chat-run-state-events.spec.ts
- src/stores/cron-live-run-overlay.ts
- tests/unit/cron-live-run-overlay-store.test.ts
- tests/unit/cron-live-run-overlay.test.tsx
- tests/e2e/cron-run-live-status.spec.ts
requiredProfiles:
- fast
- comms
@@ -54,10 +48,8 @@ requiredRules:
- 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 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.
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.
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.
An externally triggered cron run may appear only as the separate, bounded, running-only overlay documented in `harness/reference/acp-cron-live-overlay.md`. Gateway runtime events never become ACP notifications or timeline items. The overlay is read-only and cannot own ACP sending, cancellation, permissions, replay, history, or sidebar attention; terminal content becomes visible only through an authoritative ACP or typed cron-history reload after overlay removal.
The durable architecture, exceptions, access boundary, file-activity separation, Office preview behavior, cron live-overlay boundary, 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`, and `harness/reference/acp-cron-live-overlay.md`.
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`.
+1 -1
View File
@@ -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 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.
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.
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`.

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